prompt
stringclasses
1 value
completions
listlengths
1
63.8k
labels
listlengths
1
63.8k
source
stringclasses
1 value
other_info
stringlengths
2.06k
101k
index
int64
0
6.83k
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n* ECC Domain Parameters\n*\n* (C) 2007 Falko Strenzke, FlexSecure GmbH\n* 2008-2010 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*/", "#ifndef BOTAN_ECC_DOMAIN_PARAMETERS_H_\n#define BOTAN_ECC_DOMAIN_PARAMETERS_H_", "#include <botan/point_gfp.h>\n#include <botan/asn1_oid.h>\n#include <memory>\n#include <set>", "namespace Botan {", "/**\n* This class represents elliptic curce domain parameters\n*/\nenum EC_Group_Encoding {\n EC_DOMPAR_ENC_EXPLICIT = 0,\n EC_DOMPAR_ENC_IMPLICITCA = 1,\n EC_DOMPAR_ENC_OID = 2\n};", "class CurveGFp;", "class EC_Group_Data;\nclass EC_Group_Data_Map;", "/**\n* Class representing an elliptic curve\n*\n* The internal representation is stored in a shared_ptr, so copying an\n* EC_Group is inexpensive.\n*/\nclass BOTAN_PUBLIC_API(2,0) EC_Group final\n {\n public:", " /**\n * Construct Domain paramers from specified parameters\n * @param curve elliptic curve\n * @param base_point a base point\n * @param order the order of the base point\n * @param cofactor the cofactor\n */\n BOTAN_DEPRECATED(\"Use version taking all BigInts\")\n EC_Group(const CurveGFp& curve,\n const PointGFp& base_point,\n const BigInt& order,\n const BigInt& cofactor) :\n EC_Group(curve.get_p(),\n curve.get_a(),\n curve.get_b(),\n base_point.get_affine_x(),\n base_point.get_affine_y(),\n order,\n cofactor) {}", " /**\n * Construct Domain paramers from specified parameters\n * @param p the elliptic curve p\n * @param a the elliptic curve a param\n * @param b the elliptic curve b param\n * @param base_x the x coordinate of the base point\n * @param base_y the y coordinate of the base point\n * @param order the order of the base point\n * @param cofactor the cofactor\n * @param oid an optional OID used to identify this curve\n */\n EC_Group(const BigInt& p,\n const BigInt& a,\n const BigInt& b,\n const BigInt& base_x,\n const BigInt& base_y,\n const BigInt& order,\n const BigInt& cofactor,\n const OID& oid = OID());", " /**\n * Decode a BER encoded ECC domain parameter set\n * @param ber_encoding the bytes of the BER encoding\n */\n explicit EC_Group(const std::vector<uint8_t>& ber_encoding);", " /**\n * Create an EC domain by OID (or throw if unknown)\n * @param oid the OID of the EC domain to create\n */\n explicit EC_Group(const OID& oid);", " /**\n * Create an EC domain from PEM encoding (as from PEM_encode), or\n * from an OID name (eg \"secp256r1\", or \"1.2.840.10045.3.1.7\")\n * @param pem_or_oid PEM-encoded data, or an OID\n */\n explicit EC_Group(const std::string& pem_or_oid);", " /**\n * Create an uninitialized EC_Group\n */\n EC_Group();", " ~EC_Group();", " /**\n * Create the DER encoding of this domain\n * @param form of encoding to use\n * @returns bytes encododed as DER\n */\n std::vector<uint8_t> DER_encode(EC_Group_Encoding form) const;", " /**\n * Return the PEM encoding (always in explicit form)\n * @return string containing PEM data\n */\n std::string PEM_encode() const;", " /**\n * Return domain parameter curve\n * @result domain parameter curve\n */\n BOTAN_DEPRECATED(\"Avoid CurveGFp\") const CurveGFp& get_curve() const;", " /**\n * Return if a == -3 mod p\n */\n bool a_is_minus_3() const;", " /**\n * Return if a == 0 mod p\n */\n bool a_is_zero() const;", " /**\n * Return the size of p in bits (same as get_p().bits())\n */\n size_t get_p_bits() const;", " /**\n * Return the size of p in bits (same as get_p().bytes())\n */\n size_t get_p_bytes() const;", " /**\n * Return the size of group order in bits (same as get_order().bits())\n */\n size_t get_order_bits() const;", " /**\n * Return the size of p in bytes (same as get_order().bytes())\n */\n size_t get_order_bytes() const;", " /**\n * Return the prime modulus of the field\n */\n const BigInt& get_p() const;", " /**\n * Return the a parameter of the elliptic curve equation\n */\n const BigInt& get_a() const;", " /**\n * Return the b parameter of the elliptic curve equation\n */\n const BigInt& get_b() const;", " /**\n * Return group base point\n * @result base point\n */\n const PointGFp& get_base_point() const;", " /**\n * Return the x coordinate of the base point\n */\n const BigInt& get_g_x() const;", " /**\n * Return the y coordinate of the base point\n */\n const BigInt& get_g_y() const;", " /**\n * Return the order of the base point\n * @result order of the base point\n */\n const BigInt& get_order() const;", " /*\n * Reduce x modulo the order\n */\n BigInt mod_order(const BigInt& x) const;", " /*\n * Return inverse of x modulo the order\n */\n BigInt inverse_mod_order(const BigInt& x) const;", " /*", "", " * Reduce (x*y) modulo the order\n */\n BigInt multiply_mod_order(const BigInt& x, const BigInt& y) const;", "", "\n /**\n * Return the cofactor\n * @result the cofactor\n */\n const BigInt& get_cofactor() const;", " /**\n * Check if y is a plausible point on the curve\n *\n * In particular, checks that it is a point on the curve, not infinity,\n * and that it has order matching the group.\n */\n bool verify_public_element(const PointGFp& y) const;", " /**\n * Return the OID of these domain parameters\n * @result the OID as a string\n */\n std::string BOTAN_DEPRECATED(\"Use get_curve_oid\") get_oid() const { return get_curve_oid().as_string(); }", " /**\n * Return the OID of these domain parameters\n * @result the OID\n */\n const OID& get_curve_oid() const;", " /**\n * Return a point on this curve with the affine values x, y\n */\n PointGFp point(const BigInt& x, const BigInt& y) const;", " /**\n * Multi exponentiate. Not constant time.\n * @return base_point*x + pt*y\n */\n PointGFp point_multiply(const BigInt& x, const PointGFp& pt, const BigInt& y) const;", " /**\n * Blinded point multiplication, attempts resistance to side channels\n * @param k the scalar\n * @param rng a random number generator\n * @param ws a temp workspace\n * @return base_point*k\n */\n PointGFp blinded_base_point_multiply(const BigInt& k,\n RandomNumberGenerator& rng,\n std::vector<BigInt>& ws) const;", " /**\n * Blinded point multiplication, attempts resistance to side channels\n * Returns just the x coordinate of the point\n *\n * @param k the scalar\n * @param rng a random number generator\n * @param ws a temp workspace\n * @return x coordinate of base_point*k\n */\n BigInt blinded_base_point_multiply_x(const BigInt& k,\n RandomNumberGenerator& rng,\n std::vector<BigInt>& ws) const;", " /**\n * Blinded point multiplication, attempts resistance to side channels\n * @param point input point\n * @param k the scalar\n * @param rng a random number generator\n * @param ws a temp workspace\n * @return point*k\n */\n PointGFp blinded_var_point_multiply(const PointGFp& point,\n const BigInt& k,\n RandomNumberGenerator& rng,\n std::vector<BigInt>& ws) const;", " /**\n * Return a random scalar ie an integer in [1,order)\n */\n BigInt random_scalar(RandomNumberGenerator& rng) const;", " /**\n * Return the zero (or infinite) point on this curve\n */\n PointGFp zero_point() const;", " PointGFp OS2ECP(const uint8_t bits[], size_t len) const;", " template<typename Alloc>\n PointGFp OS2ECP(const std::vector<uint8_t, Alloc>& vec) const\n {\n return this->OS2ECP(vec.data(), vec.size());\n }", " bool initialized() const { return (m_data != nullptr); }", " /**\n * Verify EC_Group domain\n * @returns true if group is valid. false otherwise\n */\n bool verify_group(RandomNumberGenerator& rng,\n bool strong = false) const;", " bool operator==(const EC_Group& other) const;", " /**\n * Return PEM representation of named EC group\n * Deprecated: Use EC_Group(name).PEM_encode() if this is needed\n */\n static std::string BOTAN_DEPRECATED(\"See header comment\") PEM_for_named_group(const std::string& name);", " /**\n * Return a set of known named EC groups\n */\n static const std::set<std::string>& known_named_groups();", " /*\n * For internal use only\n */\n static std::shared_ptr<EC_Group_Data> EC_group_info(const OID& oid);", " static size_t clear_registered_curve_data();", " private:\n static EC_Group_Data_Map& ec_group_data();", " static std::shared_ptr<EC_Group_Data> BER_decode_EC_group(const uint8_t bits[], size_t len);", " static std::shared_ptr<EC_Group_Data>\n load_EC_group_info(const char* p,\n const char* a,\n const char* b,\n const char* g_x,\n const char* g_y,\n const char* order,\n const OID& oid);", " // Member data\n const EC_Group_Data& data() const;\n std::shared_ptr<EC_Group_Data> m_data;\n };", "inline bool operator!=(const EC_Group& lhs,\n const EC_Group& rhs)\n {\n return !(lhs == rhs);\n }", "// For compatibility with 1.8\ntypedef EC_Group EC_Domain_Params;", "}", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [19, 202, 482, 209, 237], "buggy_code_start_loc": [19, 77, 86, 206, 54], "filenames": ["doc/security.rst", "src/lib/pubkey/dsa/dsa.cpp", "src/lib/pubkey/ec_group/ec_group.cpp", "src/lib/pubkey/ec_group/ec_group.h", "src/lib/pubkey/ecdsa/ecdsa.cpp"], "fixing_code_end_loc": [28, 220, 503, 220, 252], "fixing_code_start_loc": [20, 77, 87, 207, 54], "message": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:botan_project:botan:*:*:*:*:*:*:*:*", "matchCriteriaId": "416ED13A-040B-4ED0-ACAD-9EC53C2EBE6C", "versionEndExcluding": null, "versionEndIncluding": "2.7.0", "versionStartExcluding": null, "versionStartIncluding": "2.5.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host."}, {"lang": "es", "value": "Botan versi\u00f3n 2.5.0 hasta 2.6.0 anterior a 2.7.0, permite un ataque de canal lateral de memoria cach\u00e9 en firmas ECDSA, tambi\u00e9n se conoce como Problema del Retorno de N\u00famero Oculto o ROHNP, relacionado con los archivos dsa/dsa.cpp, ec_group/ec_group.cpp, y ecdsa/ecdsa.cpp. Para descubrir una clave ECDSA, el atacante requiere acceso a la m\u00e1quina local o a una m\u00e1quina virtual diferente en el mismo host f\u00edsico."}], "evaluatorComment": null, "id": "CVE-2018-12435", "lastModified": "2018-08-22T19:57:41.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 1.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:N/UI:N/S:C/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 1.4, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-15T02:29:00.377", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://botan.randombit.net/security.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.nccgroup.trust/us/our-research/technical-advisory-return-of-the-hidden-number-problem/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, "type": "CWE-200"}
20
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n* ECC Domain Parameters\n*\n* (C) 2007 Falko Strenzke, FlexSecure GmbH\n* 2008-2010 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*/", "#ifndef BOTAN_ECC_DOMAIN_PARAMETERS_H_\n#define BOTAN_ECC_DOMAIN_PARAMETERS_H_", "#include <botan/point_gfp.h>\n#include <botan/asn1_oid.h>\n#include <memory>\n#include <set>", "namespace Botan {", "/**\n* This class represents elliptic curce domain parameters\n*/\nenum EC_Group_Encoding {\n EC_DOMPAR_ENC_EXPLICIT = 0,\n EC_DOMPAR_ENC_IMPLICITCA = 1,\n EC_DOMPAR_ENC_OID = 2\n};", "class CurveGFp;", "class EC_Group_Data;\nclass EC_Group_Data_Map;", "/**\n* Class representing an elliptic curve\n*\n* The internal representation is stored in a shared_ptr, so copying an\n* EC_Group is inexpensive.\n*/\nclass BOTAN_PUBLIC_API(2,0) EC_Group final\n {\n public:", " /**\n * Construct Domain paramers from specified parameters\n * @param curve elliptic curve\n * @param base_point a base point\n * @param order the order of the base point\n * @param cofactor the cofactor\n */\n BOTAN_DEPRECATED(\"Use version taking all BigInts\")\n EC_Group(const CurveGFp& curve,\n const PointGFp& base_point,\n const BigInt& order,\n const BigInt& cofactor) :\n EC_Group(curve.get_p(),\n curve.get_a(),\n curve.get_b(),\n base_point.get_affine_x(),\n base_point.get_affine_y(),\n order,\n cofactor) {}", " /**\n * Construct Domain paramers from specified parameters\n * @param p the elliptic curve p\n * @param a the elliptic curve a param\n * @param b the elliptic curve b param\n * @param base_x the x coordinate of the base point\n * @param base_y the y coordinate of the base point\n * @param order the order of the base point\n * @param cofactor the cofactor\n * @param oid an optional OID used to identify this curve\n */\n EC_Group(const BigInt& p,\n const BigInt& a,\n const BigInt& b,\n const BigInt& base_x,\n const BigInt& base_y,\n const BigInt& order,\n const BigInt& cofactor,\n const OID& oid = OID());", " /**\n * Decode a BER encoded ECC domain parameter set\n * @param ber_encoding the bytes of the BER encoding\n */\n explicit EC_Group(const std::vector<uint8_t>& ber_encoding);", " /**\n * Create an EC domain by OID (or throw if unknown)\n * @param oid the OID of the EC domain to create\n */\n explicit EC_Group(const OID& oid);", " /**\n * Create an EC domain from PEM encoding (as from PEM_encode), or\n * from an OID name (eg \"secp256r1\", or \"1.2.840.10045.3.1.7\")\n * @param pem_or_oid PEM-encoded data, or an OID\n */\n explicit EC_Group(const std::string& pem_or_oid);", " /**\n * Create an uninitialized EC_Group\n */\n EC_Group();", " ~EC_Group();", " /**\n * Create the DER encoding of this domain\n * @param form of encoding to use\n * @returns bytes encododed as DER\n */\n std::vector<uint8_t> DER_encode(EC_Group_Encoding form) const;", " /**\n * Return the PEM encoding (always in explicit form)\n * @return string containing PEM data\n */\n std::string PEM_encode() const;", " /**\n * Return domain parameter curve\n * @result domain parameter curve\n */\n BOTAN_DEPRECATED(\"Avoid CurveGFp\") const CurveGFp& get_curve() const;", " /**\n * Return if a == -3 mod p\n */\n bool a_is_minus_3() const;", " /**\n * Return if a == 0 mod p\n */\n bool a_is_zero() const;", " /**\n * Return the size of p in bits (same as get_p().bits())\n */\n size_t get_p_bits() const;", " /**\n * Return the size of p in bits (same as get_p().bytes())\n */\n size_t get_p_bytes() const;", " /**\n * Return the size of group order in bits (same as get_order().bits())\n */\n size_t get_order_bits() const;", " /**\n * Return the size of p in bytes (same as get_order().bytes())\n */\n size_t get_order_bytes() const;", " /**\n * Return the prime modulus of the field\n */\n const BigInt& get_p() const;", " /**\n * Return the a parameter of the elliptic curve equation\n */\n const BigInt& get_a() const;", " /**\n * Return the b parameter of the elliptic curve equation\n */\n const BigInt& get_b() const;", " /**\n * Return group base point\n * @result base point\n */\n const PointGFp& get_base_point() const;", " /**\n * Return the x coordinate of the base point\n */\n const BigInt& get_g_x() const;", " /**\n * Return the y coordinate of the base point\n */\n const BigInt& get_g_y() const;", " /**\n * Return the order of the base point\n * @result order of the base point\n */\n const BigInt& get_order() const;", " /*\n * Reduce x modulo the order\n */\n BigInt mod_order(const BigInt& x) const;", " /*\n * Return inverse of x modulo the order\n */\n BigInt inverse_mod_order(const BigInt& x) const;", " /*", " * Reduce (x*x) modulo the order\n */\n BigInt square_mod_order(const BigInt& x) const;", " /*", " * Reduce (x*y) modulo the order\n */\n BigInt multiply_mod_order(const BigInt& x, const BigInt& y) const;", "\n /*\n * Reduce (x*y*z) modulo the order\n */\n BigInt multiply_mod_order(const BigInt& x, const BigInt& y, const BigInt& z) const;", "\n /**\n * Return the cofactor\n * @result the cofactor\n */\n const BigInt& get_cofactor() const;", " /**\n * Check if y is a plausible point on the curve\n *\n * In particular, checks that it is a point on the curve, not infinity,\n * and that it has order matching the group.\n */\n bool verify_public_element(const PointGFp& y) const;", " /**\n * Return the OID of these domain parameters\n * @result the OID as a string\n */\n std::string BOTAN_DEPRECATED(\"Use get_curve_oid\") get_oid() const { return get_curve_oid().as_string(); }", " /**\n * Return the OID of these domain parameters\n * @result the OID\n */\n const OID& get_curve_oid() const;", " /**\n * Return a point on this curve with the affine values x, y\n */\n PointGFp point(const BigInt& x, const BigInt& y) const;", " /**\n * Multi exponentiate. Not constant time.\n * @return base_point*x + pt*y\n */\n PointGFp point_multiply(const BigInt& x, const PointGFp& pt, const BigInt& y) const;", " /**\n * Blinded point multiplication, attempts resistance to side channels\n * @param k the scalar\n * @param rng a random number generator\n * @param ws a temp workspace\n * @return base_point*k\n */\n PointGFp blinded_base_point_multiply(const BigInt& k,\n RandomNumberGenerator& rng,\n std::vector<BigInt>& ws) const;", " /**\n * Blinded point multiplication, attempts resistance to side channels\n * Returns just the x coordinate of the point\n *\n * @param k the scalar\n * @param rng a random number generator\n * @param ws a temp workspace\n * @return x coordinate of base_point*k\n */\n BigInt blinded_base_point_multiply_x(const BigInt& k,\n RandomNumberGenerator& rng,\n std::vector<BigInt>& ws) const;", " /**\n * Blinded point multiplication, attempts resistance to side channels\n * @param point input point\n * @param k the scalar\n * @param rng a random number generator\n * @param ws a temp workspace\n * @return point*k\n */\n PointGFp blinded_var_point_multiply(const PointGFp& point,\n const BigInt& k,\n RandomNumberGenerator& rng,\n std::vector<BigInt>& ws) const;", " /**\n * Return a random scalar ie an integer in [1,order)\n */\n BigInt random_scalar(RandomNumberGenerator& rng) const;", " /**\n * Return the zero (or infinite) point on this curve\n */\n PointGFp zero_point() const;", " PointGFp OS2ECP(const uint8_t bits[], size_t len) const;", " template<typename Alloc>\n PointGFp OS2ECP(const std::vector<uint8_t, Alloc>& vec) const\n {\n return this->OS2ECP(vec.data(), vec.size());\n }", " bool initialized() const { return (m_data != nullptr); }", " /**\n * Verify EC_Group domain\n * @returns true if group is valid. false otherwise\n */\n bool verify_group(RandomNumberGenerator& rng,\n bool strong = false) const;", " bool operator==(const EC_Group& other) const;", " /**\n * Return PEM representation of named EC group\n * Deprecated: Use EC_Group(name).PEM_encode() if this is needed\n */\n static std::string BOTAN_DEPRECATED(\"See header comment\") PEM_for_named_group(const std::string& name);", " /**\n * Return a set of known named EC groups\n */\n static const std::set<std::string>& known_named_groups();", " /*\n * For internal use only\n */\n static std::shared_ptr<EC_Group_Data> EC_group_info(const OID& oid);", " static size_t clear_registered_curve_data();", " private:\n static EC_Group_Data_Map& ec_group_data();", " static std::shared_ptr<EC_Group_Data> BER_decode_EC_group(const uint8_t bits[], size_t len);", " static std::shared_ptr<EC_Group_Data>\n load_EC_group_info(const char* p,\n const char* a,\n const char* b,\n const char* g_x,\n const char* g_y,\n const char* order,\n const OID& oid);", " // Member data\n const EC_Group_Data& data() const;\n std::shared_ptr<EC_Group_Data> m_data;\n };", "inline bool operator!=(const EC_Group& lhs,\n const EC_Group& rhs)\n {\n return !(lhs == rhs);\n }", "// For compatibility with 1.8\ntypedef EC_Group EC_Domain_Params;", "}", "#endif" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [19, 202, 482, 209, 237], "buggy_code_start_loc": [19, 77, 86, 206, 54], "filenames": ["doc/security.rst", "src/lib/pubkey/dsa/dsa.cpp", "src/lib/pubkey/ec_group/ec_group.cpp", "src/lib/pubkey/ec_group/ec_group.h", "src/lib/pubkey/ecdsa/ecdsa.cpp"], "fixing_code_end_loc": [28, 220, 503, 220, 252], "fixing_code_start_loc": [20, 77, 87, 207, 54], "message": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:botan_project:botan:*:*:*:*:*:*:*:*", "matchCriteriaId": "416ED13A-040B-4ED0-ACAD-9EC53C2EBE6C", "versionEndExcluding": null, "versionEndIncluding": "2.7.0", "versionStartExcluding": null, "versionStartIncluding": "2.5.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host."}, {"lang": "es", "value": "Botan versi\u00f3n 2.5.0 hasta 2.6.0 anterior a 2.7.0, permite un ataque de canal lateral de memoria cach\u00e9 en firmas ECDSA, tambi\u00e9n se conoce como Problema del Retorno de N\u00famero Oculto o ROHNP, relacionado con los archivos dsa/dsa.cpp, ec_group/ec_group.cpp, y ecdsa/ecdsa.cpp. Para descubrir una clave ECDSA, el atacante requiere acceso a la m\u00e1quina local o a una m\u00e1quina virtual diferente en el mismo host f\u00edsico."}], "evaluatorComment": null, "id": "CVE-2018-12435", "lastModified": "2018-08-22T19:57:41.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 1.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:N/UI:N/S:C/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 1.4, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-15T02:29:00.377", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://botan.randombit.net/security.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.nccgroup.trust/us/our-research/technical-advisory-return-of-the-hidden-number-problem/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, "type": "CWE-200"}
20
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n* ECDSA implemenation\n* (C) 2007 Manuel Hartl, FlexSecure GmbH\n* 2007 Falko Strenzke, FlexSecure GmbH\n* 2008-2010,2015,2016,2018 Jack Lloyd\n* 2016 RenΓ© Korthaus\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*/", "#include <botan/ecdsa.h>\n#include <botan/internal/pk_ops_impl.h>\n#include <botan/internal/point_mul.h>\n#include <botan/keypair.h>\n#include <botan/reducer.h>\n#include <botan/emsa.h>", "#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n #include <botan/rfc6979.h>\n#endif", "#if defined(BOTAN_HAS_BEARSSL)\n #include <botan/internal/bearssl.h>\n#endif", "#if defined(BOTAN_HAS_OPENSSL)\n #include <botan/internal/openssl.h>\n#endif", "namespace Botan {", "bool ECDSA_PrivateKey::check_key(RandomNumberGenerator& rng,\n bool strong) const\n {\n if(!public_point().on_the_curve())\n return false;", " if(!strong)\n return true;", " return KeyPair::signature_consistency_check(rng, *this, \"EMSA1(SHA-256)\");\n }", "namespace {", "/**\n* ECDSA signature operation\n*/\nclass ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA\n {\n public:", " ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,", " const std::string& emsa) :", " PK_Ops::Signature_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_x(ecdsa.private_value())\n {\n#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n m_rfc6979_hash = hash_for_emsa(emsa);\n#endif", "", " }", " size_t max_input_bits() const override { return m_group.get_order_bits(); }", " secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,\n RandomNumberGenerator& rng) override;", " private:\n const EC_Group m_group;\n const BigInt& m_x;", "#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n std::string m_rfc6979_hash;\n#endif", " std::vector<BigInt> m_ws;", "", " };", "secure_vector<uint8_t>\nECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,\n RandomNumberGenerator& rng)\n {\n BigInt m(msg, msg_len, m_group.get_order_bits());", "#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);\n#else\n const BigInt k = m_group.random_scalar(rng);\n#endif\n", " const BigInt k_inv = m_group.inverse_mod_order(k);", " const BigInt r = m_group.mod_order(\n m_group.blinded_base_point_multiply_x(k, rng, m_ws));\n", " const BigInt xrm = m_group.mod_order(m_group.multiply_mod_order(m_x, r) + m);\n const BigInt s = m_group.multiply_mod_order(k_inv, xrm);", "\n // With overwhelming probability, a bug rather than actual zero r/s\n if(r.is_zero() || s.is_zero())\n throw Internal_Error(\"During ECDSA signature generated zero r/s\");", " return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());\n }", "/**\n* ECDSA verification operation\n*/\nclass ECDSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA\n {\n public:\n ECDSA_Verification_Operation(const ECDSA_PublicKey& ecdsa,\n const std::string& emsa) :\n PK_Ops::Verification_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_gy_mul(m_group.get_base_point(), ecdsa.public_point())\n {\n }", " size_t max_input_bits() const override { return m_group.get_order_bits(); }", " bool with_recovery() const override { return false; }", " bool verify(const uint8_t msg[], size_t msg_len,\n const uint8_t sig[], size_t sig_len) override;\n private:\n const EC_Group m_group;\n const PointGFp_Multi_Point_Precompute m_gy_mul;\n };", "bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,\n const uint8_t sig[], size_t sig_len)\n {\n if(sig_len != m_group.get_order_bytes() * 2)\n return false;", " const BigInt e(msg, msg_len, m_group.get_order_bits());", " const BigInt r(sig, sig_len / 2);\n const BigInt s(sig + sig_len / 2, sig_len / 2);", " if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())\n return false;", " const BigInt w = m_group.inverse_mod_order(s);\n", " const BigInt u1 = m_group.multiply_mod_order(e, w);", " const BigInt u2 = m_group.multiply_mod_order(r, w);\n const PointGFp R = m_gy_mul.multi_exp(u1, u2);", " if(R.is_zero())\n return false;", " const BigInt v = m_group.mod_order(R.get_affine_x());\n return (v == r);\n }", "}", "std::unique_ptr<PK_Ops::Verification>\nECDSA_PublicKey::create_verification_op(const std::string& params,\n const std::string& provider) const\n {\n#if defined(BOTAN_HAS_BEARSSL)\n if(provider == \"bearssl\" || provider.empty())\n {\n try\n {\n return make_bearssl_ecdsa_ver_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"bearssl\")\n throw;\n }\n }\n#endif", "#if defined(BOTAN_HAS_OPENSSL)\n if(provider == \"openssl\" || provider.empty())\n {\n try\n {\n return make_openssl_ecdsa_ver_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"openssl\")\n throw;\n }\n }\n#endif", " if(provider == \"base\" || provider.empty())\n return std::unique_ptr<PK_Ops::Verification>(new ECDSA_Verification_Operation(*this, params));", " throw Provider_Not_Found(algo_name(), provider);\n }", "std::unique_ptr<PK_Ops::Signature>", "ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& /*rng*/,", " const std::string& params,\n const std::string& provider) const\n {\n#if defined(BOTAN_HAS_BEARSSL)\n if(provider == \"bearssl\" || provider.empty())\n {\n try\n {\n return make_bearssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"bearssl\")\n throw;\n }\n }\n#endif", "#if defined(BOTAN_HAS_OPENSSL)\n if(provider == \"openssl\" || provider.empty())\n {\n try\n {\n return make_openssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"openssl\")\n throw;\n }\n }\n#endif", " if(provider == \"base\" || provider.empty())", " return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params));", "\n throw Provider_Not_Found(algo_name(), provider);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [19, 202, 482, 209, 237], "buggy_code_start_loc": [19, 77, 86, 206, 54], "filenames": ["doc/security.rst", "src/lib/pubkey/dsa/dsa.cpp", "src/lib/pubkey/ec_group/ec_group.cpp", "src/lib/pubkey/ec_group/ec_group.h", "src/lib/pubkey/ecdsa/ecdsa.cpp"], "fixing_code_end_loc": [28, 220, 503, 220, 252], "fixing_code_start_loc": [20, 77, 87, 207, 54], "message": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:botan_project:botan:*:*:*:*:*:*:*:*", "matchCriteriaId": "416ED13A-040B-4ED0-ACAD-9EC53C2EBE6C", "versionEndExcluding": null, "versionEndIncluding": "2.7.0", "versionStartExcluding": null, "versionStartIncluding": "2.5.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host."}, {"lang": "es", "value": "Botan versi\u00f3n 2.5.0 hasta 2.6.0 anterior a 2.7.0, permite un ataque de canal lateral de memoria cach\u00e9 en firmas ECDSA, tambi\u00e9n se conoce como Problema del Retorno de N\u00famero Oculto o ROHNP, relacionado con los archivos dsa/dsa.cpp, ec_group/ec_group.cpp, y ecdsa/ecdsa.cpp. Para descubrir una clave ECDSA, el atacante requiere acceso a la m\u00e1quina local o a una m\u00e1quina virtual diferente en el mismo host f\u00edsico."}], "evaluatorComment": null, "id": "CVE-2018-12435", "lastModified": "2018-08-22T19:57:41.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 1.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:N/UI:N/S:C/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 1.4, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-15T02:29:00.377", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://botan.randombit.net/security.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.nccgroup.trust/us/our-research/technical-advisory-return-of-the-hidden-number-problem/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, "type": "CWE-200"}
20
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n* ECDSA implemenation\n* (C) 2007 Manuel Hartl, FlexSecure GmbH\n* 2007 Falko Strenzke, FlexSecure GmbH\n* 2008-2010,2015,2016,2018 Jack Lloyd\n* 2016 RenΓ© Korthaus\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*/", "#include <botan/ecdsa.h>\n#include <botan/internal/pk_ops_impl.h>\n#include <botan/internal/point_mul.h>\n#include <botan/keypair.h>\n#include <botan/reducer.h>\n#include <botan/emsa.h>", "#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n #include <botan/rfc6979.h>\n#endif", "#if defined(BOTAN_HAS_BEARSSL)\n #include <botan/internal/bearssl.h>\n#endif", "#if defined(BOTAN_HAS_OPENSSL)\n #include <botan/internal/openssl.h>\n#endif", "namespace Botan {", "bool ECDSA_PrivateKey::check_key(RandomNumberGenerator& rng,\n bool strong) const\n {\n if(!public_point().on_the_curve())\n return false;", " if(!strong)\n return true;", " return KeyPair::signature_consistency_check(rng, *this, \"EMSA1(SHA-256)\");\n }", "namespace {", "/**\n* ECDSA signature operation\n*/\nclass ECDSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA\n {\n public:", " ECDSA_Signature_Operation(const ECDSA_PrivateKey& ecdsa,", " const std::string& emsa,\n RandomNumberGenerator& rng) :", " PK_Ops::Signature_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_x(ecdsa.private_value())\n {\n#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n m_rfc6979_hash = hash_for_emsa(emsa);\n#endif", "\n m_b = m_group.random_scalar(rng);\n m_b_inv = m_group.inverse_mod_order(m_b);", " }", " size_t max_input_bits() const override { return m_group.get_order_bits(); }", " secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,\n RandomNumberGenerator& rng) override;", " private:\n const EC_Group m_group;\n const BigInt& m_x;", "#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n std::string m_rfc6979_hash;\n#endif", " std::vector<BigInt> m_ws;", "\n BigInt m_b, m_b_inv;", " };", "secure_vector<uint8_t>\nECDSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len,\n RandomNumberGenerator& rng)\n {\n BigInt m(msg, msg_len, m_group.get_order_bits());", "#if defined(BOTAN_HAS_RFC6979_GENERATOR)\n const BigInt k = generate_rfc6979_nonce(m_x, m_group.get_order(), m, m_rfc6979_hash);\n#else\n const BigInt k = m_group.random_scalar(rng);\n#endif\n", "", " const BigInt r = m_group.mod_order(\n m_group.blinded_base_point_multiply_x(k, rng, m_ws));\n", " const BigInt k_inv = m_group.inverse_mod_order(k);", " /*\n * Blind the input message and compute x*r+m as (x*r*b + m*b)/b\n */\n m_b = m_group.square_mod_order(m_b);\n m_b_inv = m_group.square_mod_order(m_b_inv);", " m = m_group.multiply_mod_order(m_b, m);\n const BigInt xr = m_group.multiply_mod_order(m_x, m_b, r);", " const BigInt s = m_group.multiply_mod_order(k_inv, xr + m, m_b_inv);", "\n // With overwhelming probability, a bug rather than actual zero r/s\n if(r.is_zero() || s.is_zero())\n throw Internal_Error(\"During ECDSA signature generated zero r/s\");", " return BigInt::encode_fixed_length_int_pair(r, s, m_group.get_order_bytes());\n }", "/**\n* ECDSA verification operation\n*/\nclass ECDSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA\n {\n public:\n ECDSA_Verification_Operation(const ECDSA_PublicKey& ecdsa,\n const std::string& emsa) :\n PK_Ops::Verification_with_EMSA(emsa),\n m_group(ecdsa.domain()),\n m_gy_mul(m_group.get_base_point(), ecdsa.public_point())\n {\n }", " size_t max_input_bits() const override { return m_group.get_order_bits(); }", " bool with_recovery() const override { return false; }", " bool verify(const uint8_t msg[], size_t msg_len,\n const uint8_t sig[], size_t sig_len) override;\n private:\n const EC_Group m_group;\n const PointGFp_Multi_Point_Precompute m_gy_mul;\n };", "bool ECDSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len,\n const uint8_t sig[], size_t sig_len)\n {\n if(sig_len != m_group.get_order_bytes() * 2)\n return false;", " const BigInt e(msg, msg_len, m_group.get_order_bits());", " const BigInt r(sig, sig_len / 2);\n const BigInt s(sig + sig_len / 2, sig_len / 2);", " if(r <= 0 || r >= m_group.get_order() || s <= 0 || s >= m_group.get_order())\n return false;", " const BigInt w = m_group.inverse_mod_order(s);\n", " const BigInt u1 = m_group.multiply_mod_order(m_group.mod_order(e), w);", " const BigInt u2 = m_group.multiply_mod_order(r, w);\n const PointGFp R = m_gy_mul.multi_exp(u1, u2);", " if(R.is_zero())\n return false;", " const BigInt v = m_group.mod_order(R.get_affine_x());\n return (v == r);\n }", "}", "std::unique_ptr<PK_Ops::Verification>\nECDSA_PublicKey::create_verification_op(const std::string& params,\n const std::string& provider) const\n {\n#if defined(BOTAN_HAS_BEARSSL)\n if(provider == \"bearssl\" || provider.empty())\n {\n try\n {\n return make_bearssl_ecdsa_ver_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"bearssl\")\n throw;\n }\n }\n#endif", "#if defined(BOTAN_HAS_OPENSSL)\n if(provider == \"openssl\" || provider.empty())\n {\n try\n {\n return make_openssl_ecdsa_ver_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"openssl\")\n throw;\n }\n }\n#endif", " if(provider == \"base\" || provider.empty())\n return std::unique_ptr<PK_Ops::Verification>(new ECDSA_Verification_Operation(*this, params));", " throw Provider_Not_Found(algo_name(), provider);\n }", "std::unique_ptr<PK_Ops::Signature>", "ECDSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng,", " const std::string& params,\n const std::string& provider) const\n {\n#if defined(BOTAN_HAS_BEARSSL)\n if(provider == \"bearssl\" || provider.empty())\n {\n try\n {\n return make_bearssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"bearssl\")\n throw;\n }\n }\n#endif", "#if defined(BOTAN_HAS_OPENSSL)\n if(provider == \"openssl\" || provider.empty())\n {\n try\n {\n return make_openssl_ecdsa_sig_op(*this, params);\n }\n catch(Lookup_Error& e)\n {\n if(provider == \"openssl\")\n throw;\n }\n }\n#endif", " if(provider == \"base\" || provider.empty())", " return std::unique_ptr<PK_Ops::Signature>(new ECDSA_Signature_Operation(*this, params, rng));", "\n throw Provider_Not_Found(algo_name(), provider);\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [19, 202, 482, 209, 237], "buggy_code_start_loc": [19, 77, 86, 206, 54], "filenames": ["doc/security.rst", "src/lib/pubkey/dsa/dsa.cpp", "src/lib/pubkey/ec_group/ec_group.cpp", "src/lib/pubkey/ec_group/ec_group.h", "src/lib/pubkey/ecdsa/ecdsa.cpp"], "fixing_code_end_loc": [28, 220, 503, 220, 252], "fixing_code_start_loc": [20, 77, 87, 207, 54], "message": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:botan_project:botan:*:*:*:*:*:*:*:*", "matchCriteriaId": "416ED13A-040B-4ED0-ACAD-9EC53C2EBE6C", "versionEndExcluding": null, "versionEndIncluding": "2.7.0", "versionStartExcluding": null, "versionStartIncluding": "2.5.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Botan 2.5.0 through 2.6.0 before 2.7.0 allows a memory-cache side-channel attack on ECDSA signatures, aka the Return Of the Hidden Number Problem or ROHNP, related to dsa/dsa.cpp, ec_group/ec_group.cpp, and ecdsa/ecdsa.cpp. To discover an ECDSA key, the attacker needs access to either the local machine or a different virtual machine on the same physical host."}, {"lang": "es", "value": "Botan versi\u00f3n 2.5.0 hasta 2.6.0 anterior a 2.7.0, permite un ataque de canal lateral de memoria cach\u00e9 en firmas ECDSA, tambi\u00e9n se conoce como Problema del Retorno de N\u00famero Oculto o ROHNP, relacionado con los archivos dsa/dsa.cpp, ec_group/ec_group.cpp, y ecdsa/ecdsa.cpp. Para descubrir una clave ECDSA, el atacante requiere acceso a la m\u00e1quina local o a una m\u00e1quina virtual diferente en el mismo host f\u00edsico."}], "evaluatorComment": null, "id": "CVE-2018-12435", "lastModified": "2018-08-22T19:57:41.990", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 1.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "LOCAL", "availabilityImpact": "NONE", "baseScore": 5.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:H/PR:N/UI:N/S:C/C:H/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 1.4, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-15T02:29:00.377", "references": [{"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://botan.randombit.net/security.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://www.nccgroup.trust/us/our-research/technical-advisory-return-of-the-hidden-number-problem/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/randombit/botan/commit/48fc8df51d99f9d8ba251219367b3d629cc848e3"}, "type": "CWE-200"}
20
Determine whether the {function_name} code is vulnerable or not.
[ "// SPDX-License-Identifier: BSD-2-Clause\n/*\n * Copyright (c) 2015-2016, Linaro Limited\n * Copyright (c) 2014, STMicroelectronics International N.V.\n */", "#include <assert.h>\n#include <bench.h>\n#include <compiler.h>\n#include <initcall.h>\n#include <io.h>\n#include <kernel/linker.h>\n#include <kernel/msg_param.h>\n#include <kernel/panic.h>\n#include <kernel/tee_misc.h>\n#include <mm/core_memprot.h>\n#include <mm/core_mmu.h>\n#include <mm/mobj.h>\n#include <optee_msg.h>\n#include <sm/optee_smc.h>\n#include <string.h>\n#include <tee/entry_std.h>\n#include <tee/tee_cryp_utl.h>\n#include <tee/uuid.h>\n#include <util.h>", "#define SHM_CACHE_ATTRS\t\\\n\t(uint32_t)(core_mmu_is_shm_cached() ? OPTEE_SMC_SHM_CACHED : 0)", "/* Sessions opened from normal world */\nstatic struct tee_ta_session_head tee_open_sessions =\nTAILQ_HEAD_INITIALIZER(tee_open_sessions);", "static struct mobj *shm_mobj;\n#ifdef CFG_SECURE_DATA_PATH\nstatic struct mobj **sdp_mem_mobjs;\n#endif", "static unsigned int session_pnum;", "static bool param_mem_from_mobj(struct param_mem *mem, struct mobj *mobj,\n\t\t\t\tconst paddr_t pa, const size_t sz)\n{\n\tpaddr_t b;", "\tif (mobj_get_pa(mobj, 0, 0, &b) != TEE_SUCCESS)\n\t\tpanic(\"mobj_get_pa failed\");", "\tif (!core_is_buffer_inside(pa, MAX(sz, 1UL), b, mobj->size))\n\t\treturn false;", "\tmem->mobj = mobj;\n\tmem->offs = pa - b;\n\tmem->size = sz;\n\treturn true;\n}", "/* fill 'struct param_mem' structure if buffer matches a valid memory object */\nstatic TEE_Result set_tmem_param(const struct optee_msg_param_tmem *tmem,\n\t\t\t\t uint32_t attr, struct param_mem *mem)\n{\n\tstruct mobj __maybe_unused **mobj;\n\tpaddr_t pa = READ_ONCE(tmem->buf_ptr);\n\tsize_t sz = READ_ONCE(tmem->size);", "\t/* NULL Memory Rerefence? */\n\tif (!pa && !sz) {\n\t\tmem->mobj = NULL;\n\t\tmem->offs = 0;\n\t\tmem->size = 0;\n\t\treturn TEE_SUCCESS;\n\t}", "\t/* Non-contigous buffer from non sec DDR? */\n\tif (attr & OPTEE_MSG_ATTR_NONCONTIG) {\n\t\tuint64_t shm_ref = READ_ONCE(tmem->shm_ref);", "\t\tmem->mobj = msg_param_mobj_from_noncontig(pa, sz, shm_ref,\n\t\t\t\t\t\t\t false);\n\t\tif (!mem->mobj)\n\t\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t\tmem->offs = 0;\n\t\tmem->size = sz;\n\t\treturn TEE_SUCCESS;\n\t}", "\t/* Belongs to nonsecure shared memory? */\n\tif (param_mem_from_mobj(mem, shm_mobj, pa, sz))\n\t\treturn TEE_SUCCESS;", "#ifdef CFG_SECURE_DATA_PATH\n\t/* Belongs to SDP memories? */\n\tfor (mobj = sdp_mem_mobjs; *mobj; mobj++)\n\t\tif (param_mem_from_mobj(mem, *mobj, pa, sz))\n\t\t\treturn TEE_SUCCESS;\n#endif", "\treturn TEE_ERROR_BAD_PARAMETERS;\n}", "static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem,\n\t\t\t\t struct param_mem *mem)\n{", "", "\tuint64_t shm_ref = READ_ONCE(rmem->shm_ref);", "\tmem->mobj = mobj_reg_shm_get_by_cookie(shm_ref);\n\tif (!mem->mobj)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\tmem->offs = READ_ONCE(rmem->offs);\n\tmem->size = READ_ONCE(rmem->size);", "", "\n\treturn TEE_SUCCESS;\n}", "static TEE_Result copy_in_params(const struct optee_msg_param *params,\n\t\t\t\t uint32_t num_params,\n\t\t\t\t struct tee_ta_param *ta_param,\n\t\t\t\t uint64_t *saved_attr)\n{\n\tTEE_Result res;\n\tsize_t n;\n\tuint8_t pt[TEE_NUM_PARAMS] = { 0 };", "\tif (num_params > TEE_NUM_PARAMS)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\tmemset(ta_param, 0, sizeof(*ta_param));", "\tfor (n = 0; n < num_params; n++) {\n\t\tuint32_t attr;", "\t\tsaved_attr[n] = READ_ONCE(params[n].attr);", "\t\tif (saved_attr[n] & OPTEE_MSG_ATTR_META)\n\t\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\t\tattr = saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK;\n\t\tswitch (attr) {\n\t\tcase OPTEE_MSG_ATTR_TYPE_NONE:\n\t\t\tpt[n] = TEE_PARAM_TYPE_NONE;\n\t\t\tbreak;\n\t\tcase OPTEE_MSG_ATTR_TYPE_VALUE_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:\n\t\t\tpt[n] = TEE_PARAM_TYPE_VALUE_INPUT + attr -\n\t\t\t\tOPTEE_MSG_ATTR_TYPE_VALUE_INPUT;\n\t\t\tta_param->u[n].val.a = READ_ONCE(params[n].u.value.a);\n\t\t\tta_param->u[n].val.b = READ_ONCE(params[n].u.value.b);\n\t\t\tbreak;\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:\n\t\t\tres = set_tmem_param(&params[n].u.tmem, saved_attr[n],\n\t\t\t\t\t &ta_param->u[n].mem);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t\tpt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr -\n\t\t\t\tOPTEE_MSG_ATTR_TYPE_TMEM_INPUT;\n\t\t\tbreak;\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:\n\t\t\tres = set_rmem_param(&params[n].u.rmem,\n\t\t\t\t\t &ta_param->u[n].mem);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t\tpt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr -\n\t\t\t\tOPTEE_MSG_ATTR_TYPE_RMEM_INPUT;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t\t}\n\t}", "\tta_param->types = TEE_PARAM_TYPES(pt[0], pt[1], pt[2], pt[3]);", "\treturn TEE_SUCCESS;\n}", "static void cleanup_shm_refs(const uint64_t *saved_attr,\n\t\t\t struct tee_ta_param *param, uint32_t num_params)\n{\n\tsize_t n;", "\tfor (n = 0; n < num_params; n++) {\n\t\tswitch (saved_attr[n]) {\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:\n\t\t\tif (saved_attr[n] & OPTEE_MSG_ATTR_NONCONTIG)\n\t\t\t\tmobj_free(param->u[n].mem.mobj);\n\t\t\tbreak;", "\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:\n\t\t\tmobj_reg_shm_put(param->u[n].mem.mobj);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}", "static void copy_out_param(struct tee_ta_param *ta_param, uint32_t num_params,\n\t\t\t struct optee_msg_param *params, uint64_t *saved_attr)\n{\n\tsize_t n;", "\tfor (n = 0; n < num_params; n++) {\n\t\tswitch (TEE_PARAM_TYPE_GET(ta_param->types, n)) {\n\t\tcase TEE_PARAM_TYPE_MEMREF_OUTPUT:\n\t\tcase TEE_PARAM_TYPE_MEMREF_INOUT:\n\t\t\tswitch (saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK) {\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:\n\t\t\t\tparams[n].u.tmem.size = ta_param->u[n].mem.size;\n\t\t\t\tbreak;\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:\n\t\t\t\tparams[n].u.rmem.size = ta_param->u[n].mem.size;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TEE_PARAM_TYPE_VALUE_OUTPUT:\n\t\tcase TEE_PARAM_TYPE_VALUE_INOUT:\n\t\t\tparams[n].u.value.a = ta_param->u[n].val.a;\n\t\t\tparams[n].u.value.b = ta_param->u[n].val.b;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}", "/*\n * Extracts mandatory parameter for open session.\n *\n * Returns\n * false : mandatory parameter wasn't found or malformatted\n * true : paramater found and OK\n */\nstatic TEE_Result get_open_session_meta(size_t num_params,\n\t\t\t\t\tstruct optee_msg_param *params,\n\t\t\t\t\tsize_t *num_meta, TEE_UUID *uuid,\n\t\t\t\t\tTEE_Identity *clnt_id)\n{\n\tconst uint32_t req_attr = OPTEE_MSG_ATTR_META |\n\t\t\t\t OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;", "\tif (num_params < 2)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\tif (params[0].attr != req_attr || params[1].attr != req_attr)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\ttee_uuid_from_octets(uuid, (void *)&params[0].u.value);\n\tclnt_id->login = params[1].u.value.c;\n\tswitch (clnt_id->login) {\n\tcase TEE_LOGIN_PUBLIC:\n\t\tmemset(&clnt_id->uuid, 0, sizeof(clnt_id->uuid));\n\t\tbreak;\n\tcase TEE_LOGIN_USER:\n\tcase TEE_LOGIN_GROUP:\n\tcase TEE_LOGIN_APPLICATION:\n\tcase TEE_LOGIN_APPLICATION_USER:\n\tcase TEE_LOGIN_APPLICATION_GROUP:\n\t\ttee_uuid_from_octets(&clnt_id->uuid,\n\t\t\t\t (void *)&params[1].u.value);\n\t\tbreak;\n\tdefault:\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t}", "\t*num_meta = 2;\n\treturn TEE_SUCCESS;\n}", "static void entry_open_session(struct thread_smc_args *smc_args,\n\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tTEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;\n\tstruct tee_ta_session *s = NULL;\n\tTEE_Identity clnt_id;\n\tTEE_UUID uuid;\n\tstruct tee_ta_param param;\n\tsize_t num_meta;\n\tuint64_t saved_attr[TEE_NUM_PARAMS] = { 0 };", "\tres = get_open_session_meta(num_params, arg->params, &num_meta, &uuid,\n\t\t\t\t &clnt_id);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;", "\tres = copy_in_params(arg->params + num_meta, num_params - num_meta,\n\t\t\t &param, saved_attr);\n\tif (res != TEE_SUCCESS)\n\t\tgoto cleanup_shm_refs;", "\tres = tee_ta_open_session(&err_orig, &s, &tee_open_sessions, &uuid,\n\t\t\t\t &clnt_id, TEE_TIMEOUT_INFINITE, &param);\n\tif (res != TEE_SUCCESS)\n\t\ts = NULL;\n\tcopy_out_param(&param, num_params - num_meta, arg->params + num_meta,\n\t\t saved_attr);", "\t/*\n\t * The occurrence of open/close session command is usually\n\t * un-predictable, using this property to increase randomness\n\t * of prng\n\t */\n\tplat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION,\n\t\t\t\t &session_pnum);", "cleanup_shm_refs:\n\tcleanup_shm_refs(saved_attr, &param, num_params - num_meta);", "out:\n\tif (s)\n\t\targ->session = (vaddr_t)s;\n\telse\n\t\targ->session = 0;\n\targ->ret = res;\n\targ->ret_origin = err_orig;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void entry_close_session(struct thread_smc_args *smc_args,\n\t\t\tstruct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tstruct tee_ta_session *s;", "\tif (num_params) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\tplat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION,\n\t\t\t\t &session_pnum);", "\ts = (struct tee_ta_session *)(vaddr_t)arg->session;\n\tres = tee_ta_close_session(s, &tee_open_sessions, NSAPP_IDENTITY);\nout:\n\targ->ret = res;\n\targ->ret_origin = TEE_ORIGIN_TEE;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void entry_invoke_command(struct thread_smc_args *smc_args,\n\t\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tTEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;\n\tstruct tee_ta_session *s;\n\tstruct tee_ta_param param = { 0 };\n\tuint64_t saved_attr[TEE_NUM_PARAMS] = { 0 };", "\tbm_timestamp();", "\tres = copy_in_params(arg->params, num_params, &param, saved_attr);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;", "\ts = tee_ta_get_session(arg->session, true, &tee_open_sessions);\n\tif (!s) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\tres = tee_ta_invoke_command(&err_orig, s, NSAPP_IDENTITY,\n\t\t\t\t TEE_TIMEOUT_INFINITE, arg->func, &param);", "\tbm_timestamp();", "\ttee_ta_put_session(s);", "\tcopy_out_param(&param, num_params, arg->params, saved_attr);", "out:\n\tcleanup_shm_refs(saved_attr, &param, num_params);", "\targ->ret = res;\n\targ->ret_origin = err_orig;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void entry_cancel(struct thread_smc_args *smc_args,\n\t\t\tstruct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tTEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;\n\tstruct tee_ta_session *s;", "\tif (num_params) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\ts = tee_ta_get_session(arg->session, false, &tee_open_sessions);\n\tif (!s) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\tres = tee_ta_cancel_command(&err_orig, s, NSAPP_IDENTITY);\n\ttee_ta_put_session(s);", "out:\n\targ->ret = res;\n\targ->ret_origin = err_orig;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void register_shm(struct thread_smc_args *smc_args,\n\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\targ->ret = TEE_ERROR_BAD_PARAMETERS;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;", "\tif (num_params != 1 ||\n\t (arg->params[0].attr !=\n\t (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG)))\n\t\treturn;", "\tstruct optee_msg_param_tmem *tmem = &arg->params[0].u.tmem;\n\tstruct mobj *mobj = msg_param_mobj_from_noncontig(tmem->buf_ptr,\n\t\t\t\t\t\t\t tmem->size,\n\t\t\t\t\t\t\t tmem->shm_ref, false);", "\tif (!mobj)\n\t\treturn;", "\tmobj_reg_shm_unguard(mobj);\n\targ->ret = TEE_SUCCESS;\n}", "static void unregister_shm(struct thread_smc_args *smc_args,\n\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\tif (num_params == 1) {\n\t\tuint64_t cookie = arg->params[0].u.rmem.shm_ref;\n\t\tTEE_Result res = mobj_reg_shm_release_by_cookie(cookie);", "\t\tif (res)\n\t\t\tEMSG(\"Can't find mapping with given cookie\");\n\t\targ->ret = res;\n\t} else {\n\t\targ->ret = TEE_ERROR_BAD_PARAMETERS;\n\t\targ->ret_origin = TEE_ORIGIN_TEE;\n\t}", "\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static struct mobj *map_cmd_buffer(paddr_t parg, uint32_t *num_params)\n{\n\tstruct mobj *mobj;\n\tstruct optee_msg_arg *arg;\n\tsize_t args_size;", "\tassert(!(parg & SMALL_PAGE_MASK));\n\t/* mobj_mapped_shm_alloc checks if parg resides in nonsec ddr */\n\tmobj = mobj_mapped_shm_alloc(&parg, 1, 0, 0);\n\tif (!mobj)\n\t\treturn NULL;", "\targ = mobj_get_va(mobj, 0);\n\tif (!arg) {\n\t\tmobj_free(mobj);\n\t\treturn NULL;\n\t}", "\t*num_params = READ_ONCE(arg->num_params);\n\targs_size = OPTEE_MSG_GET_ARG_SIZE(*num_params);\n\tif (args_size > SMALL_PAGE_SIZE) {\n\t\tEMSG(\"Command buffer spans across page boundary\");\n\t\tmobj_free(mobj);\n\t\treturn NULL;\n\t}", "\treturn mobj;\n}", "static struct mobj *get_cmd_buffer(paddr_t parg, uint32_t *num_params)\n{\n\tstruct optee_msg_arg *arg;\n\tsize_t args_size;", "\targ = phys_to_virt(parg, MEM_AREA_NSEC_SHM);\n\tif (!arg)\n\t\treturn NULL;", "\t*num_params = READ_ONCE(arg->num_params);\n\targs_size = OPTEE_MSG_GET_ARG_SIZE(*num_params);", "\treturn mobj_shm_alloc(parg, args_size, 0);\n}", "/*\n * Note: this function is weak just to make it possible to exclude it from\n * the unpaged area.\n */\nvoid __weak tee_entry_std(struct thread_smc_args *smc_args)\n{\n\tpaddr_t parg;\n\tstruct optee_msg_arg *arg = NULL;\t/* fix gcc warning */\n\tuint32_t num_params = 0;\t\t/* fix gcc warning */\n\tstruct mobj *mobj;", "\tif (smc_args->a0 != OPTEE_SMC_CALL_WITH_ARG) {\n\t\tEMSG(\"Unknown SMC 0x%\" PRIx64, (uint64_t)smc_args->a0);\n\t\tDMSG(\"Expected 0x%x\\n\", OPTEE_SMC_CALL_WITH_ARG);\n\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADCMD;\n\t\treturn;\n\t}\n\tparg = (uint64_t)smc_args->a1 << 32 | smc_args->a2;", "\t/* Check if this region is in static shared space */\n\tif (core_pbuf_is(CORE_MEM_NSEC_SHM, parg,\n\t\t\t sizeof(struct optee_msg_arg))) {\n\t\tmobj = get_cmd_buffer(parg, &num_params);\n\t} else {\n\t\tif (parg & SMALL_PAGE_MASK) {\n\t\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADADDR;\n\t\t\treturn;\n\t\t}\n\t\tmobj = map_cmd_buffer(parg, &num_params);\n\t}", "\tif (!mobj || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg)) {\n\t\tEMSG(\"Bad arg address 0x%\" PRIxPA, parg);\n\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADADDR;\n\t\tmobj_free(mobj);\n\t\treturn;\n\t}", "\targ = mobj_get_va(mobj, 0);\n\tassert(arg && mobj_is_nonsec(mobj));", "\t/* Enable foreign interrupts for STD calls */\n\tthread_set_foreign_intr(true);\n\tswitch (arg->cmd) {\n\tcase OPTEE_MSG_CMD_OPEN_SESSION:\n\t\tentry_open_session(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_CLOSE_SESSION:\n\t\tentry_close_session(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_INVOKE_COMMAND:\n\t\tentry_invoke_command(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_CANCEL:\n\t\tentry_cancel(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_REGISTER_SHM:\n\t\tregister_shm(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_UNREGISTER_SHM:\n\t\tunregister_shm(smc_args, arg, num_params);\n\t\tbreak;", "\tdefault:\n\t\tEMSG(\"Unknown cmd 0x%x\\n\", arg->cmd);\n\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADCMD;\n\t}\n\tmobj_free(mobj);\n}", "static TEE_Result default_mobj_init(void)\n{\n\tshm_mobj = mobj_phys_alloc(default_nsec_shm_paddr,\n\t\t\t\t default_nsec_shm_size, SHM_CACHE_ATTRS,\n\t\t\t\t CORE_MEM_NSEC_SHM);\n\tif (!shm_mobj)\n\t\tpanic(\"Failed to register shared memory\");", "#ifdef CFG_SECURE_DATA_PATH\n\tsdp_mem_mobjs = core_sdp_mem_create_mobjs();\n\tif (!sdp_mem_mobjs)\n\t\tpanic(\"Failed to register SDP memory\");\n#endif", "\treturn TEE_SUCCESS;\n}", "driver_init_late(default_mobj_init);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [111], "buggy_code_start_loc": [103], "filenames": ["core/arch/arm/tee/entry_std.c"], "fixing_code_end_loc": [121], "fixing_code_start_loc": [104], "message": "Linaro/OP-TEE OP-TEE Prior to version v3.4.0 is affected by: Boundary checks. The impact is: This could lead to corruption of any memory which the TA can access. The component is: optee_os. The fixed version is: v3.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linaro:op-tee:*:*:*:*:*:*:*:*", "matchCriteriaId": "E5151242-B2AA-44C7-8271-52C991A0FF8D", "versionEndExcluding": "3.4.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Linaro/OP-TEE OP-TEE Prior to version v3.4.0 is affected by: Boundary checks. The impact is: This could lead to corruption of any memory which the TA can access. The component is: optee_os. The fixed version is: v3.4.0."}, {"lang": "es", "value": "OP-TEE versiones anteriores a v3.4.0 de Linaro/OP-TEE, est\u00e1 afectada por: Comprobaciones de l\u00edmites. El impacto es: Esto podr\u00eda conllevar a la corrupci\u00f3n de cualquier memoria a la que pueda acceder el TA. El componente es: optee_os. La versi\u00f3n corregida es: v3.4.0."}], "evaluatorComment": null, "id": "CVE-2019-1010292", "lastModified": "2021-07-21T11:39:23.747", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-07-16T14:15:11.997", "references": [{"source": "josh@bress.net", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/OP-TEE/optee_os/commit/e3adcf566cb278444830e7badfdcc3983e334fd1"}], "sourceIdentifier": "josh@bress.net", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/OP-TEE/optee_os/commit/e3adcf566cb278444830e7badfdcc3983e334fd1"}, "type": "CWE-787"}
21
Determine whether the {function_name} code is vulnerable or not.
[ "// SPDX-License-Identifier: BSD-2-Clause\n/*\n * Copyright (c) 2015-2016, Linaro Limited\n * Copyright (c) 2014, STMicroelectronics International N.V.\n */", "#include <assert.h>\n#include <bench.h>\n#include <compiler.h>\n#include <initcall.h>\n#include <io.h>\n#include <kernel/linker.h>\n#include <kernel/msg_param.h>\n#include <kernel/panic.h>\n#include <kernel/tee_misc.h>\n#include <mm/core_memprot.h>\n#include <mm/core_mmu.h>\n#include <mm/mobj.h>\n#include <optee_msg.h>\n#include <sm/optee_smc.h>\n#include <string.h>\n#include <tee/entry_std.h>\n#include <tee/tee_cryp_utl.h>\n#include <tee/uuid.h>\n#include <util.h>", "#define SHM_CACHE_ATTRS\t\\\n\t(uint32_t)(core_mmu_is_shm_cached() ? OPTEE_SMC_SHM_CACHED : 0)", "/* Sessions opened from normal world */\nstatic struct tee_ta_session_head tee_open_sessions =\nTAILQ_HEAD_INITIALIZER(tee_open_sessions);", "static struct mobj *shm_mobj;\n#ifdef CFG_SECURE_DATA_PATH\nstatic struct mobj **sdp_mem_mobjs;\n#endif", "static unsigned int session_pnum;", "static bool param_mem_from_mobj(struct param_mem *mem, struct mobj *mobj,\n\t\t\t\tconst paddr_t pa, const size_t sz)\n{\n\tpaddr_t b;", "\tif (mobj_get_pa(mobj, 0, 0, &b) != TEE_SUCCESS)\n\t\tpanic(\"mobj_get_pa failed\");", "\tif (!core_is_buffer_inside(pa, MAX(sz, 1UL), b, mobj->size))\n\t\treturn false;", "\tmem->mobj = mobj;\n\tmem->offs = pa - b;\n\tmem->size = sz;\n\treturn true;\n}", "/* fill 'struct param_mem' structure if buffer matches a valid memory object */\nstatic TEE_Result set_tmem_param(const struct optee_msg_param_tmem *tmem,\n\t\t\t\t uint32_t attr, struct param_mem *mem)\n{\n\tstruct mobj __maybe_unused **mobj;\n\tpaddr_t pa = READ_ONCE(tmem->buf_ptr);\n\tsize_t sz = READ_ONCE(tmem->size);", "\t/* NULL Memory Rerefence? */\n\tif (!pa && !sz) {\n\t\tmem->mobj = NULL;\n\t\tmem->offs = 0;\n\t\tmem->size = 0;\n\t\treturn TEE_SUCCESS;\n\t}", "\t/* Non-contigous buffer from non sec DDR? */\n\tif (attr & OPTEE_MSG_ATTR_NONCONTIG) {\n\t\tuint64_t shm_ref = READ_ONCE(tmem->shm_ref);", "\t\tmem->mobj = msg_param_mobj_from_noncontig(pa, sz, shm_ref,\n\t\t\t\t\t\t\t false);\n\t\tif (!mem->mobj)\n\t\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t\tmem->offs = 0;\n\t\tmem->size = sz;\n\t\treturn TEE_SUCCESS;\n\t}", "\t/* Belongs to nonsecure shared memory? */\n\tif (param_mem_from_mobj(mem, shm_mobj, pa, sz))\n\t\treturn TEE_SUCCESS;", "#ifdef CFG_SECURE_DATA_PATH\n\t/* Belongs to SDP memories? */\n\tfor (mobj = sdp_mem_mobjs; *mobj; mobj++)\n\t\tif (param_mem_from_mobj(mem, *mobj, pa, sz))\n\t\t\treturn TEE_SUCCESS;\n#endif", "\treturn TEE_ERROR_BAD_PARAMETERS;\n}", "static TEE_Result set_rmem_param(const struct optee_msg_param_rmem *rmem,\n\t\t\t\t struct param_mem *mem)\n{", "\tsize_t req_size = 0;", "\tuint64_t shm_ref = READ_ONCE(rmem->shm_ref);", "\tmem->mobj = mobj_reg_shm_get_by_cookie(shm_ref);\n\tif (!mem->mobj)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\tmem->offs = READ_ONCE(rmem->offs);\n\tmem->size = READ_ONCE(rmem->size);", "\n\t/*\n\t * Check that the supplied offset and size is covered by the\n\t * previously verified MOBJ.\n\t */\n\tif (ADD_OVERFLOW(mem->offs, mem->size, &req_size) ||\n\t mem->mobj->size < req_size)\n\t\treturn TEE_ERROR_SECURITY;", "\n\treturn TEE_SUCCESS;\n}", "static TEE_Result copy_in_params(const struct optee_msg_param *params,\n\t\t\t\t uint32_t num_params,\n\t\t\t\t struct tee_ta_param *ta_param,\n\t\t\t\t uint64_t *saved_attr)\n{\n\tTEE_Result res;\n\tsize_t n;\n\tuint8_t pt[TEE_NUM_PARAMS] = { 0 };", "\tif (num_params > TEE_NUM_PARAMS)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\tmemset(ta_param, 0, sizeof(*ta_param));", "\tfor (n = 0; n < num_params; n++) {\n\t\tuint32_t attr;", "\t\tsaved_attr[n] = READ_ONCE(params[n].attr);", "\t\tif (saved_attr[n] & OPTEE_MSG_ATTR_META)\n\t\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\t\tattr = saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK;\n\t\tswitch (attr) {\n\t\tcase OPTEE_MSG_ATTR_TYPE_NONE:\n\t\t\tpt[n] = TEE_PARAM_TYPE_NONE;\n\t\t\tbreak;\n\t\tcase OPTEE_MSG_ATTR_TYPE_VALUE_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_VALUE_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_VALUE_INOUT:\n\t\t\tpt[n] = TEE_PARAM_TYPE_VALUE_INPUT + attr -\n\t\t\t\tOPTEE_MSG_ATTR_TYPE_VALUE_INPUT;\n\t\t\tta_param->u[n].val.a = READ_ONCE(params[n].u.value.a);\n\t\t\tta_param->u[n].val.b = READ_ONCE(params[n].u.value.b);\n\t\t\tbreak;\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:\n\t\t\tres = set_tmem_param(&params[n].u.tmem, saved_attr[n],\n\t\t\t\t\t &ta_param->u[n].mem);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t\tpt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr -\n\t\t\t\tOPTEE_MSG_ATTR_TYPE_TMEM_INPUT;\n\t\t\tbreak;\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:\n\t\t\tres = set_rmem_param(&params[n].u.rmem,\n\t\t\t\t\t &ta_param->u[n].mem);\n\t\t\tif (res)\n\t\t\t\treturn res;\n\t\t\tpt[n] = TEE_PARAM_TYPE_MEMREF_INPUT + attr -\n\t\t\t\tOPTEE_MSG_ATTR_TYPE_RMEM_INPUT;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t\t}\n\t}", "\tta_param->types = TEE_PARAM_TYPES(pt[0], pt[1], pt[2], pt[3]);", "\treturn TEE_SUCCESS;\n}", "static void cleanup_shm_refs(const uint64_t *saved_attr,\n\t\t\t struct tee_ta_param *param, uint32_t num_params)\n{\n\tsize_t n;", "\tfor (n = 0; n < num_params; n++) {\n\t\tswitch (saved_attr[n]) {\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:\n\t\t\tif (saved_attr[n] & OPTEE_MSG_ATTR_NONCONTIG)\n\t\t\t\tmobj_free(param->u[n].mem.mobj);\n\t\t\tbreak;", "\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:\n\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:\n\t\t\tmobj_reg_shm_put(param->u[n].mem.mobj);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}", "static void copy_out_param(struct tee_ta_param *ta_param, uint32_t num_params,\n\t\t\t struct optee_msg_param *params, uint64_t *saved_attr)\n{\n\tsize_t n;", "\tfor (n = 0; n < num_params; n++) {\n\t\tswitch (TEE_PARAM_TYPE_GET(ta_param->types, n)) {\n\t\tcase TEE_PARAM_TYPE_MEMREF_OUTPUT:\n\t\tcase TEE_PARAM_TYPE_MEMREF_INOUT:\n\t\t\tswitch (saved_attr[n] & OPTEE_MSG_ATTR_TYPE_MASK) {\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT:\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_TMEM_INOUT:\n\t\t\t\tparams[n].u.tmem.size = ta_param->u[n].mem.size;\n\t\t\t\tbreak;\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_OUTPUT:\n\t\t\tcase OPTEE_MSG_ATTR_TYPE_RMEM_INOUT:\n\t\t\t\tparams[n].u.rmem.size = ta_param->u[n].mem.size;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TEE_PARAM_TYPE_VALUE_OUTPUT:\n\t\tcase TEE_PARAM_TYPE_VALUE_INOUT:\n\t\t\tparams[n].u.value.a = ta_param->u[n].val.a;\n\t\t\tparams[n].u.value.b = ta_param->u[n].val.b;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}", "/*\n * Extracts mandatory parameter for open session.\n *\n * Returns\n * false : mandatory parameter wasn't found or malformatted\n * true : paramater found and OK\n */\nstatic TEE_Result get_open_session_meta(size_t num_params,\n\t\t\t\t\tstruct optee_msg_param *params,\n\t\t\t\t\tsize_t *num_meta, TEE_UUID *uuid,\n\t\t\t\t\tTEE_Identity *clnt_id)\n{\n\tconst uint32_t req_attr = OPTEE_MSG_ATTR_META |\n\t\t\t\t OPTEE_MSG_ATTR_TYPE_VALUE_INPUT;", "\tif (num_params < 2)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\tif (params[0].attr != req_attr || params[1].attr != req_attr)\n\t\treturn TEE_ERROR_BAD_PARAMETERS;", "\ttee_uuid_from_octets(uuid, (void *)&params[0].u.value);\n\tclnt_id->login = params[1].u.value.c;\n\tswitch (clnt_id->login) {\n\tcase TEE_LOGIN_PUBLIC:\n\t\tmemset(&clnt_id->uuid, 0, sizeof(clnt_id->uuid));\n\t\tbreak;\n\tcase TEE_LOGIN_USER:\n\tcase TEE_LOGIN_GROUP:\n\tcase TEE_LOGIN_APPLICATION:\n\tcase TEE_LOGIN_APPLICATION_USER:\n\tcase TEE_LOGIN_APPLICATION_GROUP:\n\t\ttee_uuid_from_octets(&clnt_id->uuid,\n\t\t\t\t (void *)&params[1].u.value);\n\t\tbreak;\n\tdefault:\n\t\treturn TEE_ERROR_BAD_PARAMETERS;\n\t}", "\t*num_meta = 2;\n\treturn TEE_SUCCESS;\n}", "static void entry_open_session(struct thread_smc_args *smc_args,\n\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tTEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;\n\tstruct tee_ta_session *s = NULL;\n\tTEE_Identity clnt_id;\n\tTEE_UUID uuid;\n\tstruct tee_ta_param param;\n\tsize_t num_meta;\n\tuint64_t saved_attr[TEE_NUM_PARAMS] = { 0 };", "\tres = get_open_session_meta(num_params, arg->params, &num_meta, &uuid,\n\t\t\t\t &clnt_id);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;", "\tres = copy_in_params(arg->params + num_meta, num_params - num_meta,\n\t\t\t &param, saved_attr);\n\tif (res != TEE_SUCCESS)\n\t\tgoto cleanup_shm_refs;", "\tres = tee_ta_open_session(&err_orig, &s, &tee_open_sessions, &uuid,\n\t\t\t\t &clnt_id, TEE_TIMEOUT_INFINITE, &param);\n\tif (res != TEE_SUCCESS)\n\t\ts = NULL;\n\tcopy_out_param(&param, num_params - num_meta, arg->params + num_meta,\n\t\t saved_attr);", "\t/*\n\t * The occurrence of open/close session command is usually\n\t * un-predictable, using this property to increase randomness\n\t * of prng\n\t */\n\tplat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION,\n\t\t\t\t &session_pnum);", "cleanup_shm_refs:\n\tcleanup_shm_refs(saved_attr, &param, num_params - num_meta);", "out:\n\tif (s)\n\t\targ->session = (vaddr_t)s;\n\telse\n\t\targ->session = 0;\n\targ->ret = res;\n\targ->ret_origin = err_orig;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void entry_close_session(struct thread_smc_args *smc_args,\n\t\t\tstruct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tstruct tee_ta_session *s;", "\tif (num_params) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\tplat_prng_add_jitter_entropy(CRYPTO_RNG_SRC_JITTER_SESSION,\n\t\t\t\t &session_pnum);", "\ts = (struct tee_ta_session *)(vaddr_t)arg->session;\n\tres = tee_ta_close_session(s, &tee_open_sessions, NSAPP_IDENTITY);\nout:\n\targ->ret = res;\n\targ->ret_origin = TEE_ORIGIN_TEE;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void entry_invoke_command(struct thread_smc_args *smc_args,\n\t\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tTEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;\n\tstruct tee_ta_session *s;\n\tstruct tee_ta_param param = { 0 };\n\tuint64_t saved_attr[TEE_NUM_PARAMS] = { 0 };", "\tbm_timestamp();", "\tres = copy_in_params(arg->params, num_params, &param, saved_attr);\n\tif (res != TEE_SUCCESS)\n\t\tgoto out;", "\ts = tee_ta_get_session(arg->session, true, &tee_open_sessions);\n\tif (!s) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\tres = tee_ta_invoke_command(&err_orig, s, NSAPP_IDENTITY,\n\t\t\t\t TEE_TIMEOUT_INFINITE, arg->func, &param);", "\tbm_timestamp();", "\ttee_ta_put_session(s);", "\tcopy_out_param(&param, num_params, arg->params, saved_attr);", "out:\n\tcleanup_shm_refs(saved_attr, &param, num_params);", "\targ->ret = res;\n\targ->ret_origin = err_orig;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void entry_cancel(struct thread_smc_args *smc_args,\n\t\t\tstruct optee_msg_arg *arg, uint32_t num_params)\n{\n\tTEE_Result res;\n\tTEE_ErrorOrigin err_orig = TEE_ORIGIN_TEE;\n\tstruct tee_ta_session *s;", "\tif (num_params) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\ts = tee_ta_get_session(arg->session, false, &tee_open_sessions);\n\tif (!s) {\n\t\tres = TEE_ERROR_BAD_PARAMETERS;\n\t\tgoto out;\n\t}", "\tres = tee_ta_cancel_command(&err_orig, s, NSAPP_IDENTITY);\n\ttee_ta_put_session(s);", "out:\n\targ->ret = res;\n\targ->ret_origin = err_orig;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static void register_shm(struct thread_smc_args *smc_args,\n\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\targ->ret = TEE_ERROR_BAD_PARAMETERS;\n\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;", "\tif (num_params != 1 ||\n\t (arg->params[0].attr !=\n\t (OPTEE_MSG_ATTR_TYPE_TMEM_OUTPUT | OPTEE_MSG_ATTR_NONCONTIG)))\n\t\treturn;", "\tstruct optee_msg_param_tmem *tmem = &arg->params[0].u.tmem;\n\tstruct mobj *mobj = msg_param_mobj_from_noncontig(tmem->buf_ptr,\n\t\t\t\t\t\t\t tmem->size,\n\t\t\t\t\t\t\t tmem->shm_ref, false);", "\tif (!mobj)\n\t\treturn;", "\tmobj_reg_shm_unguard(mobj);\n\targ->ret = TEE_SUCCESS;\n}", "static void unregister_shm(struct thread_smc_args *smc_args,\n\t\t\t struct optee_msg_arg *arg, uint32_t num_params)\n{\n\tif (num_params == 1) {\n\t\tuint64_t cookie = arg->params[0].u.rmem.shm_ref;\n\t\tTEE_Result res = mobj_reg_shm_release_by_cookie(cookie);", "\t\tif (res)\n\t\t\tEMSG(\"Can't find mapping with given cookie\");\n\t\targ->ret = res;\n\t} else {\n\t\targ->ret = TEE_ERROR_BAD_PARAMETERS;\n\t\targ->ret_origin = TEE_ORIGIN_TEE;\n\t}", "\tsmc_args->a0 = OPTEE_SMC_RETURN_OK;\n}", "static struct mobj *map_cmd_buffer(paddr_t parg, uint32_t *num_params)\n{\n\tstruct mobj *mobj;\n\tstruct optee_msg_arg *arg;\n\tsize_t args_size;", "\tassert(!(parg & SMALL_PAGE_MASK));\n\t/* mobj_mapped_shm_alloc checks if parg resides in nonsec ddr */\n\tmobj = mobj_mapped_shm_alloc(&parg, 1, 0, 0);\n\tif (!mobj)\n\t\treturn NULL;", "\targ = mobj_get_va(mobj, 0);\n\tif (!arg) {\n\t\tmobj_free(mobj);\n\t\treturn NULL;\n\t}", "\t*num_params = READ_ONCE(arg->num_params);\n\targs_size = OPTEE_MSG_GET_ARG_SIZE(*num_params);\n\tif (args_size > SMALL_PAGE_SIZE) {\n\t\tEMSG(\"Command buffer spans across page boundary\");\n\t\tmobj_free(mobj);\n\t\treturn NULL;\n\t}", "\treturn mobj;\n}", "static struct mobj *get_cmd_buffer(paddr_t parg, uint32_t *num_params)\n{\n\tstruct optee_msg_arg *arg;\n\tsize_t args_size;", "\targ = phys_to_virt(parg, MEM_AREA_NSEC_SHM);\n\tif (!arg)\n\t\treturn NULL;", "\t*num_params = READ_ONCE(arg->num_params);\n\targs_size = OPTEE_MSG_GET_ARG_SIZE(*num_params);", "\treturn mobj_shm_alloc(parg, args_size, 0);\n}", "/*\n * Note: this function is weak just to make it possible to exclude it from\n * the unpaged area.\n */\nvoid __weak tee_entry_std(struct thread_smc_args *smc_args)\n{\n\tpaddr_t parg;\n\tstruct optee_msg_arg *arg = NULL;\t/* fix gcc warning */\n\tuint32_t num_params = 0;\t\t/* fix gcc warning */\n\tstruct mobj *mobj;", "\tif (smc_args->a0 != OPTEE_SMC_CALL_WITH_ARG) {\n\t\tEMSG(\"Unknown SMC 0x%\" PRIx64, (uint64_t)smc_args->a0);\n\t\tDMSG(\"Expected 0x%x\\n\", OPTEE_SMC_CALL_WITH_ARG);\n\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADCMD;\n\t\treturn;\n\t}\n\tparg = (uint64_t)smc_args->a1 << 32 | smc_args->a2;", "\t/* Check if this region is in static shared space */\n\tif (core_pbuf_is(CORE_MEM_NSEC_SHM, parg,\n\t\t\t sizeof(struct optee_msg_arg))) {\n\t\tmobj = get_cmd_buffer(parg, &num_params);\n\t} else {\n\t\tif (parg & SMALL_PAGE_MASK) {\n\t\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADADDR;\n\t\t\treturn;\n\t\t}\n\t\tmobj = map_cmd_buffer(parg, &num_params);\n\t}", "\tif (!mobj || !ALIGNMENT_IS_OK(parg, struct optee_msg_arg)) {\n\t\tEMSG(\"Bad arg address 0x%\" PRIxPA, parg);\n\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADADDR;\n\t\tmobj_free(mobj);\n\t\treturn;\n\t}", "\targ = mobj_get_va(mobj, 0);\n\tassert(arg && mobj_is_nonsec(mobj));", "\t/* Enable foreign interrupts for STD calls */\n\tthread_set_foreign_intr(true);\n\tswitch (arg->cmd) {\n\tcase OPTEE_MSG_CMD_OPEN_SESSION:\n\t\tentry_open_session(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_CLOSE_SESSION:\n\t\tentry_close_session(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_INVOKE_COMMAND:\n\t\tentry_invoke_command(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_CANCEL:\n\t\tentry_cancel(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_REGISTER_SHM:\n\t\tregister_shm(smc_args, arg, num_params);\n\t\tbreak;\n\tcase OPTEE_MSG_CMD_UNREGISTER_SHM:\n\t\tunregister_shm(smc_args, arg, num_params);\n\t\tbreak;", "\tdefault:\n\t\tEMSG(\"Unknown cmd 0x%x\\n\", arg->cmd);\n\t\tsmc_args->a0 = OPTEE_SMC_RETURN_EBADCMD;\n\t}\n\tmobj_free(mobj);\n}", "static TEE_Result default_mobj_init(void)\n{\n\tshm_mobj = mobj_phys_alloc(default_nsec_shm_paddr,\n\t\t\t\t default_nsec_shm_size, SHM_CACHE_ATTRS,\n\t\t\t\t CORE_MEM_NSEC_SHM);\n\tif (!shm_mobj)\n\t\tpanic(\"Failed to register shared memory\");", "#ifdef CFG_SECURE_DATA_PATH\n\tsdp_mem_mobjs = core_sdp_mem_create_mobjs();\n\tif (!sdp_mem_mobjs)\n\t\tpanic(\"Failed to register SDP memory\");\n#endif", "\treturn TEE_SUCCESS;\n}", "driver_init_late(default_mobj_init);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [111], "buggy_code_start_loc": [103], "filenames": ["core/arch/arm/tee/entry_std.c"], "fixing_code_end_loc": [121], "fixing_code_start_loc": [104], "message": "Linaro/OP-TEE OP-TEE Prior to version v3.4.0 is affected by: Boundary checks. The impact is: This could lead to corruption of any memory which the TA can access. The component is: optee_os. The fixed version is: v3.4.0.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linaro:op-tee:*:*:*:*:*:*:*:*", "matchCriteriaId": "E5151242-B2AA-44C7-8271-52C991A0FF8D", "versionEndExcluding": "3.4.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Linaro/OP-TEE OP-TEE Prior to version v3.4.0 is affected by: Boundary checks. The impact is: This could lead to corruption of any memory which the TA can access. The component is: optee_os. The fixed version is: v3.4.0."}, {"lang": "es", "value": "OP-TEE versiones anteriores a v3.4.0 de Linaro/OP-TEE, est\u00e1 afectada por: Comprobaciones de l\u00edmites. El impacto es: Esto podr\u00eda conllevar a la corrupci\u00f3n de cualquier memoria a la que pueda acceder el TA. El componente es: optee_os. La versi\u00f3n corregida es: v3.4.0."}], "evaluatorComment": null, "id": "CVE-2019-1010292", "lastModified": "2021-07-21T11:39:23.747", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2019-07-16T14:15:11.997", "references": [{"source": "josh@bress.net", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/OP-TEE/optee_os/commit/e3adcf566cb278444830e7badfdcc3983e334fd1"}], "sourceIdentifier": "josh@bress.net", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-787"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/OP-TEE/optee_os/commit/e3adcf566cb278444830e7badfdcc3983e334fd1"}, "type": "CWE-787"}
21
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\Bundle\\AdminBundle\\Controller\\Admin\\Asset;", "use League\\Flysystem\\FilesystemException;\nuse League\\Flysystem\\UnableToReadFile;\nuse PhpOffice\\PhpSpreadsheet\\Reader\\Csv;\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\nuse Pimcore\\Bundle\\AdminBundle\\Controller\\AdminController;\nuse Pimcore\\Bundle\\AdminBundle\\Helper\\GridHelperService;\nuse Pimcore\\Db;\nuse Pimcore\\Event\\AdminEvents;\nuse Pimcore\\Loader\\ImplementationLoader\\Exception\\UnsupportedException;\nuse Pimcore\\Localization\\LocaleServiceInterface;\nuse Pimcore\\Logger;\nuse Pimcore\\Model\\Asset;\nuse Pimcore\\Model\\Element;\nuse Pimcore\\Model\\GridConfig;\nuse Pimcore\\Model\\GridConfigFavourite;\nuse Pimcore\\Model\\GridConfigShare;\nuse Pimcore\\Model\\Metadata;\nuse Pimcore\\Model\\User;", "", "use Pimcore\\Tool;\nuse Pimcore\\Tool\\Storage;\nuse Pimcore\\Version;\nuse Symfony\\Component\\EventDispatcher\\GenericEvent;\nuse Symfony\\Component\\HttpFoundation\\BinaryFileResponse;\nuse Symfony\\Component\\HttpFoundation\\HeaderUtils;\nuse Symfony\\Component\\HttpFoundation\\JsonResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;", "/**\n * @Route(\"/asset-helper\")\n *\n * @internal\n */\nclass AssetHelperController extends AdminController\n{\n /**\n * @param int $userId\n * @param string $classId\n * @param string $searchType\n *\n * @return array\n */\n public function getMyOwnGridColumnConfigs($userId, $classId, $searchType)\n {\n $db = Db::get();\n $configListingConditionParts = [];\n $configListingConditionParts[] = 'ownerId = ' . $userId;\n $configListingConditionParts[] = 'classId = ' . $db->quote($classId);", " if ($searchType) {\n $configListingConditionParts[] = 'searchType = ' . $db->quote($searchType);\n }", " $configCondition = implode(' AND ', $configListingConditionParts);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition($configCondition);\n $configListing = $configListing->load();", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @param User $user\n * @param string $classId\n * @param string $searchType\n *\n * @return array\n */\n public function getSharedGridColumnConfigs($user, $classId, $searchType = null)\n {\n $db = Db::get();", " $configListing = [];", " $userIds = [$user->getId()];\n // collect all roles\n $userIds = array_merge($userIds, $user->getRoles());\n $userIds = implode(',', $userIds);", " $query = 'select distinct c1.id from gridconfigs c1, gridconfig_shares s\n where (c1.searchType = ' . $db->quote($searchType) . ' and ((c1.id = s.gridConfigId and s.sharedWithUserId IN (' . $userIds . '))) and c1.classId = ' . $db->quote($classId) . ')\n UNION distinct select c2.id from gridconfigs c2 where shareGlobally = 1 and c2.classId = '. $db->quote($classId) . ' and c2.ownerId != ' . $db->quote($user->getId());", " $ids = $db->fetchFirstColumn($query);", " if ($ids) {\n $ids = implode(',', $ids);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition('id in (' . $ids . ')');\n $configListing = $configListing->load();\n }", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @Route(\"/grid-delete-column-config\", name=\"pimcore_admin_asset_assethelper_griddeletecolumnconfig\", methods={\"DELETE\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridDeleteColumnConfigAction(Request $request)\n {\n $gridConfigId = $request->get('gridConfigId');\n $gridConfig = GridConfig::getById($gridConfigId);\n $success = false;\n if ($gridConfig) {\n if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $gridConfig->delete();\n $success = true;\n }", " $newGridConfig = $this->doGetGridColumnConfig($request, true);\n $newGridConfig['deleteSuccess'] = $success;", " return $this->adminJson($newGridConfig);\n }", " /**\n * @Route(\"/grid-get-column-config\", name=\"pimcore_admin_asset_assethelper_gridgetcolumnconfig\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridGetColumnConfigAction(Request $request)\n {\n $result = $this->doGetGridColumnConfig($request);", " return $this->adminJson($result);\n }", " /**\n * @param Request $request\n * @param bool $isDelete\n *\n * @return array\n */\n public function doGetGridColumnConfig(Request $request, $isDelete = false)\n {\n $gridConfigId = null;", " $classId = $request->get('id');\n $type = $request->get('type');", " $context = ['purpose' => 'gridconfig'];", " $types = [];\n if ($request->get('types')) {\n $types = explode(',', $request->get('types'));\n }", " $userId = $this->getAdminUser()->getId();", " $requestedGridConfigId = $isDelete ? null : $request->get('gridConfigId');", " // grid config\n $gridConfig = [];\n $searchType = $request->get('searchType');", " if (strlen($requestedGridConfigId) == 0) {\n // check if there is a favourite view\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $classId, 0, $searchType);", " if ($favourite) {\n $requestedGridConfigId = $favourite->getGridConfigId();\n }\n }", " if (is_numeric($requestedGridConfigId) && $requestedGridConfigId > 0) {\n $db = Db::get();\n $savedGridConfig = GridConfig::getById((int) $requestedGridConfigId);", " if ($savedGridConfig) {\n $shared = null;", " try {\n $userIds = [$this->getAdminUser()->getId()];\n if ($this->getAdminUser()->getRoles()) {\n $userIds = array_merge($userIds, $this->getAdminUser()->getRoles());\n }\n $userIds = implode(',', $userIds);\n $shared = ($savedGridConfig->getOwnerId() != $userId && $savedGridConfig->isShareGlobally()) || $db->fetchOne('select * from gridconfig_shares where sharedWithUserId IN (' . $userIds . ') and gridConfigId = ' . $savedGridConfig->getId());\n } catch (\\Exception $e) {\n }", " if (!$shared && $savedGridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception('You are neither the owner of this config nor it is shared with you');\n }\n $gridConfigId = $savedGridConfig->getId();\n $gridConfig = $savedGridConfig->getConfig();\n $gridConfig = json_decode($gridConfig, true);\n $gridConfigName = $savedGridConfig->getName();\n $gridConfigDescription = $savedGridConfig->getDescription();\n $sharedGlobally = $savedGridConfig->isShareGlobally();\n $setAsFavourite = $savedGridConfig->isSetAsFavourite();\n }\n }", " $availableFields = [];\n $language = '';", " if (empty($gridConfig)) {\n $availableFields = $this->getDefaultGridFields(\n $request->get('no_system_columns'),\n [], //maybe required for types other than metadata\n $context,\n $types);\n } else {\n $savedColumns = $gridConfig['columns'];", " foreach ($savedColumns as $key => $sc) {\n if (!$sc['hidden']) {\n $colConfig = $this->getFieldGridConfig($sc, $language, null);\n if ($colConfig) {\n $availableFields[] = $colConfig;\n }\n }\n }\n }\n usort($availableFields, function ($a, $b) {\n if ($a['position'] == $b['position']) {\n return 0;\n }", " return ($a['position'] < $b['position']) ? -1 : 1;\n });", " $availableConfigs = $classId ? $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType) : [];\n $sharedConfigs = $classId ? $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType) : [];\n $settings = $this->getShareSettings((int)$gridConfigId);\n $settings['gridConfigId'] = (int)$gridConfigId;\n $settings['gridConfigName'] = $gridConfigName ?? null;\n $settings['gridConfigDescription'] = $gridConfigDescription ?? null;\n $settings['shareGlobally'] = $sharedGlobally ?? null;\n $settings['setAsFavourite'] = $setAsFavourite ?? null;\n $settings['isShared'] = !$gridConfigId || ($shared ?? null);", " $context = $gridConfig['context'] ?? null;\n if ($context) {\n $context = json_decode($context, true);\n }", " return [\n 'sortinfo' => isset($gridConfig['sortinfo']) ? $gridConfig['sortinfo'] : false,\n 'availableFields' => $availableFields,\n 'settings' => $settings,\n 'onlyDirectChildren' => isset($gridConfig['onlyDirectChildren']) ? $gridConfig['onlyDirectChildren'] : false,\n 'onlyUnreferenced' => isset($gridConfig['onlyUnreferenced']) ? $gridConfig['onlyUnreferenced'] : false,\n 'pageSize' => isset($gridConfig['pageSize']) ? $gridConfig['pageSize'] : false,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n 'context' => $context,\n ];\n }", " /**\n * @param array $field\n * @param string $language\n * @param string|null $keyPrefix\n *\n * @return array|null\n */\n protected function getFieldGridConfig($field, $language = '', $keyPrefix = null)\n {\n $defaulMetadataFields = ['copyright', 'alt', 'title'];\n $predefined = null;", " if (isset($field['fieldConfig']['layout']['name'])) {\n $predefined = Metadata\\Predefined::getByName($field['fieldConfig']['layout']['name']);\n }", " $key = $field['name'];\n if ($keyPrefix) {\n $key = $keyPrefix . $key;\n }", " $fieldDef = explode('~', $field['name']);\n $field['name'] = $fieldDef[0];", " if (isset($fieldDef[1]) && $fieldDef[1] === 'system') {\n $type = 'system';\n } elseif (in_array($fieldDef[0], $defaulMetadataFields)) {\n $type = 'input';\n } else {\n $type = $field['fieldConfig']['type'];\n if (isset($fieldDef[1])) {\n $field['fieldConfig']['label'] = $field['fieldConfig']['layout']['title'] = $fieldDef[0] . ' (' . $fieldDef[1] . ')';\n $field['fieldConfig']['layout']['icon'] = Tool::getLanguageFlagFile($fieldDef[1], true);\n }\n }", " $result = [\n 'key' => $key,\n 'type' => $type,\n 'label' => $field['fieldConfig']['label'] ?? $key,\n 'width' => $field['width'],\n 'position' => $field['position'],\n 'language' => $field['fieldConfig']['language'] ?? null,\n 'layout' => $field['fieldConfig']['layout'] ?? null,\n ];", " if (isset($field['locked'])) {\n $result['locked'] = $field['locked'];\n }", " if ($type === 'select' && $predefined) {\n $field['fieldConfig']['layout']['config'] = $predefined->getConfig();\n $result['layout'] = $field['fieldConfig']['layout'];\n } elseif ($type === 'document' || $type === 'asset' || $type === 'object') {\n $result['layout']['fieldtype'] = 'manyToOneRelation';\n $result['layout']['subtype'] = $type;\n }", " return $result;\n }", " /**\n * @param bool $noSystemColumns\n * @param array $fields\n * @param array $context\n * @param array $types\n *\n * @return array\n */\n public function getDefaultGridFields($noSystemColumns, $fields, $context, $types = [])\n {\n $count = 0;\n $availableFields = [];", " if (!$noSystemColumns) {\n foreach (Asset\\Service::GRID_SYSTEM_COLUMNS as $sc) {\n if (empty($types)) {\n $availableFields[] = [\n 'key' => $sc . '~system',\n 'type' => 'system',\n 'label' => $sc,\n 'position' => $count, ];\n $count++;\n }\n }\n }", " return $availableFields;\n }", " /**\n * @Route(\"/prepare-helper-column-configs\", name=\"pimcore_admin_asset_assethelper_preparehelpercolumnconfigs\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function prepareHelperColumnConfigs(Request $request)\n {\n $helperColumns = [];\n $newData = [];\n $data = json_decode($request->get('columns'));\n /** @var \\stdClass $item */\n foreach ($data as $item) {\n if (!empty($item->isOperator)) {\n $itemKey = '#' . uniqid();", " $item->key = $itemKey;\n $newData[] = $item;\n $helperColumns[$itemKey] = $item;\n } else {\n $newData[] = $item;\n }\n }", " Tool\\Session::useSession(function (AttributeBagInterface $session) use ($helperColumns) {\n $existingColumns = $session->get('helpercolumns', []);\n $helperColumns = array_merge($helperColumns, $existingColumns);\n $session->set('helpercolumns', $helperColumns);\n }, 'pimcore_gridconfig');", " return $this->adminJson(['success' => true, 'columns' => $newData]);\n }", " /**\n * @Route(\"/grid-mark-favourite-column-config\", name=\"pimcore_admin_asset_assethelper_gridmarkfavouritecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridMarkFavouriteColumnConfigAction(Request $request)\n {\n $classId = $request->get('classId');\n $asset = Asset::getById($classId);", " if ($asset->isAllowed('list')) {\n $gridConfigId = $request->get('gridConfigId');\n $searchType = $request->get('searchType');\n $type = $request->get('type');\n $user = $this->getAdminUser();", " $favourite = new GridConfigFavourite();\n $favourite->setOwnerId($user->getId());\n $favourite->setClassId($classId);\n $favourite->setSearchType($searchType);\n $favourite->setType($type);\n $specializedConfigs = false;", " try {\n if ($gridConfigId != 0) {\n $gridConfig = GridConfig::getById($gridConfigId);\n $favourite->setGridConfigId($gridConfig->getId());\n }", " $favourite->setObjectId(0);\n $favourite->save();\n } catch (\\Exception $e) {\n $favourite->delete();\n }", " return $this->adminJson(['success' => true, 'spezializedConfigs' => $specializedConfigs]);\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param int $gridConfigId\n *\n * @return array\n */\n protected function getShareSettings($gridConfigId)\n {\n $result = [\n 'sharedUserIds' => [],\n 'sharedRoleIds' => [],\n ];", " $db = Db::get();\n $allShares = $db->fetchAllAssociative('select s.sharedWithUserId, u.type from gridconfig_shares s, users u\n where s.sharedWithUserId = u.id and s.gridConfigId = ' . $gridConfigId);", " if ($allShares) {\n foreach ($allShares as $share) {\n $type = $share['type'];\n $key = 'shared' . ucfirst($type) . 'Ids';\n $result[$key][] = $share['sharedWithUserId'];\n }\n }", " foreach ($result as $idx => $value) {\n $value = $value ? implode(',', $value) : '';\n $result[$idx] = $value;\n }", " return $result;\n }", " /**\n * @Route(\"/grid-save-column-config\", name=\"pimcore_admin_asset_assethelper_gridsavecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridSaveColumnConfigAction(Request $request)\n {\n $asset = Asset::getById((int) $request->get('id'));", " if (!$asset) {\n throw $this->createNotFoundException();\n }", " if ($asset->isAllowed('list')) {\n try {\n $classId = $request->get('class_id');\n $context = $request->get('context');", " $searchType = $request->get('searchType');\n $type = $request->get('type');", " // grid config\n $gridConfigData = $this->decodeJson($request->get('gridconfig'));\n $gridConfigData['pimcore_version'] = Version::getVersion();\n $gridConfigData['pimcore_revision'] = Version::getRevision();\n $gridConfigData['context'] = $context;\n unset($gridConfigData['settings']['isShared']);", " $metadata = $request->get('settings');\n $metadata = json_decode($metadata, true);", " $gridConfigId = $metadata['gridConfigId'];\n $gridConfig = GridConfig::getById($gridConfigId);", " if ($gridConfig && $gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess around with somebody else's configuration\");\n }", " $this->updateGridConfigShares($gridConfig, $metadata);", " if ($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin()) {\n $this->updateGridConfigFavourites($gridConfig, $metadata);\n }", " if (!$gridConfig) {\n $gridConfig = new GridConfig();\n $gridConfig->setName(date('c'));\n $gridConfig->setClassId($classId);\n $gridConfig->setSearchType($searchType);\n $gridConfig->setType($type);", " $gridConfig->setOwnerId($this->getAdminUser()->getId());\n }", " if ($metadata) {\n $gridConfig->setName($metadata['gridConfigName']);\n $gridConfig->setDescription($metadata['gridConfigDescription']);\n $gridConfig->setShareGlobally($metadata['shareGlobally'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSetAsFavourite($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin());\n }", " $gridConfigData = json_encode($gridConfigData);\n $gridConfig->setConfig($gridConfigData);\n $gridConfig->save();", " $userId = $this->getAdminUser()->getId();", " $availableConfigs = $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType);\n $sharedConfigs = $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType);", " $settings = $this->getShareSettings($gridConfig->getId());\n $settings['gridConfigId'] = (int)$gridConfig->getId();\n $settings['gridConfigName'] = $gridConfig->getName();\n $settings['gridConfigDescription'] = $gridConfig->getDescription();\n $settings['shareGlobally'] = $gridConfig->isShareGlobally();\n $settings['setAsFavourite'] = $gridConfig->isSetAsFavourite();\n $settings['isShared'] = $gridConfig->getOwnerId() != $this->getAdminUser()->getId();", " return $this->adminJson([\n 'success' => true,\n 'settings' => $settings,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n *\n * @throws \\Exception\n */\n protected function updateGridConfigShares($gridConfig, $metadata)\n {\n $user = $this->getAdminUser();\n if (!$gridConfig || !$user->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n $combinedShares = [];\n $sharedUserIds = $metadata['sharedUserIds'];\n $sharedRoleIds = $metadata['sharedRoleIds'];", " if ($sharedUserIds) {\n $combinedShares = explode(',', $sharedUserIds);\n }", " if ($sharedRoleIds) {\n $sharedRoleIds = explode(',', $sharedRoleIds);\n $combinedShares = array_merge($combinedShares, $sharedRoleIds);\n }", " $db = Db::get();\n $db->delete('gridconfig_shares', ['gridConfigId' => $gridConfig->getId()]);", " foreach ($combinedShares as $id) {\n $share = new GridConfigShare();\n $share->setGridConfigId($gridConfig->getId());\n $share->setSharedWithUserId((int) $id);\n $share->save();\n }\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n *\n * @throws \\Exception\n */\n protected function updateGridConfigFavourites($gridConfig, $metadata)\n {\n $currentUser = $this->getAdminUser();", " if (!$gridConfig || $currentUser === null || !$currentUser->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if (!$currentUser->isAdmin() && (int) $gridConfig->getOwnerId() !== $currentUser->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $sharedUsers = [];", " if ($metadata['shareGlobally'] === false) {\n $sharedUserIds = $metadata['sharedUserIds'];", " if ($sharedUserIds) {\n $sharedUsers = explode(',', $sharedUserIds);\n }\n }", " if ($metadata['shareGlobally'] === true) {\n $users = new User\\Listing();\n $users->setCondition('id = ?', $currentUser->getId());", " foreach ($users as $user) {\n $sharedUsers[] = $user->getId();\n }\n }", " foreach ($sharedUsers as $id) {\n // Check if the user has already a favourite\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n (int) $id,\n $gridConfig->getClassId(),\n 0,\n $gridConfig->getSearchType()\n );", " if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());", " if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ((bool) $favouriteGridConfig->isShareGlobally() === false) {\n continue;\n }", " // Check if the user is the owner. If that is the case we do not update the favourite\n if ((int) $favouriteGridConfig->getOwnerId() === (int) $id) {\n continue;\n }\n }\n }", " $favourite = new GridConfigFavourite();\n $favourite->setGridConfigId($gridConfig->getId());\n $favourite->setClassId($gridConfig->getClassId());\n $favourite->setObjectId(0);\n $favourite->setOwnerId($id);\n $favourite->setType($gridConfig->getType());\n $favourite->setSearchType($gridConfig->getSearchType());\n $favourite->save();\n }\n }", " /**\n * @Route(\"/get-export-jobs\", name=\"pimcore_admin_asset_assethelper_getexportjobs\", methods={\"POST\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n *\n * @return JsonResponse\n */\n public function getExportJobsAction(Request $request, GridHelperService $gridHelperService)\n {\n $allParams = array_merge($request->request->all(), $request->query->all());\n $list = $gridHelperService->prepareAssetListingForGrid($allParams, $this->getAdminUser());", " if (empty($ids = $allParams['ids'] ?? '')) {\n $ids = $list->loadIdList();\n }", " $jobs = array_chunk($ids, 20);", " $fileHandle = uniqid('asset-export-');\n $storage = Storage::get('temp');\n $storage->write($this->getCsvFile($fileHandle), '');", " return $this->adminJson(['success' => true, 'jobs' => $jobs, 'fileHandle' => $fileHandle]);\n }", " /**\n * @Route(\"/do-export\", name=\"pimcore_admin_asset_assethelper_doexport\", methods={\"POST\"})\n *\n * @param Request $request\n * @param LocaleServiceInterface $localeService\n *\n * @return JsonResponse\n */\n public function doExportAction(Request $request, LocaleServiceInterface $localeService)\n {\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $ids = $request->get('ids');\n $settings = $request->get('settings');\n $settings = json_decode($settings, true);\n $delimiter = $settings['delimiter'] ?? ';';\n $language = str_replace('default', '', $request->get('language'));", " $list = new Asset\\Listing();", " $quotedIds = [];\n foreach ($ids as $id) {\n $quotedIds[] = $list->quote($id);\n }", " $list->setCondition('id IN (' . implode(',', $quotedIds) . ')');\n $list->setOrderKey(' FIELD(id, ' . implode(',', $quotedIds) . ')', false);", " $fields = $request->get('fields');", " $addTitles = $request->get('initial');", " $csv = $this->getCsvData($request, $language, $list, $fields, $addTitles);", " $storage = Storage::get('temp');\n $csvFile = $this->getCsvFile($fileHandle);", " $fileStream = $storage->readStream($csvFile);", " $temp = tmpfile();\n stream_copy_to_stream($fileStream, $temp, null, 0);", " $firstLine = true;\n foreach ($csv as $line) {\n if ($addTitles && $firstLine) {\n $firstLine = false;\n $line = implode($delimiter, $line) . \"\\r\\n\";\n fwrite($temp, $line);\n } else {\n fwrite($temp, implode($delimiter, array_map([$this, 'encodeFunc'], $line)) . \"\\r\\n\");\n }\n }", " $storage->writeStream($csvFile, $temp);", " return $this->adminJson(['success' => true]);\n }", " public function encodeFunc($value)\n {\n $value = str_replace('\"', '\"\"', $value);\n //force wrap value in quotes and return\n return '\"' . $value . '\"';\n }", " /**\n * @param Request $request\n * @param string $language\n * @param Asset\\Listing $list\n * @param array $fields\n * @param bool $addTitles\n *\n * @return array\n */\n protected function getCsvData(Request $request, $language, $list, $fields, $addTitles = true)\n {\n //create csv\n $csv = [];", " $unsupportedFields = ['preview~system', 'size~system'];\n $fields = array_diff($fields, $unsupportedFields);", " if ($addTitles) {\n $columns = $fields;\n foreach ($columns as $columnIdx => $columnKey) {\n $columns[$columnIdx] = '\"' . $columnKey . '\"';\n }\n $csv[] = $columns;\n }", " foreach ($list->load() as $asset) {\n if ($fields) {\n $dataRows = [];\n foreach ($fields as $field) {\n $fieldDef = explode('~', $field);\n $getter = 'get' . ucfirst($fieldDef[0]);", " if (isset($fieldDef[1])) {\n if ($fieldDef[1] == 'system' && method_exists($asset, $getter)) {\n $data = $asset->$getter($language);\n } else {\n $fieldDef[1] = str_replace('none', '', $fieldDef[1]);\n $data = $asset->getMetadata($fieldDef[0], $fieldDef[1], true);\n }\n } else {\n $data = $asset->getMetadata($field, $language, true);\n }", " if ($data instanceof Element\\ElementInterface) {\n $data = $data->getRealFullPath();\n }\n $dataRows[] = $data;\n }\n $dataRows = Element\\Service::escapeCsvRecord($dataRows);\n $csv[] = $dataRows;\n }\n }", " return $csv;\n }", " /**\n * @param Request $request\n *\n * @return string\n */\n protected function extractLanguage(Request $request)\n {\n $requestedLanguage = $request->get('language');\n if ($requestedLanguage) {\n if ($requestedLanguage != 'default') {\n $request->setLocale($requestedLanguage);\n }\n } else {\n $requestedLanguage = $request->getLocale();\n }", " return $requestedLanguage;\n }", " /**\n * @param string $fileHandle\n *\n * @return string\n */\n protected function getCsvFile($fileHandle)\n {\n return $fileHandle . '.csv';\n }", " /**\n * @Route(\"/download-csv-file\", name=\"pimcore_admin_asset_assethelper_downloadcsvfile\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return Response\n */\n public function downloadCsvFileAction(Request $request)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n $csvData = $storage->read($csvFile);\n $response = new Response($csvData);\n $response->headers->set('Content-Type', 'application/csv');\n $disposition = HeaderUtils::makeDisposition(\n HeaderUtils::DISPOSITION_ATTACHMENT,\n 'export.csv'\n );", " $response->headers->set('Content-Disposition', $disposition);\n $storage->delete($csvFile);", " return $response;\n } catch (FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('CSV file not found');\n }\n }", " /**\n * @Route(\"/download-xlsx-file\", name=\"pimcore_admin_asset_assethelper_downloadxlsxfile\", methods={\"GET\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n *\n * @return BinaryFileResponse\n */\n public function downloadXlsxFileAction(Request $request, GridHelperService $gridHelperService)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n return $gridHelperService->createXlsxExportFile($storage, $fileHandle, $csvFile);\n } catch (\\Exception | FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('XLSX file not found');\n }\n }", " /**\n * @Route(\"/get-metadata-for-column-config\", name=\"pimcore_admin_asset_assethelper_getmetadataforcolumnconfig\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getMetadataForColumnConfigAction(Request $request)\n {\n $result = [];", " //default metadata\n $defaultMetadataNames = ['copyright', 'alt', 'title'];\n foreach ($defaultMetadataNames as $defaultMetadata) {\n $defaultColumns[] = ['title' => $defaultMetadata, 'name' => $defaultMetadata, 'datatype' => 'data', 'fieldtype' => 'input'];\n }\n $result['defaultColumns']['nodeLabel'] = 'default_metadata';\n $result['defaultColumns']['nodeType'] = 'image';\n $result['defaultColumns']['children'] = $defaultColumns;", " //predefined metadata\n $list = Metadata\\Predefined\\Listing::getByTargetType('asset');\n $metadataItems = [];\n $tmp = [];\n foreach ($list as $item) {\n //only allow unique metadata columns with subtypes\n $uniqueKey = $item->getName().'_'.$item->getTargetSubtype();\n if (!in_array($uniqueKey, $tmp) && !in_array($item->getName(), $defaultMetadataNames)) {\n $tmp[] = $uniqueKey;\n $item->expand();", "", " $metadataItems[] = [", " 'title' => $item->getName(),\n 'name' => $item->getName(),", " 'subtype' => $item->getTargetSubtype(),\n 'datatype' => 'data',\n 'fieldtype' => $item->getType(),\n 'config' => $item->getConfig(),\n ];\n }\n }", " $result['metadataColumns']['children'] = $metadataItems;\n $result['metadataColumns']['nodeLabel'] = 'predefined_metadata';\n $result['metadataColumns']['nodeType'] = 'metadata';", " //system columns\n $systemColumnNames = Asset\\Service::GRID_SYSTEM_COLUMNS;\n $systemColumns = [];\n foreach ($systemColumnNames as $systemColumn) {\n $systemColumns[] = ['title' => $systemColumn, 'name' => $systemColumn, 'datatype' => 'data', 'fieldtype' => 'system'];\n }\n $result['systemColumns']['nodeLabel'] = 'system_columns';\n $result['systemColumns']['nodeType'] = 'system';\n $result['systemColumns']['children'] = $systemColumns;", " return $this->adminJson($result);\n }", " /**\n * @Route(\"/get-batch-jobs\", name=\"pimcore_admin_asset_assethelper_getbatchjobs\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getBatchJobsAction(Request $request, GridHelperService $gridHelperService)\n {\n if ($request->get('language')) {\n $request->setLocale($request->get('language'));\n }", " $allParams = array_merge($request->request->all(), $request->query->all());\n $list = $gridHelperService->prepareAssetListingForGrid($allParams, $this->getAdminUser());", " $jobs = $list->loadIdList();", " return $this->adminJson(['success' => true, 'jobs' => $jobs]);\n }", " /**\n * @Route(\"/batch\", name=\"pimcore_admin_asset_assethelper_batch\", methods={\"PUT\"})\n *\n * @param Request $request\n * @param EventDispatcherInterface $eventDispatcher\n *\n * @return JsonResponse\n */\n public function batchAction(Request $request, EventDispatcherInterface $eventDispatcher)\n {\n try {\n if ($request->get('data')) {\n $loader = \\Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data');", " $data = $this->decodeJson($request->get('data'), true);", " $updateEvent = new GenericEvent($this, [\n 'data' => $data,\n 'processed' => false,\n ]);", " $eventDispatcher->dispatch($updateEvent, AdminEvents::ASSET_LIST_BEFORE_BATCH_UPDATE);", " $processed = $updateEvent->getArgument('processed');", " if ($processed) {\n return $this->adminJson(['success' => true]);\n }", " $language = null;\n if (isset($data['language'])) {\n $language = $data['language'] != 'default' ? $data['language'] : null;\n }", " $asset = Asset::getById($data['job']);", " if ($asset) {\n if (!$asset->isAllowed('publish')) {\n throw new \\Exception(\"Permission denied. You don't have the rights to save this asset.\");\n }", " $metadata = $asset->getMetadata(null, null, false, true);\n $dirty = false;", " $name = $data['name'];\n $value = $data['value'];", " if ($data['valueType'] == 'object') {\n $value = $this->decodeJson($value);\n }", " $fieldDef = explode('~', $name);\n $name = $fieldDef[0];\n if (count($fieldDef) > 1) {\n $language = ($fieldDef[1] == 'none' ? '' : $fieldDef[1]);\n }", " foreach ($metadata as $idx => &$em) {\n if ($em['name'] == $name && $em['language'] == $language) {\n try {\n $dataImpl = $loader->build($em['type']);\n $value = $dataImpl->getDataFromListfolderGrid($value, $em);\n } catch (UnsupportedException $le) {\n Logger::error('could not resolve metadata implementation for ' . $em['type']);\n }\n $em['data'] = $value;\n $dirty = true;", " break;\n }\n }", " if (!$dirty) {\n $defaulMetadata = ['title', 'alt', 'copyright'];\n if (in_array($name, $defaulMetadata)) {\n $newEm = [\n 'name' => $name,\n 'language' => $language,\n 'type' => 'input',\n 'data' => $value,\n ];", " try {\n $dataImpl = $loader->build($newEm['type']);\n $newEm['data'] = $dataImpl->getDataFromListfolderGrid($value, $newEm);\n } catch (UnsupportedException $le) {\n Logger::error('could not resolve metadata implementation for ' . $newEm['type']);\n }", " $metadata[] = $newEm;\n $dirty = true;\n } else {\n $predefined = Metadata\\Predefined::getByName($name);\n if ($predefined && (empty($predefined->getTargetSubtype())\n || $predefined->getTargetSubtype() == $asset->getType())) {\n $newEm = [\n 'name' => $name,\n 'language' => $language,\n 'type' => $predefined->getType(),\n 'data' => $value,\n ];", " try {\n $dataImpl = $loader->build($newEm['type']);\n $newEm['data'] = $dataImpl->getDataFromListfolderGrid($value, $newEm);\n } catch (UnsupportedException $le) {\n Logger::error('could not resolve metadata implementation for ' . $newEm['type']);\n }", " $metadata[] = $newEm;", " $dirty = true;\n }\n }\n }", " try {\n if ($dirty) {\n // $metadata = Asset\\Service::minimizeMetadata($metadata, \"grid\");\n $asset->setMetadataRaw($metadata);\n $asset->save();", " return $this->adminJson(['success' => true]);\n }\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n } else {\n Logger::debug('AssetHelperController::batchAction => There is no asset left to update.');", " return $this->adminJson(['success' => false, 'message' => 'AssetHelperController::batchAction => There is no asset left to update.']);\n }\n }\n } catch (\\Exception $e) {\n Logger::err($e);", " return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }", " return $this->adminJson(['success' => false, 'message' => 'something went wrong.']);\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\Bundle\\AdminBundle\\Controller\\Admin\\Asset;", "use League\\Flysystem\\FilesystemException;\nuse League\\Flysystem\\UnableToReadFile;\nuse PhpOffice\\PhpSpreadsheet\\Reader\\Csv;\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\nuse Pimcore\\Bundle\\AdminBundle\\Controller\\AdminController;\nuse Pimcore\\Bundle\\AdminBundle\\Helper\\GridHelperService;\nuse Pimcore\\Db;\nuse Pimcore\\Event\\AdminEvents;\nuse Pimcore\\Loader\\ImplementationLoader\\Exception\\UnsupportedException;\nuse Pimcore\\Localization\\LocaleServiceInterface;\nuse Pimcore\\Logger;\nuse Pimcore\\Model\\Asset;\nuse Pimcore\\Model\\Element;\nuse Pimcore\\Model\\GridConfig;\nuse Pimcore\\Model\\GridConfigFavourite;\nuse Pimcore\\Model\\GridConfigShare;\nuse Pimcore\\Model\\Metadata;\nuse Pimcore\\Model\\User;", "use Pimcore\\Security\\SecurityHelper;", "use Pimcore\\Tool;\nuse Pimcore\\Tool\\Storage;\nuse Pimcore\\Version;\nuse Symfony\\Component\\EventDispatcher\\GenericEvent;\nuse Symfony\\Component\\HttpFoundation\\BinaryFileResponse;\nuse Symfony\\Component\\HttpFoundation\\HeaderUtils;\nuse Symfony\\Component\\HttpFoundation\\JsonResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;", "/**\n * @Route(\"/asset-helper\")\n *\n * @internal\n */\nclass AssetHelperController extends AdminController\n{\n /**\n * @param int $userId\n * @param string $classId\n * @param string $searchType\n *\n * @return array\n */\n public function getMyOwnGridColumnConfigs($userId, $classId, $searchType)\n {\n $db = Db::get();\n $configListingConditionParts = [];\n $configListingConditionParts[] = 'ownerId = ' . $userId;\n $configListingConditionParts[] = 'classId = ' . $db->quote($classId);", " if ($searchType) {\n $configListingConditionParts[] = 'searchType = ' . $db->quote($searchType);\n }", " $configCondition = implode(' AND ', $configListingConditionParts);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition($configCondition);\n $configListing = $configListing->load();", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @param User $user\n * @param string $classId\n * @param string $searchType\n *\n * @return array\n */\n public function getSharedGridColumnConfigs($user, $classId, $searchType = null)\n {\n $db = Db::get();", " $configListing = [];", " $userIds = [$user->getId()];\n // collect all roles\n $userIds = array_merge($userIds, $user->getRoles());\n $userIds = implode(',', $userIds);", " $query = 'select distinct c1.id from gridconfigs c1, gridconfig_shares s\n where (c1.searchType = ' . $db->quote($searchType) . ' and ((c1.id = s.gridConfigId and s.sharedWithUserId IN (' . $userIds . '))) and c1.classId = ' . $db->quote($classId) . ')\n UNION distinct select c2.id from gridconfigs c2 where shareGlobally = 1 and c2.classId = '. $db->quote($classId) . ' and c2.ownerId != ' . $db->quote($user->getId());", " $ids = $db->fetchFirstColumn($query);", " if ($ids) {\n $ids = implode(',', $ids);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition('id in (' . $ids . ')');\n $configListing = $configListing->load();\n }", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @Route(\"/grid-delete-column-config\", name=\"pimcore_admin_asset_assethelper_griddeletecolumnconfig\", methods={\"DELETE\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridDeleteColumnConfigAction(Request $request)\n {\n $gridConfigId = $request->get('gridConfigId');\n $gridConfig = GridConfig::getById($gridConfigId);\n $success = false;\n if ($gridConfig) {\n if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $gridConfig->delete();\n $success = true;\n }", " $newGridConfig = $this->doGetGridColumnConfig($request, true);\n $newGridConfig['deleteSuccess'] = $success;", " return $this->adminJson($newGridConfig);\n }", " /**\n * @Route(\"/grid-get-column-config\", name=\"pimcore_admin_asset_assethelper_gridgetcolumnconfig\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridGetColumnConfigAction(Request $request)\n {\n $result = $this->doGetGridColumnConfig($request);", " return $this->adminJson($result);\n }", " /**\n * @param Request $request\n * @param bool $isDelete\n *\n * @return array\n */\n public function doGetGridColumnConfig(Request $request, $isDelete = false)\n {\n $gridConfigId = null;", " $classId = $request->get('id');\n $type = $request->get('type');", " $context = ['purpose' => 'gridconfig'];", " $types = [];\n if ($request->get('types')) {\n $types = explode(',', $request->get('types'));\n }", " $userId = $this->getAdminUser()->getId();", " $requestedGridConfigId = $isDelete ? null : $request->get('gridConfigId');", " // grid config\n $gridConfig = [];\n $searchType = $request->get('searchType');", " if (strlen($requestedGridConfigId) == 0) {\n // check if there is a favourite view\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $classId, 0, $searchType);", " if ($favourite) {\n $requestedGridConfigId = $favourite->getGridConfigId();\n }\n }", " if (is_numeric($requestedGridConfigId) && $requestedGridConfigId > 0) {\n $db = Db::get();\n $savedGridConfig = GridConfig::getById((int) $requestedGridConfigId);", " if ($savedGridConfig) {\n $shared = null;", " try {\n $userIds = [$this->getAdminUser()->getId()];\n if ($this->getAdminUser()->getRoles()) {\n $userIds = array_merge($userIds, $this->getAdminUser()->getRoles());\n }\n $userIds = implode(',', $userIds);\n $shared = ($savedGridConfig->getOwnerId() != $userId && $savedGridConfig->isShareGlobally()) || $db->fetchOne('select * from gridconfig_shares where sharedWithUserId IN (' . $userIds . ') and gridConfigId = ' . $savedGridConfig->getId());\n } catch (\\Exception $e) {\n }", " if (!$shared && $savedGridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception('You are neither the owner of this config nor it is shared with you');\n }\n $gridConfigId = $savedGridConfig->getId();\n $gridConfig = $savedGridConfig->getConfig();\n $gridConfig = json_decode($gridConfig, true);\n $gridConfigName = $savedGridConfig->getName();\n $gridConfigDescription = $savedGridConfig->getDescription();\n $sharedGlobally = $savedGridConfig->isShareGlobally();\n $setAsFavourite = $savedGridConfig->isSetAsFavourite();\n }\n }", " $availableFields = [];\n $language = '';", " if (empty($gridConfig)) {\n $availableFields = $this->getDefaultGridFields(\n $request->get('no_system_columns'),\n [], //maybe required for types other than metadata\n $context,\n $types);\n } else {\n $savedColumns = $gridConfig['columns'];", " foreach ($savedColumns as $key => $sc) {\n if (!$sc['hidden']) {\n $colConfig = $this->getFieldGridConfig($sc, $language, null);\n if ($colConfig) {\n $availableFields[] = $colConfig;\n }\n }\n }\n }\n usort($availableFields, function ($a, $b) {\n if ($a['position'] == $b['position']) {\n return 0;\n }", " return ($a['position'] < $b['position']) ? -1 : 1;\n });", " $availableConfigs = $classId ? $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType) : [];\n $sharedConfigs = $classId ? $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType) : [];\n $settings = $this->getShareSettings((int)$gridConfigId);\n $settings['gridConfigId'] = (int)$gridConfigId;\n $settings['gridConfigName'] = $gridConfigName ?? null;\n $settings['gridConfigDescription'] = $gridConfigDescription ?? null;\n $settings['shareGlobally'] = $sharedGlobally ?? null;\n $settings['setAsFavourite'] = $setAsFavourite ?? null;\n $settings['isShared'] = !$gridConfigId || ($shared ?? null);", " $context = $gridConfig['context'] ?? null;\n if ($context) {\n $context = json_decode($context, true);\n }", " return [\n 'sortinfo' => isset($gridConfig['sortinfo']) ? $gridConfig['sortinfo'] : false,\n 'availableFields' => $availableFields,\n 'settings' => $settings,\n 'onlyDirectChildren' => isset($gridConfig['onlyDirectChildren']) ? $gridConfig['onlyDirectChildren'] : false,\n 'onlyUnreferenced' => isset($gridConfig['onlyUnreferenced']) ? $gridConfig['onlyUnreferenced'] : false,\n 'pageSize' => isset($gridConfig['pageSize']) ? $gridConfig['pageSize'] : false,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n 'context' => $context,\n ];\n }", " /**\n * @param array $field\n * @param string $language\n * @param string|null $keyPrefix\n *\n * @return array|null\n */\n protected function getFieldGridConfig($field, $language = '', $keyPrefix = null)\n {\n $defaulMetadataFields = ['copyright', 'alt', 'title'];\n $predefined = null;", " if (isset($field['fieldConfig']['layout']['name'])) {\n $predefined = Metadata\\Predefined::getByName($field['fieldConfig']['layout']['name']);\n }", " $key = $field['name'];\n if ($keyPrefix) {\n $key = $keyPrefix . $key;\n }", " $fieldDef = explode('~', $field['name']);\n $field['name'] = $fieldDef[0];", " if (isset($fieldDef[1]) && $fieldDef[1] === 'system') {\n $type = 'system';\n } elseif (in_array($fieldDef[0], $defaulMetadataFields)) {\n $type = 'input';\n } else {\n $type = $field['fieldConfig']['type'];\n if (isset($fieldDef[1])) {\n $field['fieldConfig']['label'] = $field['fieldConfig']['layout']['title'] = $fieldDef[0] . ' (' . $fieldDef[1] . ')';\n $field['fieldConfig']['layout']['icon'] = Tool::getLanguageFlagFile($fieldDef[1], true);\n }\n }", " $result = [\n 'key' => $key,\n 'type' => $type,\n 'label' => $field['fieldConfig']['label'] ?? $key,\n 'width' => $field['width'],\n 'position' => $field['position'],\n 'language' => $field['fieldConfig']['language'] ?? null,\n 'layout' => $field['fieldConfig']['layout'] ?? null,\n ];", " if (isset($field['locked'])) {\n $result['locked'] = $field['locked'];\n }", " if ($type === 'select' && $predefined) {\n $field['fieldConfig']['layout']['config'] = $predefined->getConfig();\n $result['layout'] = $field['fieldConfig']['layout'];\n } elseif ($type === 'document' || $type === 'asset' || $type === 'object') {\n $result['layout']['fieldtype'] = 'manyToOneRelation';\n $result['layout']['subtype'] = $type;\n }", " return $result;\n }", " /**\n * @param bool $noSystemColumns\n * @param array $fields\n * @param array $context\n * @param array $types\n *\n * @return array\n */\n public function getDefaultGridFields($noSystemColumns, $fields, $context, $types = [])\n {\n $count = 0;\n $availableFields = [];", " if (!$noSystemColumns) {\n foreach (Asset\\Service::GRID_SYSTEM_COLUMNS as $sc) {\n if (empty($types)) {\n $availableFields[] = [\n 'key' => $sc . '~system',\n 'type' => 'system',\n 'label' => $sc,\n 'position' => $count, ];\n $count++;\n }\n }\n }", " return $availableFields;\n }", " /**\n * @Route(\"/prepare-helper-column-configs\", name=\"pimcore_admin_asset_assethelper_preparehelpercolumnconfigs\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function prepareHelperColumnConfigs(Request $request)\n {\n $helperColumns = [];\n $newData = [];\n $data = json_decode($request->get('columns'));\n /** @var \\stdClass $item */\n foreach ($data as $item) {\n if (!empty($item->isOperator)) {\n $itemKey = '#' . uniqid();", " $item->key = $itemKey;\n $newData[] = $item;\n $helperColumns[$itemKey] = $item;\n } else {\n $newData[] = $item;\n }\n }", " Tool\\Session::useSession(function (AttributeBagInterface $session) use ($helperColumns) {\n $existingColumns = $session->get('helpercolumns', []);\n $helperColumns = array_merge($helperColumns, $existingColumns);\n $session->set('helpercolumns', $helperColumns);\n }, 'pimcore_gridconfig');", " return $this->adminJson(['success' => true, 'columns' => $newData]);\n }", " /**\n * @Route(\"/grid-mark-favourite-column-config\", name=\"pimcore_admin_asset_assethelper_gridmarkfavouritecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridMarkFavouriteColumnConfigAction(Request $request)\n {\n $classId = $request->get('classId');\n $asset = Asset::getById($classId);", " if ($asset->isAllowed('list')) {\n $gridConfigId = $request->get('gridConfigId');\n $searchType = $request->get('searchType');\n $type = $request->get('type');\n $user = $this->getAdminUser();", " $favourite = new GridConfigFavourite();\n $favourite->setOwnerId($user->getId());\n $favourite->setClassId($classId);\n $favourite->setSearchType($searchType);\n $favourite->setType($type);\n $specializedConfigs = false;", " try {\n if ($gridConfigId != 0) {\n $gridConfig = GridConfig::getById($gridConfigId);\n $favourite->setGridConfigId($gridConfig->getId());\n }", " $favourite->setObjectId(0);\n $favourite->save();\n } catch (\\Exception $e) {\n $favourite->delete();\n }", " return $this->adminJson(['success' => true, 'spezializedConfigs' => $specializedConfigs]);\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param int $gridConfigId\n *\n * @return array\n */\n protected function getShareSettings($gridConfigId)\n {\n $result = [\n 'sharedUserIds' => [],\n 'sharedRoleIds' => [],\n ];", " $db = Db::get();\n $allShares = $db->fetchAllAssociative('select s.sharedWithUserId, u.type from gridconfig_shares s, users u\n where s.sharedWithUserId = u.id and s.gridConfigId = ' . $gridConfigId);", " if ($allShares) {\n foreach ($allShares as $share) {\n $type = $share['type'];\n $key = 'shared' . ucfirst($type) . 'Ids';\n $result[$key][] = $share['sharedWithUserId'];\n }\n }", " foreach ($result as $idx => $value) {\n $value = $value ? implode(',', $value) : '';\n $result[$idx] = $value;\n }", " return $result;\n }", " /**\n * @Route(\"/grid-save-column-config\", name=\"pimcore_admin_asset_assethelper_gridsavecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridSaveColumnConfigAction(Request $request)\n {\n $asset = Asset::getById((int) $request->get('id'));", " if (!$asset) {\n throw $this->createNotFoundException();\n }", " if ($asset->isAllowed('list')) {\n try {\n $classId = $request->get('class_id');\n $context = $request->get('context');", " $searchType = $request->get('searchType');\n $type = $request->get('type');", " // grid config\n $gridConfigData = $this->decodeJson($request->get('gridconfig'));\n $gridConfigData['pimcore_version'] = Version::getVersion();\n $gridConfigData['pimcore_revision'] = Version::getRevision();\n $gridConfigData['context'] = $context;\n unset($gridConfigData['settings']['isShared']);", " $metadata = $request->get('settings');\n $metadata = json_decode($metadata, true);", " $gridConfigId = $metadata['gridConfigId'];\n $gridConfig = GridConfig::getById($gridConfigId);", " if ($gridConfig && $gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess around with somebody else's configuration\");\n }", " $this->updateGridConfigShares($gridConfig, $metadata);", " if ($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin()) {\n $this->updateGridConfigFavourites($gridConfig, $metadata);\n }", " if (!$gridConfig) {\n $gridConfig = new GridConfig();\n $gridConfig->setName(date('c'));\n $gridConfig->setClassId($classId);\n $gridConfig->setSearchType($searchType);\n $gridConfig->setType($type);", " $gridConfig->setOwnerId($this->getAdminUser()->getId());\n }", " if ($metadata) {\n $gridConfig->setName($metadata['gridConfigName']);\n $gridConfig->setDescription($metadata['gridConfigDescription']);\n $gridConfig->setShareGlobally($metadata['shareGlobally'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSetAsFavourite($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin());\n }", " $gridConfigData = json_encode($gridConfigData);\n $gridConfig->setConfig($gridConfigData);\n $gridConfig->save();", " $userId = $this->getAdminUser()->getId();", " $availableConfigs = $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType);\n $sharedConfigs = $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType);", " $settings = $this->getShareSettings($gridConfig->getId());\n $settings['gridConfigId'] = (int)$gridConfig->getId();\n $settings['gridConfigName'] = $gridConfig->getName();\n $settings['gridConfigDescription'] = $gridConfig->getDescription();\n $settings['shareGlobally'] = $gridConfig->isShareGlobally();\n $settings['setAsFavourite'] = $gridConfig->isSetAsFavourite();\n $settings['isShared'] = $gridConfig->getOwnerId() != $this->getAdminUser()->getId();", " return $this->adminJson([\n 'success' => true,\n 'settings' => $settings,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n *\n * @throws \\Exception\n */\n protected function updateGridConfigShares($gridConfig, $metadata)\n {\n $user = $this->getAdminUser();\n if (!$gridConfig || !$user->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n $combinedShares = [];\n $sharedUserIds = $metadata['sharedUserIds'];\n $sharedRoleIds = $metadata['sharedRoleIds'];", " if ($sharedUserIds) {\n $combinedShares = explode(',', $sharedUserIds);\n }", " if ($sharedRoleIds) {\n $sharedRoleIds = explode(',', $sharedRoleIds);\n $combinedShares = array_merge($combinedShares, $sharedRoleIds);\n }", " $db = Db::get();\n $db->delete('gridconfig_shares', ['gridConfigId' => $gridConfig->getId()]);", " foreach ($combinedShares as $id) {\n $share = new GridConfigShare();\n $share->setGridConfigId($gridConfig->getId());\n $share->setSharedWithUserId((int) $id);\n $share->save();\n }\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n *\n * @throws \\Exception\n */\n protected function updateGridConfigFavourites($gridConfig, $metadata)\n {\n $currentUser = $this->getAdminUser();", " if (!$gridConfig || $currentUser === null || !$currentUser->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if (!$currentUser->isAdmin() && (int) $gridConfig->getOwnerId() !== $currentUser->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $sharedUsers = [];", " if ($metadata['shareGlobally'] === false) {\n $sharedUserIds = $metadata['sharedUserIds'];", " if ($sharedUserIds) {\n $sharedUsers = explode(',', $sharedUserIds);\n }\n }", " if ($metadata['shareGlobally'] === true) {\n $users = new User\\Listing();\n $users->setCondition('id = ?', $currentUser->getId());", " foreach ($users as $user) {\n $sharedUsers[] = $user->getId();\n }\n }", " foreach ($sharedUsers as $id) {\n // Check if the user has already a favourite\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n (int) $id,\n $gridConfig->getClassId(),\n 0,\n $gridConfig->getSearchType()\n );", " if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());", " if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ((bool) $favouriteGridConfig->isShareGlobally() === false) {\n continue;\n }", " // Check if the user is the owner. If that is the case we do not update the favourite\n if ((int) $favouriteGridConfig->getOwnerId() === (int) $id) {\n continue;\n }\n }\n }", " $favourite = new GridConfigFavourite();\n $favourite->setGridConfigId($gridConfig->getId());\n $favourite->setClassId($gridConfig->getClassId());\n $favourite->setObjectId(0);\n $favourite->setOwnerId($id);\n $favourite->setType($gridConfig->getType());\n $favourite->setSearchType($gridConfig->getSearchType());\n $favourite->save();\n }\n }", " /**\n * @Route(\"/get-export-jobs\", name=\"pimcore_admin_asset_assethelper_getexportjobs\", methods={\"POST\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n *\n * @return JsonResponse\n */\n public function getExportJobsAction(Request $request, GridHelperService $gridHelperService)\n {\n $allParams = array_merge($request->request->all(), $request->query->all());\n $list = $gridHelperService->prepareAssetListingForGrid($allParams, $this->getAdminUser());", " if (empty($ids = $allParams['ids'] ?? '')) {\n $ids = $list->loadIdList();\n }", " $jobs = array_chunk($ids, 20);", " $fileHandle = uniqid('asset-export-');\n $storage = Storage::get('temp');\n $storage->write($this->getCsvFile($fileHandle), '');", " return $this->adminJson(['success' => true, 'jobs' => $jobs, 'fileHandle' => $fileHandle]);\n }", " /**\n * @Route(\"/do-export\", name=\"pimcore_admin_asset_assethelper_doexport\", methods={\"POST\"})\n *\n * @param Request $request\n * @param LocaleServiceInterface $localeService\n *\n * @return JsonResponse\n */\n public function doExportAction(Request $request, LocaleServiceInterface $localeService)\n {\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $ids = $request->get('ids');\n $settings = $request->get('settings');\n $settings = json_decode($settings, true);\n $delimiter = $settings['delimiter'] ?? ';';\n $language = str_replace('default', '', $request->get('language'));", " $list = new Asset\\Listing();", " $quotedIds = [];\n foreach ($ids as $id) {\n $quotedIds[] = $list->quote($id);\n }", " $list->setCondition('id IN (' . implode(',', $quotedIds) . ')');\n $list->setOrderKey(' FIELD(id, ' . implode(',', $quotedIds) . ')', false);", " $fields = $request->get('fields');", " $addTitles = $request->get('initial');", " $csv = $this->getCsvData($request, $language, $list, $fields, $addTitles);", " $storage = Storage::get('temp');\n $csvFile = $this->getCsvFile($fileHandle);", " $fileStream = $storage->readStream($csvFile);", " $temp = tmpfile();\n stream_copy_to_stream($fileStream, $temp, null, 0);", " $firstLine = true;\n foreach ($csv as $line) {\n if ($addTitles && $firstLine) {\n $firstLine = false;\n $line = implode($delimiter, $line) . \"\\r\\n\";\n fwrite($temp, $line);\n } else {\n fwrite($temp, implode($delimiter, array_map([$this, 'encodeFunc'], $line)) . \"\\r\\n\");\n }\n }", " $storage->writeStream($csvFile, $temp);", " return $this->adminJson(['success' => true]);\n }", " public function encodeFunc($value)\n {\n $value = str_replace('\"', '\"\"', $value);\n //force wrap value in quotes and return\n return '\"' . $value . '\"';\n }", " /**\n * @param Request $request\n * @param string $language\n * @param Asset\\Listing $list\n * @param array $fields\n * @param bool $addTitles\n *\n * @return array\n */\n protected function getCsvData(Request $request, $language, $list, $fields, $addTitles = true)\n {\n //create csv\n $csv = [];", " $unsupportedFields = ['preview~system', 'size~system'];\n $fields = array_diff($fields, $unsupportedFields);", " if ($addTitles) {\n $columns = $fields;\n foreach ($columns as $columnIdx => $columnKey) {\n $columns[$columnIdx] = '\"' . $columnKey . '\"';\n }\n $csv[] = $columns;\n }", " foreach ($list->load() as $asset) {\n if ($fields) {\n $dataRows = [];\n foreach ($fields as $field) {\n $fieldDef = explode('~', $field);\n $getter = 'get' . ucfirst($fieldDef[0]);", " if (isset($fieldDef[1])) {\n if ($fieldDef[1] == 'system' && method_exists($asset, $getter)) {\n $data = $asset->$getter($language);\n } else {\n $fieldDef[1] = str_replace('none', '', $fieldDef[1]);\n $data = $asset->getMetadata($fieldDef[0], $fieldDef[1], true);\n }\n } else {\n $data = $asset->getMetadata($field, $language, true);\n }", " if ($data instanceof Element\\ElementInterface) {\n $data = $data->getRealFullPath();\n }\n $dataRows[] = $data;\n }\n $dataRows = Element\\Service::escapeCsvRecord($dataRows);\n $csv[] = $dataRows;\n }\n }", " return $csv;\n }", " /**\n * @param Request $request\n *\n * @return string\n */\n protected function extractLanguage(Request $request)\n {\n $requestedLanguage = $request->get('language');\n if ($requestedLanguage) {\n if ($requestedLanguage != 'default') {\n $request->setLocale($requestedLanguage);\n }\n } else {\n $requestedLanguage = $request->getLocale();\n }", " return $requestedLanguage;\n }", " /**\n * @param string $fileHandle\n *\n * @return string\n */\n protected function getCsvFile($fileHandle)\n {\n return $fileHandle . '.csv';\n }", " /**\n * @Route(\"/download-csv-file\", name=\"pimcore_admin_asset_assethelper_downloadcsvfile\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return Response\n */\n public function downloadCsvFileAction(Request $request)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n $csvData = $storage->read($csvFile);\n $response = new Response($csvData);\n $response->headers->set('Content-Type', 'application/csv');\n $disposition = HeaderUtils::makeDisposition(\n HeaderUtils::DISPOSITION_ATTACHMENT,\n 'export.csv'\n );", " $response->headers->set('Content-Disposition', $disposition);\n $storage->delete($csvFile);", " return $response;\n } catch (FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('CSV file not found');\n }\n }", " /**\n * @Route(\"/download-xlsx-file\", name=\"pimcore_admin_asset_assethelper_downloadxlsxfile\", methods={\"GET\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n *\n * @return BinaryFileResponse\n */\n public function downloadXlsxFileAction(Request $request, GridHelperService $gridHelperService)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n return $gridHelperService->createXlsxExportFile($storage, $fileHandle, $csvFile);\n } catch (\\Exception | FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('XLSX file not found');\n }\n }", " /**\n * @Route(\"/get-metadata-for-column-config\", name=\"pimcore_admin_asset_assethelper_getmetadataforcolumnconfig\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getMetadataForColumnConfigAction(Request $request)\n {\n $result = [];", " //default metadata\n $defaultMetadataNames = ['copyright', 'alt', 'title'];\n foreach ($defaultMetadataNames as $defaultMetadata) {\n $defaultColumns[] = ['title' => $defaultMetadata, 'name' => $defaultMetadata, 'datatype' => 'data', 'fieldtype' => 'input'];\n }\n $result['defaultColumns']['nodeLabel'] = 'default_metadata';\n $result['defaultColumns']['nodeType'] = 'image';\n $result['defaultColumns']['children'] = $defaultColumns;", " //predefined metadata\n $list = Metadata\\Predefined\\Listing::getByTargetType('asset');\n $metadataItems = [];\n $tmp = [];\n foreach ($list as $item) {\n //only allow unique metadata columns with subtypes\n $uniqueKey = $item->getName().'_'.$item->getTargetSubtype();\n if (!in_array($uniqueKey, $tmp) && !in_array($item->getName(), $defaultMetadataNames)) {\n $tmp[] = $uniqueKey;\n $item->expand();", " $name = SecurityHelper::convertHtmlSpecialChars($item->getName());", " $metadataItems[] = [", " 'title' => $name,\n 'name' => $name,", " 'subtype' => $item->getTargetSubtype(),\n 'datatype' => 'data',\n 'fieldtype' => $item->getType(),\n 'config' => $item->getConfig(),\n ];\n }\n }", " $result['metadataColumns']['children'] = $metadataItems;\n $result['metadataColumns']['nodeLabel'] = 'predefined_metadata';\n $result['metadataColumns']['nodeType'] = 'metadata';", " //system columns\n $systemColumnNames = Asset\\Service::GRID_SYSTEM_COLUMNS;\n $systemColumns = [];\n foreach ($systemColumnNames as $systemColumn) {\n $systemColumns[] = ['title' => $systemColumn, 'name' => $systemColumn, 'datatype' => 'data', 'fieldtype' => 'system'];\n }\n $result['systemColumns']['nodeLabel'] = 'system_columns';\n $result['systemColumns']['nodeType'] = 'system';\n $result['systemColumns']['children'] = $systemColumns;", " return $this->adminJson($result);\n }", " /**\n * @Route(\"/get-batch-jobs\", name=\"pimcore_admin_asset_assethelper_getbatchjobs\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getBatchJobsAction(Request $request, GridHelperService $gridHelperService)\n {\n if ($request->get('language')) {\n $request->setLocale($request->get('language'));\n }", " $allParams = array_merge($request->request->all(), $request->query->all());\n $list = $gridHelperService->prepareAssetListingForGrid($allParams, $this->getAdminUser());", " $jobs = $list->loadIdList();", " return $this->adminJson(['success' => true, 'jobs' => $jobs]);\n }", " /**\n * @Route(\"/batch\", name=\"pimcore_admin_asset_assethelper_batch\", methods={\"PUT\"})\n *\n * @param Request $request\n * @param EventDispatcherInterface $eventDispatcher\n *\n * @return JsonResponse\n */\n public function batchAction(Request $request, EventDispatcherInterface $eventDispatcher)\n {\n try {\n if ($request->get('data')) {\n $loader = \\Pimcore::getContainer()->get('pimcore.implementation_loader.asset.metadata.data');", " $data = $this->decodeJson($request->get('data'), true);", " $updateEvent = new GenericEvent($this, [\n 'data' => $data,\n 'processed' => false,\n ]);", " $eventDispatcher->dispatch($updateEvent, AdminEvents::ASSET_LIST_BEFORE_BATCH_UPDATE);", " $processed = $updateEvent->getArgument('processed');", " if ($processed) {\n return $this->adminJson(['success' => true]);\n }", " $language = null;\n if (isset($data['language'])) {\n $language = $data['language'] != 'default' ? $data['language'] : null;\n }", " $asset = Asset::getById($data['job']);", " if ($asset) {\n if (!$asset->isAllowed('publish')) {\n throw new \\Exception(\"Permission denied. You don't have the rights to save this asset.\");\n }", " $metadata = $asset->getMetadata(null, null, false, true);\n $dirty = false;", " $name = $data['name'];\n $value = $data['value'];", " if ($data['valueType'] == 'object') {\n $value = $this->decodeJson($value);\n }", " $fieldDef = explode('~', $name);\n $name = $fieldDef[0];\n if (count($fieldDef) > 1) {\n $language = ($fieldDef[1] == 'none' ? '' : $fieldDef[1]);\n }", " foreach ($metadata as $idx => &$em) {\n if ($em['name'] == $name && $em['language'] == $language) {\n try {\n $dataImpl = $loader->build($em['type']);\n $value = $dataImpl->getDataFromListfolderGrid($value, $em);\n } catch (UnsupportedException $le) {\n Logger::error('could not resolve metadata implementation for ' . $em['type']);\n }\n $em['data'] = $value;\n $dirty = true;", " break;\n }\n }", " if (!$dirty) {\n $defaulMetadata = ['title', 'alt', 'copyright'];\n if (in_array($name, $defaulMetadata)) {\n $newEm = [\n 'name' => $name,\n 'language' => $language,\n 'type' => 'input',\n 'data' => $value,\n ];", " try {\n $dataImpl = $loader->build($newEm['type']);\n $newEm['data'] = $dataImpl->getDataFromListfolderGrid($value, $newEm);\n } catch (UnsupportedException $le) {\n Logger::error('could not resolve metadata implementation for ' . $newEm['type']);\n }", " $metadata[] = $newEm;\n $dirty = true;\n } else {\n $predefined = Metadata\\Predefined::getByName($name);\n if ($predefined && (empty($predefined->getTargetSubtype())\n || $predefined->getTargetSubtype() == $asset->getType())) {\n $newEm = [\n 'name' => $name,\n 'language' => $language,\n 'type' => $predefined->getType(),\n 'data' => $value,\n ];", " try {\n $dataImpl = $loader->build($newEm['type']);\n $newEm['data'] = $dataImpl->getDataFromListfolderGrid($value, $newEm);\n } catch (UnsupportedException $le) {\n Logger::error('could not resolve metadata implementation for ' . $newEm['type']);\n }", " $metadata[] = $newEm;", " $dirty = true;\n }\n }\n }", " try {\n if ($dirty) {\n // $metadata = Asset\\Service::minimizeMetadata($metadata, \"grid\");\n $asset->setMetadataRaw($metadata);\n $asset->save();", " return $this->adminJson(['success' => true]);\n }\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n } else {\n Logger::debug('AssetHelperController::batchAction => There is no asset left to update.');", " return $this->adminJson(['success' => false, 'message' => 'AssetHelperController::batchAction => There is no asset left to update.']);\n }\n }\n } catch (\\Exception $e) {\n Logger::err($e);", " return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }", " return $this->adminJson(['success' => false, 'message' => 'something went wrong.']);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\Bundle\\AdminBundle\\Controller\\Admin\\DataObject;", "use League\\Flysystem\\FilesystemException;\nuse League\\Flysystem\\UnableToReadFile;\nuse PhpOffice\\PhpSpreadsheet\\Reader\\Csv;\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\nuse Pimcore\\Bundle\\AdminBundle\\Controller\\AdminController;\nuse Pimcore\\Bundle\\AdminBundle\\Helper\\GridHelperService;\nuse Pimcore\\Config;\nuse Pimcore\\Db;\nuse Pimcore\\Event\\AdminEvents;\nuse Pimcore\\File;\nuse Pimcore\\Localization\\LocaleServiceInterface;\nuse Pimcore\\Logger;\nuse Pimcore\\Model\\DataObject;\nuse Pimcore\\Model\\GridConfig;\nuse Pimcore\\Model\\GridConfigFavourite;\nuse Pimcore\\Model\\GridConfigShare;\nuse Pimcore\\Model\\User;", "", "use Pimcore\\Tool;\nuse Pimcore\\Tool\\Storage;\nuse Pimcore\\Version;\nuse Symfony\\Component\\EventDispatcher\\GenericEvent;\nuse Symfony\\Component\\HttpFoundation\\BinaryFileResponse;\nuse Symfony\\Component\\HttpFoundation\\HeaderUtils;\nuse Symfony\\Component\\HttpFoundation\\JsonResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;", "/**\n * @Route(\"/object-helper\", name=\"pimcore_admin_dataobject_dataobjecthelper_\")\n *\n * @internal\n */\nclass DataObjectHelperController extends AdminController\n{\n const SYSTEM_COLUMNS = ['id', 'fullpath', 'key', 'published', 'creationDate', 'modificationDate', 'filename', 'classname'];", " /**\n * @Route(\"/load-object-data\", name=\"loadobjectdata\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function loadObjectDataAction(Request $request)\n {\n $object = DataObject::getById((int) $request->get('id'));\n $result = [];\n if ($object) {\n $result['success'] = true;\n $fields = $request->get('fields');\n $result['fields'] = DataObject\\Service::gridObjectData($object, $fields);\n } else {\n $result['success'] = false;\n }", " return $this->adminJson($result);\n }", " /**\n * @param int $userId\n * @param string $classId\n * @param string|null $searchType\n *\n * @return array\n */\n public function getMyOwnGridColumnConfigs($userId, $classId, $searchType = null)\n {\n $db = Db::get();\n $configListingConditionParts = [];\n $configListingConditionParts[] = 'ownerId = ' . $userId;\n $configListingConditionParts[] = 'classId = ' . $db->quote($classId);", " if ($searchType) {\n $configListingConditionParts[] = 'searchType = ' . $db->quote($searchType);\n }", " $configCondition = implode(' AND ', $configListingConditionParts);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition($configCondition);\n $configListing = $configListing->load();", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @param User $user\n * @param string $classId\n * @param string $searchType\n *\n * @return array\n */\n public function getSharedGridColumnConfigs($user, $classId, $searchType = null)\n {\n $configListing = [];", " $userIds = [$user->getId()];\n // collect all roles\n $userIds = array_merge($userIds, $user->getRoles());\n $userIds = implode(',', $userIds);\n $db = Db::get();", " $query = 'select distinct c1.id from gridconfigs c1, gridconfig_shares s\n where (c1.searchType = ' . $db->quote($searchType) . ' and ((c1.id = s.gridConfigId and s.sharedWithUserId IN (' . $userIds . '))) and c1.classId = ' . $db->quote($classId) . ')\n UNION distinct select c2.id from gridconfigs c2 where shareGlobally = 1 and c2.classId = '. $db->quote($classId) . ' and c2.ownerId != ' . $db->quote($user->getId());", " $ids = $db->fetchFirstColumn($query);", " if ($ids) {\n $ids = implode(',', $ids);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition('id in (' . $ids . ')');\n $configListing = $configListing->load();\n }", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @Route(\"/get-export-configs\", name=\"getexportconfigs\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getExportConfigsAction(Request $request)\n {\n $classId = $request->get('classId');\n $list = $this->getMyOwnGridColumnConfigs($this->getAdminUser()->getId(), $classId);\n if (!is_array($list)) {\n $list = [];\n }\n $list = array_merge($list, $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId));\n $result = [];", " $result[] = [\n 'id' => -1,\n 'name' => '--default--',\n ];", " if ($list) {\n /** @var GridConfig $config */\n foreach ($list as $config) {\n $result[] = [\n 'id' => $config['id'],\n 'name' => $config['name'],\n ];\n }\n }", " return $this->adminJson(['success' => true, 'data' => $result]);\n }", " /**\n * @Route(\"/grid-delete-column-config\", name=\"griddeletecolumnconfig\", methods={\"DELETE\"})\n *\n * @param Request $request\n * @param EventDispatcherInterface $eventDispatcher\n * @param Config $config\n *\n * @return JsonResponse\n */\n public function gridDeleteColumnConfigAction(Request $request, EventDispatcherInterface $eventDispatcher, Config $config)\n {\n $gridConfigId = $request->get('gridConfigId');\n $gridConfig = GridConfig::getById($gridConfigId);\n $success = false;\n if ($gridConfig) {\n if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $gridConfig->delete();\n $success = true;\n }", " $newGridConfig = $this->doGetGridColumnConfig($request, $config, true);\n $newGridConfig['deleteSuccess'] = $success;", " $event = new GenericEvent($this, [\n 'data' => $newGridConfig,\n 'request' => $request,\n 'config' => $config,\n 'context' => 'delete',\n ]);", " $eventDispatcher->dispatch($event, AdminEvents::OBJECT_GRID_GET_COLUMN_CONFIG_PRE_SEND_DATA);\n $newGridConfig = $event->getArgument('data');", " return $this->adminJson($newGridConfig);\n }", " /**\n * @Route(\"/grid-get-column-config\", name=\"gridgetcolumnconfig\", methods={\"GET\"})\n *\n * @param Request $request\n * @param EventDispatcherInterface $eventDispatcher\n * @param Config $config\n *\n * @return JsonResponse\n */\n public function gridGetColumnConfigAction(Request $request, EventDispatcherInterface $eventDispatcher, Config $config)\n {\n $result = $this->doGetGridColumnConfig($request, $config);", " $event = new GenericEvent($this, [\n 'data' => $result,\n 'request' => $request,\n 'config' => $config,\n 'context' => 'get',\n ]);", " $eventDispatcher->dispatch($event, AdminEvents::OBJECT_GRID_GET_COLUMN_CONFIG_PRE_SEND_DATA);\n $result = $event->getArgument('data');", " return $this->adminJson($result);\n }", " /**\n * @param Request $request\n * @param Config $config\n * @param bool $isDelete\n *\n * @return array\n */\n public function doGetGridColumnConfig(Request $request, Config $config, $isDelete = false)\n {\n $class = null;\n $fields = null;", " if ($request->get('id')) {\n $class = DataObject\\ClassDefinition::getById($request->get('id'));\n } elseif ($request->get('name')) {\n $class = DataObject\\ClassDefinition::getByName($request->get('name'));\n }", " $gridConfigId = null;\n $gridType = 'search';\n if ($request->get('gridtype')) {\n $gridType = $request->get('gridtype');\n }", " $objectId = (int) $request->get('objectId');", " if ($objectId) {\n $fields = DataObject\\Service::getCustomGridFieldDefinitions($class->getId(), $objectId);\n }", " $context = ['purpose' => 'gridconfig'];\n if ($class) {\n $context['class'] = $class;\n }", " if ($objectId) {\n $object = DataObject::getById($objectId);\n $context['object'] = $object;\n }", " if (!$fields && $class) {\n $fields = $class->getFieldDefinitions();\n }", " $types = [];\n if ($request->get('types')) {\n $types = explode(',', $request->get('types'));\n }", " $userId = $this->getAdminUser()->getId();", " $requestedGridConfigId = $isDelete ? null : $request->get('gridConfigId');", " // grid config\n $gridConfig = [];\n $searchType = $request->get('searchType');", " if (strlen($requestedGridConfigId) == 0 && $class) {\n // check if there is a favourite view\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $class->getId(), $objectId ?: 0, $searchType);\n if (!$favourite && $objectId) {\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $class->getId(), 0, $searchType);\n }", " if ($favourite) {\n $requestedGridConfigId = $favourite->getGridConfigId();\n }\n }", " if (is_numeric($requestedGridConfigId) && $requestedGridConfigId > 0) {\n $db = Db::get();\n $savedGridConfig = GridConfig::getById((int) $requestedGridConfigId);", " if ($savedGridConfig) {\n $shared = false;\n if (!$this->getAdminUser()->isAdmin()) {\n $userIds = [$this->getAdminUser()->getId()];\n if ($this->getAdminUser()->getRoles()) {\n $userIds = array_merge($userIds, $this->getAdminUser()->getRoles());\n }\n $userIds = implode(',', $userIds);\n $shared = ($savedGridConfig->getOwnerId() != $userId && $savedGridConfig->isShareGlobally()) || $db->fetchOne('select 1 from gridconfig_shares where sharedWithUserId IN ('.$userIds.') and gridConfigId = '.$savedGridConfig->getId());\n // $shared = $savedGridConfig->isShareGlobally() || GridConfigShare::getByGridConfigAndSharedWithId($savedGridConfig->getId(), $this->getUser()->getId());", " if (!$shared && $savedGridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception('You are neither the owner of this config nor it is shared with you');\n }\n }", " $gridConfigId = $savedGridConfig->getId();\n $gridConfig = $savedGridConfig->getConfig();\n $gridConfig = json_decode($gridConfig, true);\n $gridConfigName = $savedGridConfig->getName();\n $owner = $savedGridConfig->getOwnerId();\n $ownerObject = User::getById($owner);\n if ($ownerObject instanceof User) {\n $owner = $ownerObject->getName();\n }\n $modificationDate = $savedGridConfig->getModificationDate();\n $gridConfigDescription = $savedGridConfig->getDescription();\n $sharedGlobally = $savedGridConfig->isShareGlobally();\n $setAsFavourite = $savedGridConfig->isSetAsFavourite();", "", " }\n }", " $localizedFields = [];\n $objectbrickFields = [];\n if (is_array($fields)) {\n foreach ($fields as $key => $field) {\n if ($field instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $localizedFields[] = $field;\n } elseif ($field instanceof DataObject\\ClassDefinition\\Data\\Objectbricks) {\n $objectbrickFields[] = $field;\n }\n }\n }", " $availableFields = [];", " if (empty($gridConfig)) {\n $availableFields = $this->getDefaultGridFields(\n $request->get('no_system_columns'),\n $class,\n $gridType,\n $request->get('no_brick_columns'),\n $fields,\n $context,\n $objectId,\n $types);\n } else {\n $savedColumns = $gridConfig['columns'];\n foreach ($savedColumns as $key => $sc) {\n if (!$sc['hidden']) {\n if (in_array($key, self::SYSTEM_COLUMNS)) {\n $colConfig = [\n 'key' => $key,\n 'type' => 'system',\n 'label' => $key,\n 'locked' => $sc['locked'] ?? null,\n 'position' => $sc['position'],\n ];\n if (isset($sc['width'])) {\n $colConfig['width'] = $sc['width'];\n }\n $availableFields[] = $colConfig;\n } else {\n $keyParts = explode('~', $key);", " if (substr($key, 0, 1) == '~') {\n // not needed for now\n $type = $keyParts[1];\n // $field = $keyParts[2];\n $groupAndKeyId = explode('-', $keyParts[3]);\n $keyId = (int) $groupAndKeyId[1];", " if ($type == 'classificationstore') {\n $keyDef = DataObject\\Classificationstore\\KeyConfig::getById($keyId);\n if ($keyDef) {\n $keyFieldDef = json_decode($keyDef->getDefinition(), true);\n if ($keyFieldDef) {\n $keyFieldDef = \\Pimcore\\Model\\DataObject\\Classificationstore\\Service::getFieldDefinitionFromJson($keyFieldDef, $keyDef->getType());\n $fieldConfig = $this->getFieldGridConfig($keyFieldDef, $gridType, $sc['position'], true, null, $class, $objectId);\n if ($fieldConfig) {\n $fieldConfig['key'] = $key;\n $fieldConfig['label'] = '#' . $keyFieldDef->getTitle();\n if (isset($sc['locked'])) {\n $fieldConfig['locked'] = $sc['locked'];\n }\n $availableFields[] = $fieldConfig;\n }\n }\n }\n }\n } elseif (count($keyParts) > 1) {\n $brick = $keyParts[0];\n $brickDescriptor = null;", " if (strpos($brick, '?') !== false) {\n $brickDescriptor = substr($brick, 1);\n $brickDescriptor = json_decode($brickDescriptor, true);\n $keyPrefix = $brick . '~';\n $brick = $brickDescriptor['containerKey'];\n } else {\n $keyPrefix = $brick . '~';\n }", " $fieldname = $keyParts[1];", " $brickClass = DataObject\\Objectbrick\\Definition::getByKey($brick);", " $fd = null;\n if ($brickClass instanceof DataObject\\Objectbrick\\Definition) {\n if ($brickDescriptor) {\n $innerContainer = $brickDescriptor['innerContainer'] ?? 'localizedfields';\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields $localizedFields */\n $localizedFields = $brickClass->getFieldDefinition($innerContainer);\n $fd = $localizedFields->getFieldDefinition($brickDescriptor['brickfield']);\n } else {\n $fd = $brickClass->getFieldDefinition($fieldname);\n }\n }", " if ($fd !== null) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $sc['position'], true, $keyPrefix, $class, $objectId);\n if (!empty($fieldConfig)) {\n if (isset($sc['width'])) {\n $fieldConfig['width'] = $sc['width'];\n }\n if (isset($sc['locked'])) {\n $fieldConfig['locked'] = $sc['locked'];\n }\n $availableFields[] = $fieldConfig;\n }\n }\n } else {\n if (DataObject\\Service::isHelperGridColumnConfig($key)) {\n $calculatedColumnConfig = $this->getCalculatedColumnConfig($savedColumns[$key]);\n if ($calculatedColumnConfig) {\n $availableFields[] = $calculatedColumnConfig;\n }\n } else {\n $fd = $class->getFieldDefinition($key);\n //if not found, look for localized fields\n if (empty($fd)) {\n foreach ($localizedFields as $lf) {\n $fd = $lf->getFieldDefinition($key);\n if (!empty($fd)) {\n break;\n }\n }\n }", " if (!empty($fd)) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $sc['position'], true, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n if (isset($sc['width'])) {\n $fieldConfig['width'] = $sc['width'];\n }\n if (isset($sc['locked'])) {\n $fieldConfig['locked'] = $sc['locked'];\n }\n $availableFields[] = $fieldConfig;\n }\n }\n }\n }\n }\n }\n }\n }\n usort($availableFields, function ($a, $b) {\n if ($a['position'] == $b['position']) {\n return 0;\n }", " return ($a['position'] < $b['position']) ? -1 : 1;\n });", " $frontendLanguages = Tool\\Admin::reorderWebsiteLanguages(\\Pimcore\\Tool\\Admin::getCurrentUser(), $config['general']['valid_languages']);\n if ($frontendLanguages) {\n $language = explode(',', $frontendLanguages)[0];\n } else {\n $language = $request->getLocale();\n }", " if (!Tool::isValidLanguage($language)) {\n $validLanguages = Tool::getValidLanguages();\n $language = $validLanguages[0];\n }", " if (!empty($gridConfig) && !empty($gridConfig['language'])) {\n $language = $gridConfig['language'];\n }", " $availableConfigs = $class ? $this->getMyOwnGridColumnConfigs($userId, $class->getId(), $searchType) : [];\n $sharedConfigs = $class ? $this->getSharedGridColumnConfigs($this->getAdminUser(), $class->getId(), $searchType) : [];\n $settings = $this->getShareSettings((int)$gridConfigId);\n $settings['gridConfigId'] = (int)$gridConfigId;\n $settings['gridConfigName'] = $gridConfigName ?? null;\n $settings['gridConfigDescription'] = $gridConfigDescription ?? null;\n $settings['owner'] = $owner ?? null;\n $settings['modificationDate'] = $modificationDate ?? null;\n $settings['shareGlobally'] = $sharedGlobally ?? null;\n $settings['setAsFavourite'] = $setAsFavourite ?? null;\n $settings['isShared'] = !$gridConfigId || ($shared ?? null);", " $context = $gridConfig['context'] ?? null;\n if ($context) {\n $context = json_decode($context, true);\n }", " return [\n 'sortinfo' => $gridConfig['sortinfo'] ?? false,\n 'language' => $language,\n 'availableFields' => $availableFields,\n 'settings' => $settings,\n 'onlyDirectChildren' => $gridConfig['onlyDirectChildren'] ?? false,\n 'pageSize' => $gridConfig['pageSize'] ?? false,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n 'context' => $context,\n 'sqlFilter' => $gridConfig['sqlFilter'] ?? '',\n 'searchFilter' => $gridConfig['searchFilter'] ?? '',\n ];\n }", " /**\n * @param bool $noSystemColumns\n * @param DataObject\\ClassDefinition|null $class\n * @param string $gridType\n * @param bool $noBrickColumns\n * @param DataObject\\ClassDefinition\\Data[] $fields\n * @param array $context\n * @param int $objectId\n * @param array $types\n *\n * @return array\n */\n public function getDefaultGridFields($noSystemColumns, $class, $gridType, $noBrickColumns, $fields, $context, $objectId, $types = [])\n {\n $count = 0;\n $availableFields = [];", " if (!$noSystemColumns && $class) {\n $vis = $class->getPropertyVisibility();\n foreach (self::SYSTEM_COLUMNS as $sc) {\n $key = $sc;\n if ($key === 'fullpath') {\n $key = 'path';\n }", " if (empty($types) && (!empty($vis[$gridType][$key]) || $gridType === 'all')) {\n $availableFields[] = [\n 'key' => $sc,\n 'type' => 'system',\n 'label' => $sc,\n 'position' => $count, ];\n $count++;\n }\n }\n }", " $includeBricks = !$noBrickColumns;", " if (is_array($fields)) {\n foreach ($fields as $key => $field) {\n if ($field instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n foreach ($field->getFieldDefinitions($context) as $fd) {\n if (empty($types) || in_array($fd->getFieldType(), $types)) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $count, false, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n }\n }\n } elseif ($field instanceof DataObject\\ClassDefinition\\Data\\Objectbricks && $includeBricks) {\n if (in_array($field->getFieldType(), $types)) {\n $fieldConfig = $this->getFieldGridConfig($field, $gridType, $count, false, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n } else {\n $allowedTypes = $field->getAllowedTypes();\n if (!empty($allowedTypes)) {\n foreach ($allowedTypes as $t) {\n $brickClass = DataObject\\Objectbrick\\Definition::getByKey($t);\n $brickFields = $brickClass->getFieldDefinitions($context);", " $this->appendBrickFields($field, $brickFields, $availableFields, $gridType, $count, $t, $class, $objectId);\n }\n }\n }\n } else {\n if (empty($types) || in_array($field->getFieldType(), $types)) {\n $fieldConfig = $this->getFieldGridConfig($field, $gridType, $count, !empty($types), null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n }\n }\n }\n }", " return $availableFields;\n }", " /**\n * @param DataObject\\ClassDefinition\\Data $field\n * @param DataObject\\ClassDefinition\\Data[] $brickFields\n * @param array $availableFields\n * @param string $gridType\n * @param int $count\n * @param string $brickType\n * @param DataObject\\ClassDefinition $class\n * @param int $objectId\n * @param array|null $context\n */\n protected function appendBrickFields($field, $brickFields, &$availableFields, $gridType, &$count, $brickType, $class, $objectId, $context = null)\n {\n if (!empty($brickFields)) {\n foreach ($brickFields as $bf) {\n if ($bf instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $localizedFieldDefinitions = $bf->getFieldDefinitions();", " $localizedContext = [\n 'containerKey' => $brickType,\n 'fieldname' => $field->getName(),\n ];", " $this->appendBrickFields($bf, $localizedFieldDefinitions, $availableFields, $gridType, $count, $brickType, $class, $objectId, $localizedContext);\n } else {\n if ($context) {\n $context['brickfield'] = $bf->getName();\n $keyPrefix = '?' . json_encode($context) . '~';\n } else {\n $keyPrefix = $brickType . '~';\n }\n $fieldConfig = $this->getFieldGridConfig($bf, $gridType, $count, false, $keyPrefix, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n }\n }\n }\n }", " /**\n * @param array $config\n *\n * @return mixed\n */\n protected function getCalculatedColumnConfig($config)\n {\n try {\n $calculatedColumnConfig = Tool\\Session::useSession(function (AttributeBagInterface $session) use ($config) {\n //otherwise create a new one", " $calculatedColumn = [];\n // note that we have to generate a new key!", " $existingKey = $config['fieldConfig']['key'];\n $calculatedColumnConfig['key'] = $existingKey;\n $calculatedColumnConfig['position'] = $config['position'];\n $calculatedColumnConfig['isOperator'] = true;\n $calculatedColumnConfig['attributes'] = $config['fieldConfig']['attributes'];\n $calculatedColumnConfig['width'] = $config['width'];\n $calculatedColumnConfig['locked'] = $config['locked'];", " $existingColumns = $session->get('helpercolumns', []);", " if (isset($existingColumns[$existingKey])) {\n // if the configuration is still in the session, then reuse it\n return $calculatedColumnConfig;\n }", " $newKey = '#' . uniqid();\n $calculatedColumnConfig['key'] = $newKey;", " // prepare a column config on the fly\n $phpConfig = json_encode($config['fieldConfig']);\n $phpConfig = json_decode($phpConfig);\n $helperColumns = [];\n $helperColumns[$newKey] = $phpConfig;", " $helperColumns = array_merge($helperColumns, $existingColumns);\n $session->set('helpercolumns', $helperColumns);", " return $calculatedColumnConfig;\n }, 'pimcore_gridconfig');", " return $calculatedColumnConfig;\n } catch (\\Exception $e) {\n Logger::error((string) $e);\n }\n }", " /**\n * @Route(\"/prepare-helper-column-configs\", name=\"preparehelpercolumnconfigs\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function prepareHelperColumnConfigs(Request $request)\n {\n $helperColumns = [];\n $newData = [];\n /** @var \\stdClass[] $data */\n $data = json_decode($request->get('columns'));\n foreach ($data as $item) {\n if (!empty($item->isOperator)) {\n $itemKey = '#' . uniqid();", " $item->key = $itemKey;\n $newData[] = $item;\n $helperColumns[$itemKey] = $item;\n } else {\n $newData[] = $item;\n }\n }", " Tool\\Session::useSession(function (AttributeBagInterface $session) use ($helperColumns) {\n $existingColumns = $session->get('helpercolumns', []);\n $helperColumns = array_merge($helperColumns, $existingColumns);\n $session->set('helpercolumns', $helperColumns);\n }, 'pimcore_gridconfig');", " return $this->adminJson(['success' => true, 'columns' => $newData]);\n }", " /**\n * @Route(\"/grid-config-apply-to-all\", name=\"gridconfigapplytoall\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridConfigApplyToAllAction(Request $request)\n {\n $objectId = $request->get('objectId');\n $object = DataObject::getById($objectId);", " if ($object->isAllowed('list')) {\n $classId = $request->get('classId');\n $searchType = $request->get('searchType');\n $user = $this->getAdminUser();\n $db = Db::get();\n $db->executeQuery('delete from gridconfig_favourites where '\n . 'ownerId = ' . $user->getId()\n . ' and classId = ' . $db->quote($classId) .\n ' and searchType = ' . $db->quote($searchType)\n . ' and objectId != ' . $objectId . ' and objectId != 0');", " return $this->adminJson(['success' => true]);\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @Route(\"/grid-mark-favourite-column-config\", name=\"gridmarkfavouritecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridMarkFavouriteColumnConfigAction(Request $request)\n {\n $objectId = $request->get('objectId');\n $object = DataObject::getById($objectId);", " if ($object->isAllowed('list')) {\n $classId = $request->get('classId');\n $gridConfigId = $request->get('gridConfigId');\n $searchType = $request->get('searchType');\n $global = $request->get('global');\n $user = $this->getAdminUser();\n $type = $request->get('type');", " $favourite = new GridConfigFavourite();\n $favourite->setOwnerId($user->getId());\n $class = DataObject\\ClassDefinition::getById($classId);\n if (!$class) {\n throw new \\Exception('class ' . $classId . ' does not exist anymore');\n }\n $favourite->setClassId($classId);\n $favourite->setSearchType($searchType);\n $favourite->setType($type);\n $specializedConfigs = false;", " try {\n if ($gridConfigId != 0) {\n $gridConfig = GridConfig::getById($gridConfigId);\n $favourite->setGridConfigId($gridConfig->getId());\n }\n $favourite->setObjectId($objectId);\n $favourite->save();", " if ($global) {\n $favourite->setObjectId(0);\n $favourite->save();\n }\n $db = Db::get();\n $count = $db->fetchOne('select * from gridconfig_favourites where '\n . 'ownerId = ' . $user->getId()\n . ' and classId = ' . $db->quote($classId).\n ' and searchType = ' . $db->quote($searchType)\n . ' and objectId != ' . $objectId . ' and objectId != 0'\n . ' and type != ' . $db->quote($type));\n $specializedConfigs = $count > 0;\n } catch (\\Exception $e) {\n $favourite->delete();\n }", " return $this->adminJson(['success' => true, 'spezializedConfigs' => $specializedConfigs]);\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param int $gridConfigId\n *\n * @return array\n */\n protected function getShareSettings($gridConfigId)\n {\n $result = [\n 'sharedUserIds' => [],\n 'sharedRoleIds' => [],\n ];", " $db = Db::get();\n $allShares = $db->fetchAllAssociative('select s.sharedWithUserId, u.type from gridconfig_shares s, users u\n where s.sharedWithUserId = u.id and s.gridConfigId = ' . $gridConfigId);", " if ($allShares) {\n foreach ($allShares as $share) {\n $type = $share['type'];\n $key = 'shared' . ucfirst($type) . 'Ids';\n $result[$key][] = $share['sharedWithUserId'];\n }\n }", " foreach ($result as $idx => $value) {\n $value = $value ? implode(',', $value) : '';\n $result[$idx] = $value;\n }", " return $result;\n }", " /**\n * @Route(\"/grid-save-column-config\", name=\"gridsavecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridSaveColumnConfigAction(Request $request)\n {\n $objectId = $request->get('id');\n $object = DataObject::getById($objectId);", " if ($object->isAllowed('list')) {\n try {\n $classId = $request->get('class_id');\n $context = $request->get('context');", " $searchType = $request->get('searchType');", " // grid config\n $gridConfigData = $this->decodeJson($request->get('gridconfig'));\n $gridConfigData['pimcore_version'] = Version::getVersion();\n $gridConfigData['pimcore_revision'] = Version::getRevision();", " $gridConfigData['context'] = $context;", " unset($gridConfigData['settings']['isShared']);", " $metadata = $request->get('settings');\n $metadata = json_decode($metadata, true);", " $gridConfigId = $metadata['gridConfigId'];\n $gridConfig = GridConfig::getById($gridConfigId);", " if ($gridConfig && $gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin()) {\n throw new \\Exception(\"don't mess around with somebody elses configuration\");\n }", " $this->updateGridConfigShares($gridConfig, $metadata);", " if ($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin()) {\n $this->updateGridConfigFavourites($gridConfig, $metadata, $objectId);\n }", " if (!$gridConfig) {\n $gridConfig = new GridConfig();\n $gridConfig->setName(date('c'));\n $gridConfig->setClassId($classId);\n $gridConfig->setSearchType($searchType);", " $gridConfig->setOwnerId($this->getAdminUser()->getId());\n }", " if ($metadata) {\n $gridConfig->setName($metadata['gridConfigName']);\n $gridConfig->setDescription($metadata['gridConfigDescription']);\n $gridConfig->setShareGlobally($metadata['shareGlobally'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSetAsFavourite($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin());\n }", " $gridConfigData = json_encode($gridConfigData);\n $gridConfig->setConfig($gridConfigData);\n $gridConfig->save();", " $userId = $this->getAdminUser()->getId();", " $availableConfigs = $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType);\n $sharedConfigs = $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType);", " $settings = $this->getShareSettings($gridConfig->getId());\n $settings['gridConfigId'] = (int)$gridConfig->getId();\n $settings['gridConfigName'] = $gridConfig->getName();\n $settings['gridConfigDescription'] = $gridConfig->getDescription();\n $settings['shareGlobally'] = $gridConfig->isShareGlobally();\n $settings['setAsFavourite'] = $gridConfig->isSetAsFavourite();\n $settings['isShared'] = $gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin();", " return $this->adminJson([\n 'success' => true,\n 'settings' => $settings,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n *\n * @throws \\Exception\n */\n protected function updateGridConfigShares($gridConfig, $metadata)\n {\n $user = $this->getAdminUser();\n if (!$gridConfig || !$user->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if ($gridConfig->getOwnerId() != $user->getId() && !$user->isAdmin()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n $combinedShares = [];\n $sharedUserIds = $metadata['sharedUserIds'];\n $sharedRoleIds = $metadata['sharedRoleIds'];", " if ($sharedUserIds) {\n $combinedShares = explode(',', $sharedUserIds);\n }", " if ($sharedRoleIds) {\n $sharedRoleIds = explode(',', $sharedRoleIds);\n $combinedShares = array_merge($combinedShares, $sharedRoleIds);\n }", " $db = Db::get();\n $db->delete('gridconfig_shares', ['gridConfigId' => $gridConfig->getId()]);", " foreach ($combinedShares as $id) {\n $share = new GridConfigShare();\n $share->setGridConfigId($gridConfig->getId());\n $share->setSharedWithUserId((int) $id);\n $share->save();\n }\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n * @param int $objectId\n *\n * @throws \\Exception\n */\n protected function updateGridConfigFavourites($gridConfig, $metadata, $objectId)\n {\n $currentUser = $this->getAdminUser();", " if (!$gridConfig || $currentUser === null || !$currentUser->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if (!$currentUser->isAdmin() && (int) $gridConfig->getOwnerId() !== $currentUser->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $sharedUsers = [];", " if ($metadata['shareGlobally'] === false) {\n $sharedUserIds = $metadata['sharedUserIds'];", " if ($sharedUserIds) {\n $sharedUsers = explode(',', $sharedUserIds);\n }\n }", " if ($metadata['shareGlobally'] === true) {\n $users = new User\\Listing();\n $users->setCondition('id = ?', $currentUser->getId());", " foreach ($users as $user) {\n $sharedUsers[] = $user->getId();\n }\n }", " foreach ($sharedUsers as $id) {\n $global = true;\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n (int) $id,\n $gridConfig->getClassId(),\n (int) $objectId,\n $gridConfig->getSearchType()\n );", " // If the user has already a favourite for that object we check the current favourite and decide if we update\n if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());", " if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ((bool) $favouriteGridConfig->isShareGlobally() === false) {\n continue;\n }", " // Check if the user is the owner. If that is the case we do not update the favourite\n if ((int) $favouriteGridConfig->getOwnerId() === (int) $id) {\n continue;\n }\n }\n }", " // Check if the user has already a global favourite then we do not save the favourite as global\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n (int) $id,\n $gridConfig->getClassId(),\n 0,\n $gridConfig->getSearchType()\n );", " if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());", " if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ($favouriteGridConfig->isShareGlobally() === false) {\n $global = false;\n }", " // Check if the user is the owner. If that is the case we do not update the global favourite\n if ($favouriteGridConfig->getOwnerId() === (int) $id) {\n $global = false;\n }\n }\n }", " $favourite = new GridConfigFavourite();\n $favourite->setGridConfigId($gridConfig->getId());\n $favourite->setClassId($gridConfig->getClassId());\n $favourite->setObjectId($objectId);\n $favourite->setOwnerId($id);\n $favourite->setType($gridConfig->getType());\n $favourite->setSearchType($gridConfig->getSearchType());\n $favourite->save();", " if ($global === true) {\n $favourite->setObjectId(0);\n $favourite->save();\n }\n }\n }", " /**\n * @param DataObject\\ClassDefinition\\Data $field\n * @param string $gridType\n * @param string $position\n * @param bool $force\n * @param string|null $keyPrefix\n * @param DataObject\\ClassDefinition|null $class\n * @param int|null $objectId\n *\n * @return array|null\n */\n protected function getFieldGridConfig($field, $gridType, $position, $force = false, $keyPrefix = null, $class = null, $objectId = null)\n {\n $key = $keyPrefix . $field->getName();\n $config = null;\n $title = $field->getName();\n if (method_exists($field, 'getTitle')) {\n if ($field->getTitle()) {\n $title = $field->getTitle();\n }\n }", " if ($field instanceof DataObject\\ClassDefinition\\Data\\Slider) {\n $config['minValue'] = $field->getMinValue();\n $config['maxValue'] = $field->getMaxValue();\n $config['increment'] = $field->getIncrement();\n }", " if (method_exists($field, 'getWidth')) {\n $config['width'] = $field->getWidth();\n }\n if (method_exists($field, 'getHeight')) {\n $config['height'] = $field->getHeight();\n }", " $visible = false;\n if ($gridType == 'search') {\n $visible = $field->getVisibleSearch();\n } elseif ($gridType == 'grid') {\n $visible = $field->getVisibleGridView();\n } elseif ($gridType == 'all') {\n $visible = true;\n }", " if (!$field->getInvisible() && ($force || $visible)) {\n $context = ['purpose' => 'gridconfig'];\n if ($class) {\n $context['class'] = $class;\n }", " if ($objectId) {\n $object = DataObject::getById($objectId);\n $context['object'] = $object;\n }\n DataObject\\Service::enrichLayoutDefinition($field, null, $context);", " $result = [\n 'key' => $key,\n 'type' => $field->getFieldType(),\n 'label' => $title,\n 'config' => $config,\n 'layout' => $field,\n 'position' => $position,\n ];", " if ($field instanceof DataObject\\ClassDefinition\\Data\\EncryptedField) {\n $result['delegateDatatype'] = $field->getDelegateDatatype();\n }", " return $result;\n } else {\n return null;\n }\n }", " /**\n * IMPORTER\n */", " /**\n * @Route(\"/import-upload\", name=\"importupload\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function importUploadAction(Request $request)\n {\n $data = file_get_contents($_FILES['Filedata']['tmp_name']);\n $data = Tool\\Text::convertToUTF8($data);", " $importId = $request->get('importId');\n $importId = str_replace('..', '', $importId);\n $importFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_' . $importId;\n File::put($importFile, $data);", " $importFileOriginal = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_' . $importId . '_original';\n File::put($importFileOriginal, $data);", " $response = $this->adminJson([\n 'success' => true,\n ]);", " // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in\n // Ext.form.Action.Submit and mark the submission as failed\n $response->headers->set('Content-Type', 'text/html');", " return $response;\n }", " private function getDataPreview($originalFile, $dialect)\n {\n $count = 0;\n $data = [];\n if (($handle = fopen($originalFile, 'r')) !== false) {\n while (($rowData = fgetcsv($handle, 0, $dialect->delimiter, $dialect->quotechar, $dialect->escapechar)) !== false) {\n $tmpData = [];", " foreach ($rowData as $key => $value) {\n $tmpData['field_' . $key] = $value;\n }", " $tmpData['rowId'] = $count + 1;\n $data[] = $tmpData;", " $count++;", " /**\n * Reached the number or rows for the preview\n */\n if ($count > 18) {\n break;\n }\n }\n fclose($handle);\n }", " return $data;\n }", " /**\n * @param Request $request\n *\n * @return string\n */\n protected function extractLanguage(Request $request)\n {\n $requestedLanguage = $request->get('language');\n if ($requestedLanguage) {\n if ($requestedLanguage != 'default') {\n $request->setLocale($requestedLanguage);\n }\n } else {\n $requestedLanguage = $request->getLocale();\n }", " return $requestedLanguage;\n }", " /**\n * @param string $fileHandle\n *\n * @return string\n */\n protected function getCsvFile($fileHandle)\n {\n return $fileHandle . '.csv';\n }", " /**\n * @Route(\"/get-export-jobs\", name=\"getexportjobs\", methods={\"POST\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n * @param EventDispatcherInterface $eventDispatcher\n *\n * @return JsonResponse\n */\n public function getExportJobsAction(Request $request, GridHelperService $gridHelperService, EventDispatcherInterface $eventDispatcher)\n {\n $requestedLanguage = $this->extractLanguage($request);\n $allParams = array_merge($request->request->all(), $request->query->all());", " $list = $gridHelperService->prepareListingForGrid($allParams, $requestedLanguage, $this->getAdminUser());", " $beforeListPrepareEvent = new GenericEvent($this, [\n 'list' => $list,\n 'context' => $allParams,\n ]);\n $eventDispatcher->dispatch($beforeListPrepareEvent, AdminEvents::OBJECT_LIST_BEFORE_EXPORT_PREPARE);", " $list = $beforeListPrepareEvent->getArgument('list');", " $ids = $list->loadIdList();", " $jobs = array_chunk($ids, 20);", " $fileHandle = uniqid('export-');", " $storage = Storage::get('temp');\n $storage->write($this->getCsvFile($fileHandle), '');", " return $this->adminJson(['success' => true, 'jobs' => $jobs, 'fileHandle' => $fileHandle]);\n }", " /**\n * @Route(\"/do-export\", name=\"doexport\", methods={\"POST\"})\n *\n * @param Request $request\n * @param LocaleServiceInterface $localeService\n * @param EventDispatcherInterface $eventDispatcher\n *\n * @return JsonResponse\n *\n * @throws \\Exception\n */\n public function doExportAction(Request $request, LocaleServiceInterface $localeService, EventDispatcherInterface $eventDispatcher)\n {\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $ids = $request->get('ids');\n $settings = $request->get('settings');\n $settings = json_decode($settings, true);\n $delimiter = $settings['delimiter'] ?? ';';", " $allParams = array_merge($request->request->all(), $request->query->all());", " $enableInheritance = $settings['enableInheritance'] ?? null;\n DataObject\\Concrete::setGetInheritedValues($enableInheritance);", " $class = DataObject\\ClassDefinition::getById($request->get('classId'));", " if (!$class) {\n throw new \\Exception('No class definition found');\n }", " $className = $class->getName();\n $listClass = '\\\\Pimcore\\\\Model\\\\DataObject\\\\' . ucfirst($className) . '\\\\Listing';", " /** @var \\Pimcore\\Model\\DataObject\\Listing $list */\n $list = new $listClass();", " $quotedIds = [];\n foreach ($ids as $id) {\n $quotedIds[] = $list->quote($id);\n }", " $list->setObjectTypes(DataObject::$types);\n $list->setCondition('o_id IN (' . implode(',', $quotedIds) . ')');\n $list->setOrderKey(' FIELD(o_id, ' . implode(',', $quotedIds) . ')', false);", " $beforeListExportEvent = new GenericEvent($this, [\n 'list' => $list,\n 'context' => $allParams,\n ]);\n $eventDispatcher->dispatch($beforeListExportEvent, AdminEvents::OBJECT_LIST_BEFORE_EXPORT);", " $list = $beforeListExportEvent->getArgument('list');", " $fields = $request->get('fields');", " $addTitles = (bool) $request->get('initial');", " $requestedLanguage = $this->extractLanguage($request);", " $contextFromRequest = $request->get('context');\n if ($contextFromRequest) {\n $contextFromRequest = json_decode($contextFromRequest, true);\n }", " $context = [\n 'source' => 'pimcore-export',\n ];", " if (is_array($contextFromRequest)) {\n $context = array_merge($context, $contextFromRequest);\n }", " $csv = DataObject\\Service::getCsvData($requestedLanguage, $localeService, $list, $fields, $addTitles, $context);", " $storage = Storage::get('temp');\n $csvFile = $this->getCsvFile($fileHandle);", " $fileStream = $storage->readStream($csvFile);", " $temp = tmpfile();\n stream_copy_to_stream($fileStream, $temp, null, 0);", " $firstLine = true;\n $lineCount = count($csv);", " if (!$addTitles && $lineCount > 0) {\n fwrite($temp, \"\\r\\n\");\n }", " for ($i = 0; $i < $lineCount; $i++) {\n $line = $csv[$i];\n if ($addTitles && $firstLine) {\n $firstLine = false;\n $line = implode($delimiter, $line);\n fwrite($temp, $line);\n } else {\n fwrite($temp, implode($delimiter, array_map([$this, 'encodeFunc'], $line)));\n }\n if ($i < $lineCount - 1) {\n fwrite($temp, \"\\r\\n\");\n }\n }\n $storage->writeStream($csvFile, $temp);", " return $this->adminJson(['success' => true]);\n }", " public function encodeFunc($value)\n {\n $value = str_replace('\"', '\"\"', $value);\n //force wrap value in quotes and return\n return '\"' . $value . '\"';\n }", " /**\n * @Route(\"/download-csv-file\", name=\"downloadcsvfile\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return Response\n */\n public function downloadCsvFileAction(Request $request)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n $csvData = $storage->read($csvFile);\n $response = new Response($csvData);\n $response->headers->set('Content-Type', 'application/csv');\n $disposition = HeaderUtils::makeDisposition(\n HeaderUtils::DISPOSITION_ATTACHMENT,\n 'export.csv'\n );", " $response->headers->set('Content-Disposition', $disposition);\n $storage->delete($csvFile);", " return $response;\n } catch (FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('CSV file not found');\n }\n }", " /**\n * @Route(\"/download-xlsx-file\", name=\"downloadxlsxfile\", methods={\"GET\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n *\n * @return BinaryFileResponse\n */\n public function downloadXlsxFileAction(Request $request, GridHelperService $gridHelperService)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n return $gridHelperService->createXlsxExportFile($storage, $fileHandle, $csvFile);\n } catch (\\Exception | FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('XLSX file not found');\n }\n }", " /**\n * Flattens object data to an array with key=>value where\n * value is simply a string representation of the value (for objects, hrefs and assets the full path is used)\n *\n * @param DataObject\\Concrete $object\n *\n * @return array\n */\n protected function csvObjectData($object)\n {\n $o = [];\n foreach ($object->getClass()->getFieldDefinitions() as $key => $value) {\n $o[$key] = $value->getForCsvExport($object);\n }", " $o['id (system)'] = $object->getId();\n $o['key (system)'] = $object->getKey();\n $o['fullpath (system)'] = $object->getRealFullPath();\n $o['published (system)'] = $object->isPublished();\n $o['type (system)'] = $object->getType();", " return $o;\n }", " /**\n * @Route(\"/get-batch-jobs\", name=\"getbatchjobs\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getBatchJobsAction(Request $request, GridHelperService $gridHelperService)\n {\n if ($request->get('language')) {\n $request->setLocale($request->get('language'));\n }", " $allParams = array_merge($request->request->all(), $request->query->all());\n $list = $gridHelperService->prepareListingForGrid($allParams, $request->getLocale(), $this->getAdminUser());", " $jobs = $list->loadIdList();", " return $this->adminJson(['success' => true, 'jobs' => $jobs]);\n }", " /**\n * @Route(\"/batch\", name=\"batch\", methods={\"PUT\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function batchAction(Request $request)\n {\n $success = true;", " try {\n if ($request->get('data')) {\n $params = $this->decodeJson($request->get('data'), true);\n $object = DataObject\\Concrete::getById($params['job']);", " if ($object) {\n $name = $params['name'];", " if (!$object->isAllowed('save') || ($name === 'published' && !$object->isAllowed('publish'))) {\n throw new \\Exception(\"Permission denied. You don't have the rights to save this object.\");\n }", " $append = $params['append'] ?? false;\n $remove = $params['remove'] ?? false;", " $className = $object->getClassName();\n $class = DataObject\\ClassDefinition::getByName($className);\n $value = $params['value'];\n if ($params['valueType'] == 'object') {\n $value = $this->decodeJson($value);\n }", " $parts = explode('~', $name);", " if (substr($name, 0, 1) == '~') {\n $type = $parts[1];\n $field = $parts[2];\n $keyId = $parts[3];", " if ($type == 'classificationstore') {\n $requestedLanguage = $params['language'];\n if ($requestedLanguage) {\n if ($requestedLanguage != 'default') {\n $request->setLocale($requestedLanguage);\n }\n } else {\n $requestedLanguage = $request->getLocale();\n }", " $groupKeyId = explode('-', $keyId);\n $groupId = (int) $groupKeyId[0];\n $keyId = (int) $groupKeyId[1];", " $getter = 'get' . ucfirst($field);\n if (method_exists($object, $getter)) {\n /** @var DataObject\\ClassDefinition\\Data\\Classificationstore $csFieldDefinition */\n $csFieldDefinition = $object->getClass()->getFieldDefinition($field);\n $csLanguage = $requestedLanguage;\n if (!$csFieldDefinition->isLocalized()) {\n $csLanguage = 'default';\n }", " /** @var DataObject\\ClassDefinition\\Data\\Classificationstore $fd */\n $fd = $class->getFieldDefinition($field);\n $keyConfig = $fd->getKeyConfiguration($keyId);\n $dataDefinition = DataObject\\Classificationstore\\Service::getFieldDefinitionFromKeyConfig($keyConfig);", " /** @var DataObject\\Classificationstore $classificationStoreData */\n $classificationStoreData = $object->$getter();\n if ($append) {\n $oldValue = $classificationStoreData->getLocalizedKeyValue($groupId, $keyId);\n $value = $dataDefinition->appendData($oldValue, $value);\n }\n if ($remove) {\n $oldValue = $classificationStoreData->getLocalizedKeyValue($groupId, $keyId);\n $value = $dataDefinition->removeData($oldValue, $value);\n }\n $classificationStoreData->setLocalizedKeyValue(\n $groupId,\n $keyId,\n $dataDefinition->getDataFromEditmode($value),\n $csLanguage\n );\n }\n }\n } elseif (count($parts) > 1) {\n // check for bricks\n $brickType = $parts[0];\n $brickKey = $parts[1];\n $brickField = DataObject\\Service::getFieldForBrickType($object->getClass(), $brickType);", " $fieldGetter = 'get' . ucfirst($brickField);\n $brickGetter = 'get' . ucfirst($brickType);\n $valueSetter = 'set' . ucfirst($brickKey);", " $brick = $object->$fieldGetter()->$brickGetter();\n if (empty($brick)) {\n $classname = '\\\\Pimcore\\\\Model\\\\DataObject\\\\Objectbrick\\\\Data\\\\' . ucfirst($brickType);\n $brickSetter = 'set' . ucfirst($brickType);\n $brick = new $classname($object);\n $object->$fieldGetter()->$brickSetter($brick);\n }", " $brickClass = DataObject\\Objectbrick\\Definition::getByKey($brickType);\n $field = $brickClass->getFieldDefinition($brickKey);", " $newData = $field->getDataFromEditmode($value, $object);", " if ($append) {\n $valueGetter = 'get' . ucfirst($brickKey);\n $existingData = $brick->$valueGetter();\n $newData = $field->appendData($existingData, $newData);\n }\n if ($remove) {\n $valueGetter = 'get' . ucfirst($brickKey);\n $existingData = $brick->$valueGetter();\n $newData = $field->removeData($existingData, $newData);\n }\n $brick->$valueSetter($newData);\n } else {\n // everything else\n $field = $class->getFieldDefinition($name);\n if ($field) {\n $newData = $field->getDataFromEditmode($value, $object);", " if ($append) {\n $existingData = $object->{'get' . $name}();\n $newData = $field->appendData($existingData, $newData);\n }\n if ($remove) {\n $existingData = $object->{'get' . $name}();\n $newData = $field->removeData($existingData, $newData);\n }\n $object->setValue($name, $newData);\n } else {\n // check if it is a localized field\n if ($params['language']) {\n $localizedField = $class->getFieldDefinition('localizedfields');\n if ($localizedField instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $field = $localizedField->getFieldDefinition($name);\n if ($field) {\n $getter = 'get' . $name;\n $setter = 'set' . $name;\n $newData = $field->getDataFromEditmode($value, $object);\n if ($append) {\n $existingData = $object->$getter($params['language']);\n $newData = $field->appendData($existingData, $newData);\n }\n if ($remove) {\n $existingData = $object->$getter($request->get('language'));\n $newData = $field->removeData($existingData, $newData);\n }", " $object->$setter($newData, $params['language']);\n }\n }\n }", " // seems to be a system field, this is actually only possible for the \"published\" field yet\n if ($name == 'published') {\n if ($value === 'false' || empty($value)) {\n $object->setPublished(false);\n } else {\n $object->setPublished(true);\n }\n }\n }\n }", " try {\n // don't check for mandatory fields here\n $object->setOmitMandatoryCheck(!$object->isPublished());\n $object->setUserModification($this->getAdminUser()->getId());\n $object->save();\n $success = true;\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n } else {\n Logger::debug('DataObjectController::batchAction => There is no object left to update.');", " return $this->adminJson(['success' => false, 'message' => 'DataObjectController::batchAction => There is no object left to update.']);\n }\n }\n } catch (\\Exception $e) {\n Logger::err((string) $e);", " return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }", " return $this->adminJson(['success' => $success]);\n }", " /**\n * @Route(\"/get-available-visible-vields\", name=\"getavailablevisiblefields\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getAvailableVisibleFieldsAction(Request $request)\n {\n $class = null;\n $fields = null;", " $classList = [];\n $classNameList = [];", " if ($request->get('classes')) {\n $classNameList = $request->get('classes');\n $classNameList = explode(',', $classNameList);\n foreach ($classNameList as $className) {\n $class = DataObject\\ClassDefinition::getByName($className);\n if ($class) {\n $classList[] = $class;\n }\n }\n }", " if (!$classList) {\n return $this->adminJson(['availableFields' => []]);\n }\n $availableFields = [];\n foreach (self::SYSTEM_COLUMNS as $field) {\n $availableFields[] = [\n 'key' => $field,\n 'value' => $field,\n ];\n }", " /** @var DataObject\\ClassDefinition\\Data[] $commonFields */\n $commonFields = [];", " $firstOne = true;\n foreach ($classNameList as $className) {\n $class = DataObject\\ClassDefinition::getByName($className);\n if ($class) {\n $fds = $class->getFieldDefinitions();", " $additionalFieldNames = array_keys($fds);\n $localizedFields = $class->getFieldDefinition('localizedfields');\n if ($localizedFields instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $lfNames = array_keys($localizedFields->getFieldDefinitions());\n $additionalFieldNames = array_merge($additionalFieldNames, $lfNames);\n }", " foreach ($commonFields as $commonFieldKey => $commonFieldDefinition) {\n if (!in_array($commonFieldKey, $additionalFieldNames)) {\n unset($commonFields[$commonFieldKey]);\n }\n }", " $this->processAvailableFieldDefinitions($fds, $firstOne, $commonFields);", " $firstOne = false;\n }\n }", " $commonFieldKeys = array_keys($commonFields);\n foreach ($commonFieldKeys as $field) {\n $availableFields[] = [\n 'key' => $field,\n 'value' => $field,\n ];\n }", " return $this->adminJson(['availableFields' => $availableFields]);\n }", " /**\n * @param DataObject\\ClassDefinition\\Data[] $fds\n * @param bool $firstOne\n * @param DataObject\\ClassDefinition\\Data[] $commonFields\n */\n protected function processAvailableFieldDefinitions($fds, &$firstOne, &$commonFields)\n {\n foreach ($fds as $fd) {\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\Fieldcollections || $fd instanceof DataObject\\ClassDefinition\\Data\\Objectbricks\n || $fd instanceof DataObject\\ClassDefinition\\Data\\Block) {\n continue;\n }", " if ($fd instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $lfDefs = $fd->getFieldDefinitions();\n $this->processAvailableFieldDefinitions($lfDefs, $firstOne, $commonFields);\n } elseif ($firstOne || (isset($commonFields[$fd->getName()]) && $commonFields[$fd->getName()]->getFieldtype() == $fd->getFieldtype())) {\n $commonFields[$fd->getName()] = $fd;\n }\n }\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\Bundle\\AdminBundle\\Controller\\Admin\\DataObject;", "use League\\Flysystem\\FilesystemException;\nuse League\\Flysystem\\UnableToReadFile;\nuse PhpOffice\\PhpSpreadsheet\\Reader\\Csv;\nuse PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx;\nuse Pimcore\\Bundle\\AdminBundle\\Controller\\AdminController;\nuse Pimcore\\Bundle\\AdminBundle\\Helper\\GridHelperService;\nuse Pimcore\\Config;\nuse Pimcore\\Db;\nuse Pimcore\\Event\\AdminEvents;\nuse Pimcore\\File;\nuse Pimcore\\Localization\\LocaleServiceInterface;\nuse Pimcore\\Logger;\nuse Pimcore\\Model\\DataObject;\nuse Pimcore\\Model\\GridConfig;\nuse Pimcore\\Model\\GridConfigFavourite;\nuse Pimcore\\Model\\GridConfigShare;\nuse Pimcore\\Model\\User;", "use Pimcore\\Security\\SecurityHelper;", "use Pimcore\\Tool;\nuse Pimcore\\Tool\\Storage;\nuse Pimcore\\Version;\nuse Symfony\\Component\\EventDispatcher\\GenericEvent;\nuse Symfony\\Component\\HttpFoundation\\BinaryFileResponse;\nuse Symfony\\Component\\HttpFoundation\\HeaderUtils;\nuse Symfony\\Component\\HttpFoundation\\JsonResponse;\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpFoundation\\Session\\Attribute\\AttributeBagInterface;\nuse Symfony\\Component\\Routing\\Annotation\\Route;\nuse Symfony\\Contracts\\EventDispatcher\\EventDispatcherInterface;", "/**\n * @Route(\"/object-helper\", name=\"pimcore_admin_dataobject_dataobjecthelper_\")\n *\n * @internal\n */\nclass DataObjectHelperController extends AdminController\n{\n const SYSTEM_COLUMNS = ['id', 'fullpath', 'key', 'published', 'creationDate', 'modificationDate', 'filename', 'classname'];", " /**\n * @Route(\"/load-object-data\", name=\"loadobjectdata\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function loadObjectDataAction(Request $request)\n {\n $object = DataObject::getById((int) $request->get('id'));\n $result = [];\n if ($object) {\n $result['success'] = true;\n $fields = $request->get('fields');\n $result['fields'] = DataObject\\Service::gridObjectData($object, $fields);\n } else {\n $result['success'] = false;\n }", " return $this->adminJson($result);\n }", " /**\n * @param int $userId\n * @param string $classId\n * @param string|null $searchType\n *\n * @return array\n */\n public function getMyOwnGridColumnConfigs($userId, $classId, $searchType = null)\n {\n $db = Db::get();\n $configListingConditionParts = [];\n $configListingConditionParts[] = 'ownerId = ' . $userId;\n $configListingConditionParts[] = 'classId = ' . $db->quote($classId);", " if ($searchType) {\n $configListingConditionParts[] = 'searchType = ' . $db->quote($searchType);\n }", " $configCondition = implode(' AND ', $configListingConditionParts);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition($configCondition);\n $configListing = $configListing->load();", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @param User $user\n * @param string $classId\n * @param string $searchType\n *\n * @return array\n */\n public function getSharedGridColumnConfigs($user, $classId, $searchType = null)\n {\n $configListing = [];", " $userIds = [$user->getId()];\n // collect all roles\n $userIds = array_merge($userIds, $user->getRoles());\n $userIds = implode(',', $userIds);\n $db = Db::get();", " $query = 'select distinct c1.id from gridconfigs c1, gridconfig_shares s\n where (c1.searchType = ' . $db->quote($searchType) . ' and ((c1.id = s.gridConfigId and s.sharedWithUserId IN (' . $userIds . '))) and c1.classId = ' . $db->quote($classId) . ')\n UNION distinct select c2.id from gridconfigs c2 where shareGlobally = 1 and c2.classId = '. $db->quote($classId) . ' and c2.ownerId != ' . $db->quote($user->getId());", " $ids = $db->fetchFirstColumn($query);", " if ($ids) {\n $ids = implode(',', $ids);\n $configListing = new GridConfig\\Listing();\n $configListing->setOrderKey('name');\n $configListing->setOrder('ASC');\n $configListing->setCondition('id in (' . $ids . ')');\n $configListing = $configListing->load();\n }", " $configData = [];\n if (is_array($configListing)) {\n foreach ($configListing as $config) {\n $configData[] = $config->getObjectVars();\n }\n }", " return $configData;\n }", " /**\n * @Route(\"/get-export-configs\", name=\"getexportconfigs\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getExportConfigsAction(Request $request)\n {\n $classId = $request->get('classId');\n $list = $this->getMyOwnGridColumnConfigs($this->getAdminUser()->getId(), $classId);\n if (!is_array($list)) {\n $list = [];\n }\n $list = array_merge($list, $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId));\n $result = [];", " $result[] = [\n 'id' => -1,\n 'name' => '--default--',\n ];", " if ($list) {\n /** @var GridConfig $config */\n foreach ($list as $config) {\n $result[] = [\n 'id' => $config['id'],\n 'name' => $config['name'],\n ];\n }\n }", " return $this->adminJson(['success' => true, 'data' => $result]);\n }", " /**\n * @Route(\"/grid-delete-column-config\", name=\"griddeletecolumnconfig\", methods={\"DELETE\"})\n *\n * @param Request $request\n * @param EventDispatcherInterface $eventDispatcher\n * @param Config $config\n *\n * @return JsonResponse\n */\n public function gridDeleteColumnConfigAction(Request $request, EventDispatcherInterface $eventDispatcher, Config $config)\n {\n $gridConfigId = $request->get('gridConfigId');\n $gridConfig = GridConfig::getById($gridConfigId);\n $success = false;\n if ($gridConfig) {\n if ($gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $gridConfig->delete();\n $success = true;\n }", " $newGridConfig = $this->doGetGridColumnConfig($request, $config, true);\n $newGridConfig['deleteSuccess'] = $success;", " $event = new GenericEvent($this, [\n 'data' => $newGridConfig,\n 'request' => $request,\n 'config' => $config,\n 'context' => 'delete',\n ]);", " $eventDispatcher->dispatch($event, AdminEvents::OBJECT_GRID_GET_COLUMN_CONFIG_PRE_SEND_DATA);\n $newGridConfig = $event->getArgument('data');", " return $this->adminJson($newGridConfig);\n }", " /**\n * @Route(\"/grid-get-column-config\", name=\"gridgetcolumnconfig\", methods={\"GET\"})\n *\n * @param Request $request\n * @param EventDispatcherInterface $eventDispatcher\n * @param Config $config\n *\n * @return JsonResponse\n */\n public function gridGetColumnConfigAction(Request $request, EventDispatcherInterface $eventDispatcher, Config $config)\n {\n $result = $this->doGetGridColumnConfig($request, $config);", " $event = new GenericEvent($this, [\n 'data' => $result,\n 'request' => $request,\n 'config' => $config,\n 'context' => 'get',\n ]);", " $eventDispatcher->dispatch($event, AdminEvents::OBJECT_GRID_GET_COLUMN_CONFIG_PRE_SEND_DATA);\n $result = $event->getArgument('data');", " return $this->adminJson($result);\n }", " /**\n * @param Request $request\n * @param Config $config\n * @param bool $isDelete\n *\n * @return array\n */\n public function doGetGridColumnConfig(Request $request, Config $config, $isDelete = false)\n {\n $class = null;\n $fields = null;", " if ($request->get('id')) {\n $class = DataObject\\ClassDefinition::getById($request->get('id'));\n } elseif ($request->get('name')) {\n $class = DataObject\\ClassDefinition::getByName($request->get('name'));\n }", " $gridConfigId = null;\n $gridType = 'search';\n if ($request->get('gridtype')) {\n $gridType = $request->get('gridtype');\n }", " $objectId = (int) $request->get('objectId');", " if ($objectId) {\n $fields = DataObject\\Service::getCustomGridFieldDefinitions($class->getId(), $objectId);\n }", " $context = ['purpose' => 'gridconfig'];\n if ($class) {\n $context['class'] = $class;\n }", " if ($objectId) {\n $object = DataObject::getById($objectId);\n $context['object'] = $object;\n }", " if (!$fields && $class) {\n $fields = $class->getFieldDefinitions();\n }", " $types = [];\n if ($request->get('types')) {\n $types = explode(',', $request->get('types'));\n }", " $userId = $this->getAdminUser()->getId();", " $requestedGridConfigId = $isDelete ? null : $request->get('gridConfigId');", " // grid config\n $gridConfig = [];\n $searchType = $request->get('searchType');", " if (strlen($requestedGridConfigId) == 0 && $class) {\n // check if there is a favourite view\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $class->getId(), $objectId ?: 0, $searchType);\n if (!$favourite && $objectId) {\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId($userId, $class->getId(), 0, $searchType);\n }", " if ($favourite) {\n $requestedGridConfigId = $favourite->getGridConfigId();\n }\n }", " if (is_numeric($requestedGridConfigId) && $requestedGridConfigId > 0) {\n $db = Db::get();\n $savedGridConfig = GridConfig::getById((int) $requestedGridConfigId);", " if ($savedGridConfig) {\n $shared = false;\n if (!$this->getAdminUser()->isAdmin()) {\n $userIds = [$this->getAdminUser()->getId()];\n if ($this->getAdminUser()->getRoles()) {\n $userIds = array_merge($userIds, $this->getAdminUser()->getRoles());\n }\n $userIds = implode(',', $userIds);\n $shared = ($savedGridConfig->getOwnerId() != $userId && $savedGridConfig->isShareGlobally()) || $db->fetchOne('select 1 from gridconfig_shares where sharedWithUserId IN ('.$userIds.') and gridConfigId = '.$savedGridConfig->getId());\n // $shared = $savedGridConfig->isShareGlobally() || GridConfigShare::getByGridConfigAndSharedWithId($savedGridConfig->getId(), $this->getUser()->getId());", " if (!$shared && $savedGridConfig->getOwnerId() != $this->getAdminUser()->getId()) {\n throw new \\Exception('You are neither the owner of this config nor it is shared with you');\n }\n }", " $gridConfigId = $savedGridConfig->getId();\n $gridConfig = $savedGridConfig->getConfig();\n $gridConfig = json_decode($gridConfig, true);\n $gridConfigName = $savedGridConfig->getName();\n $owner = $savedGridConfig->getOwnerId();\n $ownerObject = User::getById($owner);\n if ($ownerObject instanceof User) {\n $owner = $ownerObject->getName();\n }\n $modificationDate = $savedGridConfig->getModificationDate();\n $gridConfigDescription = $savedGridConfig->getDescription();\n $sharedGlobally = $savedGridConfig->isShareGlobally();\n $setAsFavourite = $savedGridConfig->isSetAsFavourite();", "\n foreach($gridConfig['columns'] as &$column) {\n if (array_key_exists('isOperator', $column) && $column['isOperator']) {\n $colAttributes = &$column['fieldConfig']['attributes'];\n SecurityHelper::convertHtmlSpecialCharsArrayKeys($colAttributes, ['label', 'attribute', 'param1']);\n }\n }", " }\n }", " $localizedFields = [];\n $objectbrickFields = [];\n if (is_array($fields)) {\n foreach ($fields as $key => $field) {\n if ($field instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $localizedFields[] = $field;\n } elseif ($field instanceof DataObject\\ClassDefinition\\Data\\Objectbricks) {\n $objectbrickFields[] = $field;\n }\n }\n }", " $availableFields = [];", " if (empty($gridConfig)) {\n $availableFields = $this->getDefaultGridFields(\n $request->get('no_system_columns'),\n $class,\n $gridType,\n $request->get('no_brick_columns'),\n $fields,\n $context,\n $objectId,\n $types);\n } else {\n $savedColumns = $gridConfig['columns'];\n foreach ($savedColumns as $key => $sc) {\n if (!$sc['hidden']) {\n if (in_array($key, self::SYSTEM_COLUMNS)) {\n $colConfig = [\n 'key' => $key,\n 'type' => 'system',\n 'label' => $key,\n 'locked' => $sc['locked'] ?? null,\n 'position' => $sc['position'],\n ];\n if (isset($sc['width'])) {\n $colConfig['width'] = $sc['width'];\n }\n $availableFields[] = $colConfig;\n } else {\n $keyParts = explode('~', $key);", " if (substr($key, 0, 1) == '~') {\n // not needed for now\n $type = $keyParts[1];\n // $field = $keyParts[2];\n $groupAndKeyId = explode('-', $keyParts[3]);\n $keyId = (int) $groupAndKeyId[1];", " if ($type == 'classificationstore') {\n $keyDef = DataObject\\Classificationstore\\KeyConfig::getById($keyId);\n if ($keyDef) {\n $keyFieldDef = json_decode($keyDef->getDefinition(), true);\n if ($keyFieldDef) {\n $keyFieldDef = \\Pimcore\\Model\\DataObject\\Classificationstore\\Service::getFieldDefinitionFromJson($keyFieldDef, $keyDef->getType());\n $fieldConfig = $this->getFieldGridConfig($keyFieldDef, $gridType, $sc['position'], true, null, $class, $objectId);\n if ($fieldConfig) {\n $fieldConfig['key'] = $key;\n $fieldConfig['label'] = '#' . $keyFieldDef->getTitle();\n if (isset($sc['locked'])) {\n $fieldConfig['locked'] = $sc['locked'];\n }\n $availableFields[] = $fieldConfig;\n }\n }\n }\n }\n } elseif (count($keyParts) > 1) {\n $brick = $keyParts[0];\n $brickDescriptor = null;", " if (strpos($brick, '?') !== false) {\n $brickDescriptor = substr($brick, 1);\n $brickDescriptor = json_decode($brickDescriptor, true);\n $keyPrefix = $brick . '~';\n $brick = $brickDescriptor['containerKey'];\n } else {\n $keyPrefix = $brick . '~';\n }", " $fieldname = $keyParts[1];", " $brickClass = DataObject\\Objectbrick\\Definition::getByKey($brick);", " $fd = null;\n if ($brickClass instanceof DataObject\\Objectbrick\\Definition) {\n if ($brickDescriptor) {\n $innerContainer = $brickDescriptor['innerContainer'] ?? 'localizedfields';\n /** @var DataObject\\ClassDefinition\\Data\\Localizedfields $localizedFields */\n $localizedFields = $brickClass->getFieldDefinition($innerContainer);\n $fd = $localizedFields->getFieldDefinition($brickDescriptor['brickfield']);\n } else {\n $fd = $brickClass->getFieldDefinition($fieldname);\n }\n }", " if ($fd !== null) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $sc['position'], true, $keyPrefix, $class, $objectId);\n if (!empty($fieldConfig)) {\n if (isset($sc['width'])) {\n $fieldConfig['width'] = $sc['width'];\n }\n if (isset($sc['locked'])) {\n $fieldConfig['locked'] = $sc['locked'];\n }\n $availableFields[] = $fieldConfig;\n }\n }\n } else {\n if (DataObject\\Service::isHelperGridColumnConfig($key)) {\n $calculatedColumnConfig = $this->getCalculatedColumnConfig($savedColumns[$key]);\n if ($calculatedColumnConfig) {\n $availableFields[] = $calculatedColumnConfig;\n }\n } else {\n $fd = $class->getFieldDefinition($key);\n //if not found, look for localized fields\n if (empty($fd)) {\n foreach ($localizedFields as $lf) {\n $fd = $lf->getFieldDefinition($key);\n if (!empty($fd)) {\n break;\n }\n }\n }", " if (!empty($fd)) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $sc['position'], true, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n if (isset($sc['width'])) {\n $fieldConfig['width'] = $sc['width'];\n }\n if (isset($sc['locked'])) {\n $fieldConfig['locked'] = $sc['locked'];\n }\n $availableFields[] = $fieldConfig;\n }\n }\n }\n }\n }\n }\n }\n }\n usort($availableFields, function ($a, $b) {\n if ($a['position'] == $b['position']) {\n return 0;\n }", " return ($a['position'] < $b['position']) ? -1 : 1;\n });", " $frontendLanguages = Tool\\Admin::reorderWebsiteLanguages(\\Pimcore\\Tool\\Admin::getCurrentUser(), $config['general']['valid_languages']);\n if ($frontendLanguages) {\n $language = explode(',', $frontendLanguages)[0];\n } else {\n $language = $request->getLocale();\n }", " if (!Tool::isValidLanguage($language)) {\n $validLanguages = Tool::getValidLanguages();\n $language = $validLanguages[0];\n }", " if (!empty($gridConfig) && !empty($gridConfig['language'])) {\n $language = $gridConfig['language'];\n }", " $availableConfigs = $class ? $this->getMyOwnGridColumnConfigs($userId, $class->getId(), $searchType) : [];\n $sharedConfigs = $class ? $this->getSharedGridColumnConfigs($this->getAdminUser(), $class->getId(), $searchType) : [];\n $settings = $this->getShareSettings((int)$gridConfigId);\n $settings['gridConfigId'] = (int)$gridConfigId;\n $settings['gridConfigName'] = $gridConfigName ?? null;\n $settings['gridConfigDescription'] = $gridConfigDescription ?? null;\n $settings['owner'] = $owner ?? null;\n $settings['modificationDate'] = $modificationDate ?? null;\n $settings['shareGlobally'] = $sharedGlobally ?? null;\n $settings['setAsFavourite'] = $setAsFavourite ?? null;\n $settings['isShared'] = !$gridConfigId || ($shared ?? null);", " $context = $gridConfig['context'] ?? null;\n if ($context) {\n $context = json_decode($context, true);\n }", " return [\n 'sortinfo' => $gridConfig['sortinfo'] ?? false,\n 'language' => $language,\n 'availableFields' => $availableFields,\n 'settings' => $settings,\n 'onlyDirectChildren' => $gridConfig['onlyDirectChildren'] ?? false,\n 'pageSize' => $gridConfig['pageSize'] ?? false,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n 'context' => $context,\n 'sqlFilter' => $gridConfig['sqlFilter'] ?? '',\n 'searchFilter' => $gridConfig['searchFilter'] ?? '',\n ];\n }", " /**\n * @param bool $noSystemColumns\n * @param DataObject\\ClassDefinition|null $class\n * @param string $gridType\n * @param bool $noBrickColumns\n * @param DataObject\\ClassDefinition\\Data[] $fields\n * @param array $context\n * @param int $objectId\n * @param array $types\n *\n * @return array\n */\n public function getDefaultGridFields($noSystemColumns, $class, $gridType, $noBrickColumns, $fields, $context, $objectId, $types = [])\n {\n $count = 0;\n $availableFields = [];", " if (!$noSystemColumns && $class) {\n $vis = $class->getPropertyVisibility();\n foreach (self::SYSTEM_COLUMNS as $sc) {\n $key = $sc;\n if ($key === 'fullpath') {\n $key = 'path';\n }", " if (empty($types) && (!empty($vis[$gridType][$key]) || $gridType === 'all')) {\n $availableFields[] = [\n 'key' => $sc,\n 'type' => 'system',\n 'label' => $sc,\n 'position' => $count, ];\n $count++;\n }\n }\n }", " $includeBricks = !$noBrickColumns;", " if (is_array($fields)) {\n foreach ($fields as $key => $field) {\n if ($field instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n foreach ($field->getFieldDefinitions($context) as $fd) {\n if (empty($types) || in_array($fd->getFieldType(), $types)) {\n $fieldConfig = $this->getFieldGridConfig($fd, $gridType, $count, false, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n }\n }\n } elseif ($field instanceof DataObject\\ClassDefinition\\Data\\Objectbricks && $includeBricks) {\n if (in_array($field->getFieldType(), $types)) {\n $fieldConfig = $this->getFieldGridConfig($field, $gridType, $count, false, null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n } else {\n $allowedTypes = $field->getAllowedTypes();\n if (!empty($allowedTypes)) {\n foreach ($allowedTypes as $t) {\n $brickClass = DataObject\\Objectbrick\\Definition::getByKey($t);\n $brickFields = $brickClass->getFieldDefinitions($context);", " $this->appendBrickFields($field, $brickFields, $availableFields, $gridType, $count, $t, $class, $objectId);\n }\n }\n }\n } else {\n if (empty($types) || in_array($field->getFieldType(), $types)) {\n $fieldConfig = $this->getFieldGridConfig($field, $gridType, $count, !empty($types), null, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n }\n }\n }\n }", " return $availableFields;\n }", " /**\n * @param DataObject\\ClassDefinition\\Data $field\n * @param DataObject\\ClassDefinition\\Data[] $brickFields\n * @param array $availableFields\n * @param string $gridType\n * @param int $count\n * @param string $brickType\n * @param DataObject\\ClassDefinition $class\n * @param int $objectId\n * @param array|null $context\n */\n protected function appendBrickFields($field, $brickFields, &$availableFields, $gridType, &$count, $brickType, $class, $objectId, $context = null)\n {\n if (!empty($brickFields)) {\n foreach ($brickFields as $bf) {\n if ($bf instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $localizedFieldDefinitions = $bf->getFieldDefinitions();", " $localizedContext = [\n 'containerKey' => $brickType,\n 'fieldname' => $field->getName(),\n ];", " $this->appendBrickFields($bf, $localizedFieldDefinitions, $availableFields, $gridType, $count, $brickType, $class, $objectId, $localizedContext);\n } else {\n if ($context) {\n $context['brickfield'] = $bf->getName();\n $keyPrefix = '?' . json_encode($context) . '~';\n } else {\n $keyPrefix = $brickType . '~';\n }\n $fieldConfig = $this->getFieldGridConfig($bf, $gridType, $count, false, $keyPrefix, $class, $objectId);\n if (!empty($fieldConfig)) {\n $availableFields[] = $fieldConfig;\n $count++;\n }\n }\n }\n }\n }", " /**\n * @param array $config\n *\n * @return mixed\n */\n protected function getCalculatedColumnConfig($config)\n {\n try {\n $calculatedColumnConfig = Tool\\Session::useSession(function (AttributeBagInterface $session) use ($config) {\n //otherwise create a new one", " $calculatedColumn = [];\n // note that we have to generate a new key!", " $existingKey = $config['fieldConfig']['key'];\n $calculatedColumnConfig['key'] = $existingKey;\n $calculatedColumnConfig['position'] = $config['position'];\n $calculatedColumnConfig['isOperator'] = true;\n $calculatedColumnConfig['attributes'] = $config['fieldConfig']['attributes'];\n $calculatedColumnConfig['width'] = $config['width'];\n $calculatedColumnConfig['locked'] = $config['locked'];", " $existingColumns = $session->get('helpercolumns', []);", " if (isset($existingColumns[$existingKey])) {\n // if the configuration is still in the session, then reuse it\n return $calculatedColumnConfig;\n }", " $newKey = '#' . uniqid();\n $calculatedColumnConfig['key'] = $newKey;", " // prepare a column config on the fly\n $phpConfig = json_encode($config['fieldConfig']);\n $phpConfig = json_decode($phpConfig);\n $helperColumns = [];\n $helperColumns[$newKey] = $phpConfig;", " $helperColumns = array_merge($helperColumns, $existingColumns);\n $session->set('helpercolumns', $helperColumns);", " return $calculatedColumnConfig;\n }, 'pimcore_gridconfig');", " return $calculatedColumnConfig;\n } catch (\\Exception $e) {\n Logger::error((string) $e);\n }\n }", " /**\n * @Route(\"/prepare-helper-column-configs\", name=\"preparehelpercolumnconfigs\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function prepareHelperColumnConfigs(Request $request)\n {\n $helperColumns = [];\n $newData = [];\n /** @var \\stdClass[] $data */\n $data = json_decode($request->get('columns'));\n foreach ($data as $item) {\n if (!empty($item->isOperator)) {\n $itemKey = '#' . uniqid();", " $item->key = $itemKey;\n $newData[] = $item;\n $helperColumns[$itemKey] = $item;\n } else {\n $newData[] = $item;\n }\n }", " Tool\\Session::useSession(function (AttributeBagInterface $session) use ($helperColumns) {\n $existingColumns = $session->get('helpercolumns', []);\n $helperColumns = array_merge($helperColumns, $existingColumns);\n $session->set('helpercolumns', $helperColumns);\n }, 'pimcore_gridconfig');", " return $this->adminJson(['success' => true, 'columns' => $newData]);\n }", " /**\n * @Route(\"/grid-config-apply-to-all\", name=\"gridconfigapplytoall\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridConfigApplyToAllAction(Request $request)\n {\n $objectId = $request->get('objectId');\n $object = DataObject::getById($objectId);", " if ($object->isAllowed('list')) {\n $classId = $request->get('classId');\n $searchType = $request->get('searchType');\n $user = $this->getAdminUser();\n $db = Db::get();\n $db->executeQuery('delete from gridconfig_favourites where '\n . 'ownerId = ' . $user->getId()\n . ' and classId = ' . $db->quote($classId) .\n ' and searchType = ' . $db->quote($searchType)\n . ' and objectId != ' . $objectId . ' and objectId != 0');", " return $this->adminJson(['success' => true]);\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @Route(\"/grid-mark-favourite-column-config\", name=\"gridmarkfavouritecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridMarkFavouriteColumnConfigAction(Request $request)\n {\n $objectId = $request->get('objectId');\n $object = DataObject::getById($objectId);", " if ($object->isAllowed('list')) {\n $classId = $request->get('classId');\n $gridConfigId = $request->get('gridConfigId');\n $searchType = $request->get('searchType');\n $global = $request->get('global');\n $user = $this->getAdminUser();\n $type = $request->get('type');", " $favourite = new GridConfigFavourite();\n $favourite->setOwnerId($user->getId());\n $class = DataObject\\ClassDefinition::getById($classId);\n if (!$class) {\n throw new \\Exception('class ' . $classId . ' does not exist anymore');\n }\n $favourite->setClassId($classId);\n $favourite->setSearchType($searchType);\n $favourite->setType($type);\n $specializedConfigs = false;", " try {\n if ($gridConfigId != 0) {\n $gridConfig = GridConfig::getById($gridConfigId);\n $favourite->setGridConfigId($gridConfig->getId());\n }\n $favourite->setObjectId($objectId);\n $favourite->save();", " if ($global) {\n $favourite->setObjectId(0);\n $favourite->save();\n }\n $db = Db::get();\n $count = $db->fetchOne('select * from gridconfig_favourites where '\n . 'ownerId = ' . $user->getId()\n . ' and classId = ' . $db->quote($classId).\n ' and searchType = ' . $db->quote($searchType)\n . ' and objectId != ' . $objectId . ' and objectId != 0'\n . ' and type != ' . $db->quote($type));\n $specializedConfigs = $count > 0;\n } catch (\\Exception $e) {\n $favourite->delete();\n }", " return $this->adminJson(['success' => true, 'spezializedConfigs' => $specializedConfigs]);\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param int $gridConfigId\n *\n * @return array\n */\n protected function getShareSettings($gridConfigId)\n {\n $result = [\n 'sharedUserIds' => [],\n 'sharedRoleIds' => [],\n ];", " $db = Db::get();\n $allShares = $db->fetchAllAssociative('select s.sharedWithUserId, u.type from gridconfig_shares s, users u\n where s.sharedWithUserId = u.id and s.gridConfigId = ' . $gridConfigId);", " if ($allShares) {\n foreach ($allShares as $share) {\n $type = $share['type'];\n $key = 'shared' . ucfirst($type) . 'Ids';\n $result[$key][] = $share['sharedWithUserId'];\n }\n }", " foreach ($result as $idx => $value) {\n $value = $value ? implode(',', $value) : '';\n $result[$idx] = $value;\n }", " return $result;\n }", " /**\n * @Route(\"/grid-save-column-config\", name=\"gridsavecolumnconfig\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function gridSaveColumnConfigAction(Request $request)\n {\n $objectId = $request->get('id');\n $object = DataObject::getById($objectId);", " if ($object->isAllowed('list')) {\n try {\n $classId = $request->get('class_id');\n $context = $request->get('context');", " $searchType = $request->get('searchType');", " // grid config\n $gridConfigData = $this->decodeJson($request->get('gridconfig'));\n $gridConfigData['pimcore_version'] = Version::getVersion();\n $gridConfigData['pimcore_revision'] = Version::getRevision();", " $gridConfigData['context'] = $context;", " unset($gridConfigData['settings']['isShared']);", " $metadata = $request->get('settings');\n $metadata = json_decode($metadata, true);", " $gridConfigId = $metadata['gridConfigId'];\n $gridConfig = GridConfig::getById($gridConfigId);", " if ($gridConfig && $gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin()) {\n throw new \\Exception(\"don't mess around with somebody elses configuration\");\n }", " $this->updateGridConfigShares($gridConfig, $metadata);", " if ($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin()) {\n $this->updateGridConfigFavourites($gridConfig, $metadata, $objectId);\n }", " if (!$gridConfig) {\n $gridConfig = new GridConfig();\n $gridConfig->setName(date('c'));\n $gridConfig->setClassId($classId);\n $gridConfig->setSearchType($searchType);", " $gridConfig->setOwnerId($this->getAdminUser()->getId());\n }", " if ($metadata) {\n $gridConfig->setName($metadata['gridConfigName']);\n $gridConfig->setDescription($metadata['gridConfigDescription']);\n $gridConfig->setShareGlobally($metadata['shareGlobally'] && $this->getAdminUser()->isAdmin());\n $gridConfig->setSetAsFavourite($metadata['setAsFavourite'] && $this->getAdminUser()->isAdmin());\n }", " $gridConfigData = json_encode($gridConfigData);\n $gridConfig->setConfig($gridConfigData);\n $gridConfig->save();", " $userId = $this->getAdminUser()->getId();", " $availableConfigs = $this->getMyOwnGridColumnConfigs($userId, $classId, $searchType);\n $sharedConfigs = $this->getSharedGridColumnConfigs($this->getAdminUser(), $classId, $searchType);", " $settings = $this->getShareSettings($gridConfig->getId());\n $settings['gridConfigId'] = (int)$gridConfig->getId();\n $settings['gridConfigName'] = $gridConfig->getName();\n $settings['gridConfigDescription'] = $gridConfig->getDescription();\n $settings['shareGlobally'] = $gridConfig->isShareGlobally();\n $settings['setAsFavourite'] = $gridConfig->isSetAsFavourite();\n $settings['isShared'] = $gridConfig->getOwnerId() != $this->getAdminUser()->getId() && !$this->getAdminUser()->isAdmin();", " return $this->adminJson([\n 'success' => true,\n 'settings' => $settings,\n 'availableConfigs' => $availableConfigs,\n 'sharedConfigs' => $sharedConfigs,\n ]);\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n }", " throw $this->createAccessDeniedHttpException();\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n *\n * @throws \\Exception\n */\n protected function updateGridConfigShares($gridConfig, $metadata)\n {\n $user = $this->getAdminUser();\n if (!$gridConfig || !$user->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if ($gridConfig->getOwnerId() != $user->getId() && !$user->isAdmin()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }\n $combinedShares = [];\n $sharedUserIds = $metadata['sharedUserIds'];\n $sharedRoleIds = $metadata['sharedRoleIds'];", " if ($sharedUserIds) {\n $combinedShares = explode(',', $sharedUserIds);\n }", " if ($sharedRoleIds) {\n $sharedRoleIds = explode(',', $sharedRoleIds);\n $combinedShares = array_merge($combinedShares, $sharedRoleIds);\n }", " $db = Db::get();\n $db->delete('gridconfig_shares', ['gridConfigId' => $gridConfig->getId()]);", " foreach ($combinedShares as $id) {\n $share = new GridConfigShare();\n $share->setGridConfigId($gridConfig->getId());\n $share->setSharedWithUserId((int) $id);\n $share->save();\n }\n }", " /**\n * @param GridConfig|null $gridConfig\n * @param array $metadata\n * @param int $objectId\n *\n * @throws \\Exception\n */\n protected function updateGridConfigFavourites($gridConfig, $metadata, $objectId)\n {\n $currentUser = $this->getAdminUser();", " if (!$gridConfig || $currentUser === null || !$currentUser->isAllowed('share_configurations')) {\n // nothing to do\n return;\n }", " if (!$currentUser->isAdmin() && (int) $gridConfig->getOwnerId() !== $currentUser->getId()) {\n throw new \\Exception(\"don't mess with someone elses grid config\");\n }", " $sharedUsers = [];", " if ($metadata['shareGlobally'] === false) {\n $sharedUserIds = $metadata['sharedUserIds'];", " if ($sharedUserIds) {\n $sharedUsers = explode(',', $sharedUserIds);\n }\n }", " if ($metadata['shareGlobally'] === true) {\n $users = new User\\Listing();\n $users->setCondition('id = ?', $currentUser->getId());", " foreach ($users as $user) {\n $sharedUsers[] = $user->getId();\n }\n }", " foreach ($sharedUsers as $id) {\n $global = true;\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n (int) $id,\n $gridConfig->getClassId(),\n (int) $objectId,\n $gridConfig->getSearchType()\n );", " // If the user has already a favourite for that object we check the current favourite and decide if we update\n if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());", " if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ((bool) $favouriteGridConfig->isShareGlobally() === false) {\n continue;\n }", " // Check if the user is the owner. If that is the case we do not update the favourite\n if ((int) $favouriteGridConfig->getOwnerId() === (int) $id) {\n continue;\n }\n }\n }", " // Check if the user has already a global favourite then we do not save the favourite as global\n $favourite = GridConfigFavourite::getByOwnerAndClassAndObjectId(\n (int) $id,\n $gridConfig->getClassId(),\n 0,\n $gridConfig->getSearchType()\n );", " if ($favourite instanceof GridConfigFavourite) {\n $favouriteGridConfig = GridConfig::getById($favourite->getGridConfigId());", " if ($favouriteGridConfig instanceof GridConfig) {\n // Check if the grid config was shared globally if that is *not* the case we also not update\n if ($favouriteGridConfig->isShareGlobally() === false) {\n $global = false;\n }", " // Check if the user is the owner. If that is the case we do not update the global favourite\n if ($favouriteGridConfig->getOwnerId() === (int) $id) {\n $global = false;\n }\n }\n }", " $favourite = new GridConfigFavourite();\n $favourite->setGridConfigId($gridConfig->getId());\n $favourite->setClassId($gridConfig->getClassId());\n $favourite->setObjectId($objectId);\n $favourite->setOwnerId($id);\n $favourite->setType($gridConfig->getType());\n $favourite->setSearchType($gridConfig->getSearchType());\n $favourite->save();", " if ($global === true) {\n $favourite->setObjectId(0);\n $favourite->save();\n }\n }\n }", " /**\n * @param DataObject\\ClassDefinition\\Data $field\n * @param string $gridType\n * @param string $position\n * @param bool $force\n * @param string|null $keyPrefix\n * @param DataObject\\ClassDefinition|null $class\n * @param int|null $objectId\n *\n * @return array|null\n */\n protected function getFieldGridConfig($field, $gridType, $position, $force = false, $keyPrefix = null, $class = null, $objectId = null)\n {\n $key = $keyPrefix . $field->getName();\n $config = null;\n $title = $field->getName();\n if (method_exists($field, 'getTitle')) {\n if ($field->getTitle()) {\n $title = $field->getTitle();\n }\n }", " if ($field instanceof DataObject\\ClassDefinition\\Data\\Slider) {\n $config['minValue'] = $field->getMinValue();\n $config['maxValue'] = $field->getMaxValue();\n $config['increment'] = $field->getIncrement();\n }", " if (method_exists($field, 'getWidth')) {\n $config['width'] = $field->getWidth();\n }\n if (method_exists($field, 'getHeight')) {\n $config['height'] = $field->getHeight();\n }", " $visible = false;\n if ($gridType == 'search') {\n $visible = $field->getVisibleSearch();\n } elseif ($gridType == 'grid') {\n $visible = $field->getVisibleGridView();\n } elseif ($gridType == 'all') {\n $visible = true;\n }", " if (!$field->getInvisible() && ($force || $visible)) {\n $context = ['purpose' => 'gridconfig'];\n if ($class) {\n $context['class'] = $class;\n }", " if ($objectId) {\n $object = DataObject::getById($objectId);\n $context['object'] = $object;\n }\n DataObject\\Service::enrichLayoutDefinition($field, null, $context);", " $result = [\n 'key' => $key,\n 'type' => $field->getFieldType(),\n 'label' => $title,\n 'config' => $config,\n 'layout' => $field,\n 'position' => $position,\n ];", " if ($field instanceof DataObject\\ClassDefinition\\Data\\EncryptedField) {\n $result['delegateDatatype'] = $field->getDelegateDatatype();\n }", " return $result;\n } else {\n return null;\n }\n }", " /**\n * IMPORTER\n */", " /**\n * @Route(\"/import-upload\", name=\"importupload\", methods={\"POST\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function importUploadAction(Request $request)\n {\n $data = file_get_contents($_FILES['Filedata']['tmp_name']);\n $data = Tool\\Text::convertToUTF8($data);", " $importId = $request->get('importId');\n $importId = str_replace('..', '', $importId);\n $importFile = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_' . $importId;\n File::put($importFile, $data);", " $importFileOriginal = PIMCORE_SYSTEM_TEMP_DIRECTORY . '/import_' . $importId . '_original';\n File::put($importFileOriginal, $data);", " $response = $this->adminJson([\n 'success' => true,\n ]);", " // set content-type to text/html, otherwise (when application/json is sent) chrome will complain in\n // Ext.form.Action.Submit and mark the submission as failed\n $response->headers->set('Content-Type', 'text/html');", " return $response;\n }", " private function getDataPreview($originalFile, $dialect)\n {\n $count = 0;\n $data = [];\n if (($handle = fopen($originalFile, 'r')) !== false) {\n while (($rowData = fgetcsv($handle, 0, $dialect->delimiter, $dialect->quotechar, $dialect->escapechar)) !== false) {\n $tmpData = [];", " foreach ($rowData as $key => $value) {\n $tmpData['field_' . $key] = $value;\n }", " $tmpData['rowId'] = $count + 1;\n $data[] = $tmpData;", " $count++;", " /**\n * Reached the number or rows for the preview\n */\n if ($count > 18) {\n break;\n }\n }\n fclose($handle);\n }", " return $data;\n }", " /**\n * @param Request $request\n *\n * @return string\n */\n protected function extractLanguage(Request $request)\n {\n $requestedLanguage = $request->get('language');\n if ($requestedLanguage) {\n if ($requestedLanguage != 'default') {\n $request->setLocale($requestedLanguage);\n }\n } else {\n $requestedLanguage = $request->getLocale();\n }", " return $requestedLanguage;\n }", " /**\n * @param string $fileHandle\n *\n * @return string\n */\n protected function getCsvFile($fileHandle)\n {\n return $fileHandle . '.csv';\n }", " /**\n * @Route(\"/get-export-jobs\", name=\"getexportjobs\", methods={\"POST\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n * @param EventDispatcherInterface $eventDispatcher\n *\n * @return JsonResponse\n */\n public function getExportJobsAction(Request $request, GridHelperService $gridHelperService, EventDispatcherInterface $eventDispatcher)\n {\n $requestedLanguage = $this->extractLanguage($request);\n $allParams = array_merge($request->request->all(), $request->query->all());", " $list = $gridHelperService->prepareListingForGrid($allParams, $requestedLanguage, $this->getAdminUser());", " $beforeListPrepareEvent = new GenericEvent($this, [\n 'list' => $list,\n 'context' => $allParams,\n ]);\n $eventDispatcher->dispatch($beforeListPrepareEvent, AdminEvents::OBJECT_LIST_BEFORE_EXPORT_PREPARE);", " $list = $beforeListPrepareEvent->getArgument('list');", " $ids = $list->loadIdList();", " $jobs = array_chunk($ids, 20);", " $fileHandle = uniqid('export-');", " $storage = Storage::get('temp');\n $storage->write($this->getCsvFile($fileHandle), '');", " return $this->adminJson(['success' => true, 'jobs' => $jobs, 'fileHandle' => $fileHandle]);\n }", " /**\n * @Route(\"/do-export\", name=\"doexport\", methods={\"POST\"})\n *\n * @param Request $request\n * @param LocaleServiceInterface $localeService\n * @param EventDispatcherInterface $eventDispatcher\n *\n * @return JsonResponse\n *\n * @throws \\Exception\n */\n public function doExportAction(Request $request, LocaleServiceInterface $localeService, EventDispatcherInterface $eventDispatcher)\n {\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $ids = $request->get('ids');\n $settings = $request->get('settings');\n $settings = json_decode($settings, true);\n $delimiter = $settings['delimiter'] ?? ';';", " $allParams = array_merge($request->request->all(), $request->query->all());", " $enableInheritance = $settings['enableInheritance'] ?? null;\n DataObject\\Concrete::setGetInheritedValues($enableInheritance);", " $class = DataObject\\ClassDefinition::getById($request->get('classId'));", " if (!$class) {\n throw new \\Exception('No class definition found');\n }", " $className = $class->getName();\n $listClass = '\\\\Pimcore\\\\Model\\\\DataObject\\\\' . ucfirst($className) . '\\\\Listing';", " /** @var \\Pimcore\\Model\\DataObject\\Listing $list */\n $list = new $listClass();", " $quotedIds = [];\n foreach ($ids as $id) {\n $quotedIds[] = $list->quote($id);\n }", " $list->setObjectTypes(DataObject::$types);\n $list->setCondition('o_id IN (' . implode(',', $quotedIds) . ')');\n $list->setOrderKey(' FIELD(o_id, ' . implode(',', $quotedIds) . ')', false);", " $beforeListExportEvent = new GenericEvent($this, [\n 'list' => $list,\n 'context' => $allParams,\n ]);\n $eventDispatcher->dispatch($beforeListExportEvent, AdminEvents::OBJECT_LIST_BEFORE_EXPORT);", " $list = $beforeListExportEvent->getArgument('list');", " $fields = $request->get('fields');", " $addTitles = (bool) $request->get('initial');", " $requestedLanguage = $this->extractLanguage($request);", " $contextFromRequest = $request->get('context');\n if ($contextFromRequest) {\n $contextFromRequest = json_decode($contextFromRequest, true);\n }", " $context = [\n 'source' => 'pimcore-export',\n ];", " if (is_array($contextFromRequest)) {\n $context = array_merge($context, $contextFromRequest);\n }", " $csv = DataObject\\Service::getCsvData($requestedLanguage, $localeService, $list, $fields, $addTitles, $context);", " $storage = Storage::get('temp');\n $csvFile = $this->getCsvFile($fileHandle);", " $fileStream = $storage->readStream($csvFile);", " $temp = tmpfile();\n stream_copy_to_stream($fileStream, $temp, null, 0);", " $firstLine = true;\n $lineCount = count($csv);", " if (!$addTitles && $lineCount > 0) {\n fwrite($temp, \"\\r\\n\");\n }", " for ($i = 0; $i < $lineCount; $i++) {\n $line = $csv[$i];\n if ($addTitles && $firstLine) {\n $firstLine = false;\n $line = implode($delimiter, $line);\n fwrite($temp, $line);\n } else {\n fwrite($temp, implode($delimiter, array_map([$this, 'encodeFunc'], $line)));\n }\n if ($i < $lineCount - 1) {\n fwrite($temp, \"\\r\\n\");\n }\n }\n $storage->writeStream($csvFile, $temp);", " return $this->adminJson(['success' => true]);\n }", " public function encodeFunc($value)\n {\n $value = str_replace('\"', '\"\"', $value);\n //force wrap value in quotes and return\n return '\"' . $value . '\"';\n }", " /**\n * @Route(\"/download-csv-file\", name=\"downloadcsvfile\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return Response\n */\n public function downloadCsvFileAction(Request $request)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n $csvData = $storage->read($csvFile);\n $response = new Response($csvData);\n $response->headers->set('Content-Type', 'application/csv');\n $disposition = HeaderUtils::makeDisposition(\n HeaderUtils::DISPOSITION_ATTACHMENT,\n 'export.csv'\n );", " $response->headers->set('Content-Disposition', $disposition);\n $storage->delete($csvFile);", " return $response;\n } catch (FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('CSV file not found');\n }\n }", " /**\n * @Route(\"/download-xlsx-file\", name=\"downloadxlsxfile\", methods={\"GET\"})\n *\n * @param Request $request\n * @param GridHelperService $gridHelperService\n *\n * @return BinaryFileResponse\n */\n public function downloadXlsxFileAction(Request $request, GridHelperService $gridHelperService)\n {\n $storage = Storage::get('temp');\n $fileHandle = \\Pimcore\\File::getValidFilename($request->get('fileHandle'));\n $csvFile = $this->getCsvFile($fileHandle);", " try {\n return $gridHelperService->createXlsxExportFile($storage, $fileHandle, $csvFile);\n } catch (\\Exception | FilesystemException | UnableToReadFile $exception) {\n // handle the error\n throw $this->createNotFoundException('XLSX file not found');\n }\n }", " /**\n * Flattens object data to an array with key=>value where\n * value is simply a string representation of the value (for objects, hrefs and assets the full path is used)\n *\n * @param DataObject\\Concrete $object\n *\n * @return array\n */\n protected function csvObjectData($object)\n {\n $o = [];\n foreach ($object->getClass()->getFieldDefinitions() as $key => $value) {\n $o[$key] = $value->getForCsvExport($object);\n }", " $o['id (system)'] = $object->getId();\n $o['key (system)'] = $object->getKey();\n $o['fullpath (system)'] = $object->getRealFullPath();\n $o['published (system)'] = $object->isPublished();\n $o['type (system)'] = $object->getType();", " return $o;\n }", " /**\n * @Route(\"/get-batch-jobs\", name=\"getbatchjobs\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getBatchJobsAction(Request $request, GridHelperService $gridHelperService)\n {\n if ($request->get('language')) {\n $request->setLocale($request->get('language'));\n }", " $allParams = array_merge($request->request->all(), $request->query->all());\n $list = $gridHelperService->prepareListingForGrid($allParams, $request->getLocale(), $this->getAdminUser());", " $jobs = $list->loadIdList();", " return $this->adminJson(['success' => true, 'jobs' => $jobs]);\n }", " /**\n * @Route(\"/batch\", name=\"batch\", methods={\"PUT\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function batchAction(Request $request)\n {\n $success = true;", " try {\n if ($request->get('data')) {\n $params = $this->decodeJson($request->get('data'), true);\n $object = DataObject\\Concrete::getById($params['job']);", " if ($object) {\n $name = $params['name'];", " if (!$object->isAllowed('save') || ($name === 'published' && !$object->isAllowed('publish'))) {\n throw new \\Exception(\"Permission denied. You don't have the rights to save this object.\");\n }", " $append = $params['append'] ?? false;\n $remove = $params['remove'] ?? false;", " $className = $object->getClassName();\n $class = DataObject\\ClassDefinition::getByName($className);\n $value = $params['value'];\n if ($params['valueType'] == 'object') {\n $value = $this->decodeJson($value);\n }", " $parts = explode('~', $name);", " if (substr($name, 0, 1) == '~') {\n $type = $parts[1];\n $field = $parts[2];\n $keyId = $parts[3];", " if ($type == 'classificationstore') {\n $requestedLanguage = $params['language'];\n if ($requestedLanguage) {\n if ($requestedLanguage != 'default') {\n $request->setLocale($requestedLanguage);\n }\n } else {\n $requestedLanguage = $request->getLocale();\n }", " $groupKeyId = explode('-', $keyId);\n $groupId = (int) $groupKeyId[0];\n $keyId = (int) $groupKeyId[1];", " $getter = 'get' . ucfirst($field);\n if (method_exists($object, $getter)) {\n /** @var DataObject\\ClassDefinition\\Data\\Classificationstore $csFieldDefinition */\n $csFieldDefinition = $object->getClass()->getFieldDefinition($field);\n $csLanguage = $requestedLanguage;\n if (!$csFieldDefinition->isLocalized()) {\n $csLanguage = 'default';\n }", " /** @var DataObject\\ClassDefinition\\Data\\Classificationstore $fd */\n $fd = $class->getFieldDefinition($field);\n $keyConfig = $fd->getKeyConfiguration($keyId);\n $dataDefinition = DataObject\\Classificationstore\\Service::getFieldDefinitionFromKeyConfig($keyConfig);", " /** @var DataObject\\Classificationstore $classificationStoreData */\n $classificationStoreData = $object->$getter();\n if ($append) {\n $oldValue = $classificationStoreData->getLocalizedKeyValue($groupId, $keyId);\n $value = $dataDefinition->appendData($oldValue, $value);\n }\n if ($remove) {\n $oldValue = $classificationStoreData->getLocalizedKeyValue($groupId, $keyId);\n $value = $dataDefinition->removeData($oldValue, $value);\n }\n $classificationStoreData->setLocalizedKeyValue(\n $groupId,\n $keyId,\n $dataDefinition->getDataFromEditmode($value),\n $csLanguage\n );\n }\n }\n } elseif (count($parts) > 1) {\n // check for bricks\n $brickType = $parts[0];\n $brickKey = $parts[1];\n $brickField = DataObject\\Service::getFieldForBrickType($object->getClass(), $brickType);", " $fieldGetter = 'get' . ucfirst($brickField);\n $brickGetter = 'get' . ucfirst($brickType);\n $valueSetter = 'set' . ucfirst($brickKey);", " $brick = $object->$fieldGetter()->$brickGetter();\n if (empty($brick)) {\n $classname = '\\\\Pimcore\\\\Model\\\\DataObject\\\\Objectbrick\\\\Data\\\\' . ucfirst($brickType);\n $brickSetter = 'set' . ucfirst($brickType);\n $brick = new $classname($object);\n $object->$fieldGetter()->$brickSetter($brick);\n }", " $brickClass = DataObject\\Objectbrick\\Definition::getByKey($brickType);\n $field = $brickClass->getFieldDefinition($brickKey);", " $newData = $field->getDataFromEditmode($value, $object);", " if ($append) {\n $valueGetter = 'get' . ucfirst($brickKey);\n $existingData = $brick->$valueGetter();\n $newData = $field->appendData($existingData, $newData);\n }\n if ($remove) {\n $valueGetter = 'get' . ucfirst($brickKey);\n $existingData = $brick->$valueGetter();\n $newData = $field->removeData($existingData, $newData);\n }\n $brick->$valueSetter($newData);\n } else {\n // everything else\n $field = $class->getFieldDefinition($name);\n if ($field) {\n $newData = $field->getDataFromEditmode($value, $object);", " if ($append) {\n $existingData = $object->{'get' . $name}();\n $newData = $field->appendData($existingData, $newData);\n }\n if ($remove) {\n $existingData = $object->{'get' . $name}();\n $newData = $field->removeData($existingData, $newData);\n }\n $object->setValue($name, $newData);\n } else {\n // check if it is a localized field\n if ($params['language']) {\n $localizedField = $class->getFieldDefinition('localizedfields');\n if ($localizedField instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $field = $localizedField->getFieldDefinition($name);\n if ($field) {\n $getter = 'get' . $name;\n $setter = 'set' . $name;\n $newData = $field->getDataFromEditmode($value, $object);\n if ($append) {\n $existingData = $object->$getter($params['language']);\n $newData = $field->appendData($existingData, $newData);\n }\n if ($remove) {\n $existingData = $object->$getter($request->get('language'));\n $newData = $field->removeData($existingData, $newData);\n }", " $object->$setter($newData, $params['language']);\n }\n }\n }", " // seems to be a system field, this is actually only possible for the \"published\" field yet\n if ($name == 'published') {\n if ($value === 'false' || empty($value)) {\n $object->setPublished(false);\n } else {\n $object->setPublished(true);\n }\n }\n }\n }", " try {\n // don't check for mandatory fields here\n $object->setOmitMandatoryCheck(!$object->isPublished());\n $object->setUserModification($this->getAdminUser()->getId());\n $object->save();\n $success = true;\n } catch (\\Exception $e) {\n return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }\n } else {\n Logger::debug('DataObjectController::batchAction => There is no object left to update.');", " return $this->adminJson(['success' => false, 'message' => 'DataObjectController::batchAction => There is no object left to update.']);\n }\n }\n } catch (\\Exception $e) {\n Logger::err((string) $e);", " return $this->adminJson(['success' => false, 'message' => $e->getMessage()]);\n }", " return $this->adminJson(['success' => $success]);\n }", " /**\n * @Route(\"/get-available-visible-vields\", name=\"getavailablevisiblefields\", methods={\"GET\"})\n *\n * @param Request $request\n *\n * @return JsonResponse\n */\n public function getAvailableVisibleFieldsAction(Request $request)\n {\n $class = null;\n $fields = null;", " $classList = [];\n $classNameList = [];", " if ($request->get('classes')) {\n $classNameList = $request->get('classes');\n $classNameList = explode(',', $classNameList);\n foreach ($classNameList as $className) {\n $class = DataObject\\ClassDefinition::getByName($className);\n if ($class) {\n $classList[] = $class;\n }\n }\n }", " if (!$classList) {\n return $this->adminJson(['availableFields' => []]);\n }\n $availableFields = [];\n foreach (self::SYSTEM_COLUMNS as $field) {\n $availableFields[] = [\n 'key' => $field,\n 'value' => $field,\n ];\n }", " /** @var DataObject\\ClassDefinition\\Data[] $commonFields */\n $commonFields = [];", " $firstOne = true;\n foreach ($classNameList as $className) {\n $class = DataObject\\ClassDefinition::getByName($className);\n if ($class) {\n $fds = $class->getFieldDefinitions();", " $additionalFieldNames = array_keys($fds);\n $localizedFields = $class->getFieldDefinition('localizedfields');\n if ($localizedFields instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $lfNames = array_keys($localizedFields->getFieldDefinitions());\n $additionalFieldNames = array_merge($additionalFieldNames, $lfNames);\n }", " foreach ($commonFields as $commonFieldKey => $commonFieldDefinition) {\n if (!in_array($commonFieldKey, $additionalFieldNames)) {\n unset($commonFields[$commonFieldKey]);\n }\n }", " $this->processAvailableFieldDefinitions($fds, $firstOne, $commonFields);", " $firstOne = false;\n }\n }", " $commonFieldKeys = array_keys($commonFields);\n foreach ($commonFieldKeys as $field) {\n $availableFields[] = [\n 'key' => $field,\n 'value' => $field,\n ];\n }", " return $this->adminJson(['availableFields' => $availableFields]);\n }", " /**\n * @param DataObject\\ClassDefinition\\Data[] $fds\n * @param bool $firstOne\n * @param DataObject\\ClassDefinition\\Data[] $commonFields\n */\n protected function processAvailableFieldDefinitions($fds, &$firstOne, &$commonFields)\n {\n foreach ($fds as $fd) {\n if ($fd instanceof DataObject\\ClassDefinition\\Data\\Fieldcollections || $fd instanceof DataObject\\ClassDefinition\\Data\\Objectbricks\n || $fd instanceof DataObject\\ClassDefinition\\Data\\Block) {\n continue;\n }", " if ($fd instanceof DataObject\\ClassDefinition\\Data\\Localizedfields) {\n $lfDefs = $fd->getFieldDefinitions();\n $this->processAvailableFieldDefinitions($lfDefs, $firstOne, $commonFields);\n } elseif ($firstOne || (isset($commonFields[$fd->getName()]) && $commonFields[$fd->getName()]->getFieldtype() == $fd->getFieldtype())) {\n $commonFields[$fd->getName()] = $fd;\n }\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @category Pimcore\n * @package Object\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "\npimcore.registerNS(\"pimcore.object.gridcolumn.operator.anygetter\");", "pimcore.object.gridcolumn.operator.anygetter = Class.create(pimcore.object.gridcolumn.Abstract, {\n operatorGroup: \"extractor\",\n type: \"operator\",\n class: \"AnyGetter\",\n iconCls: \"pimcore_icon_operator_anygetter\",\n defaultText: \"Any Getter\",\n group: \"getter\",", "\n getConfigTreeNode: function (configAttributes) {\n if (configAttributes) {\n var nodeLabel = this.getNodeLabel(configAttributes);\n var node = {\n draggable: true,\n iconCls: this.iconCls,\n text: nodeLabel,\n configAttributes: configAttributes,\n isTarget: true,\n expanded: true,\n leaf: false,\n expandable: false\n };\n } else {", " //For building up operator list\n var configAttributes = {type: this.type, class: this.class, label: this.getDefaultText()};", " var node = {\n draggable: true,\n iconCls: this.iconCls,\n text: this.getDefaultText(),\n configAttributes: configAttributes,\n isTarget: true,\n leaf: true\n };\n }\n node.isOperator = true;\n return node;\n },", "\n getCopyNode: function (source) {\n var copy = source.createNode({\n iconCls: this.iconCls,\n text: source.data.cssClass,\n isTarget: true,\n leaf: false,\n expanded: true,\n isOperator: true,\n configAttributes: {\n label: source.data.configAttributes.label,\n type: this.type,\n class: this.class\n }\n });\n return copy;\n },", "\n getConfigDialog: function (node, params) {\n this.node = node;", " this.textfield = new Ext.form.TextField({\n fieldLabel: t('label'),\n length: 255,\n width: 200,", " value: this.node.data.configAttributes.label", " });", " this.attributeField = new Ext.form.TextField({\n fieldLabel: t('attribute'),\n length: 255,\n width: 200,", " value: this.node.data.configAttributes.attribute", " });", " this.param1Field = new Ext.form.TextField({\n fieldLabel: t('parameter'),\n length: 255,\n width: 200,", " value: this.node.data.configAttributes.param1\n });", "\n this.returnLastResultField = new Ext.form.Checkbox({\n fieldLabel: t('return_last_result'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.returnLastResult\n });", "\n this.isArrayField = new Ext.form.Checkbox({\n fieldLabel: t('is_array'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.isArrayType\n });", " this.forwardAttributeField = new Ext.form.TextField({\n fieldLabel: t('forward_attribute'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.forwardAttribute\n });", " this.forwardParam1Field = new Ext.form.TextField({\n fieldLabel: t('forward_parameter'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.forwardParam1\n });", "\n this.configPanel = new Ext.Panel({\n layout: \"form\",\n bodyStyle: \"padding: 10px;\",\n items: [this.textfield, this.attributeField, this.param1Field, this.isArrayField, this.returnLastResultField, this.forwardAttributeField, this.forwardParam1Field],\n buttons: [{\n text: t(\"apply\"),\n iconCls: \"pimcore_icon_apply\",\n handler: function () {\n this.commitData(params);\n }.bind(this)\n }]\n });", " this.window = new Ext.Window({\n width: 400,\n height: 450,\n modal: true,\n title: t('settings'),\n layout: \"fit\",\n items: [this.configPanel]\n });", " this.window.show();", " return this.window;\n },", " commitData: function (params) {\n this.node.set('isOperator', true);\n this.node.data.configAttributes.label = this.textfield.getValue();\n this.node.data.configAttributes.attribute = this.attributeField.getValue();\n this.node.data.configAttributes.param1 = this.param1Field.getValue();\n this.node.data.configAttributes.isArrayType = this.isArrayField.getValue();\n this.node.data.configAttributes.forwardAttribute = this.forwardAttributeField.getValue();\n this.node.data.configAttributes.forwardParam1 = this.forwardParam1Field.getValue();\n this.node.data.configAttributes.returnLastResult = this.returnLastResultField.getValue();", " var nodeLabel = this.getNodeLabel(this.node.data.configAttributes);\n this.node.set('text', nodeLabel);\n this.window.close();", " if (params && params.callback) {\n params.callback();\n }\n },", " getNodeLabel: function (configAttributes) {\n var nodeLabel = configAttributes.label ? configAttributes.label : this.getDefaultText();\n if (configAttributes.attribute) {\n var attr = configAttributes.attribute;\n if (configAttributes.param1) {\n attr += \" \" + configAttributes.param1;\n }", " nodeLabel += '<span class=\"pimcore_gridnode_hint\"> (' + attr + ')</span>';", " }", " return nodeLabel;\n }\n }\n);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @category Pimcore\n * @package Object\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "\npimcore.registerNS(\"pimcore.object.gridcolumn.operator.anygetter\");", "pimcore.object.gridcolumn.operator.anygetter = Class.create(pimcore.object.gridcolumn.Abstract, {\n operatorGroup: \"extractor\",\n type: \"operator\",\n class: \"AnyGetter\",\n iconCls: \"pimcore_icon_operator_anygetter\",\n defaultText: \"Any Getter\",\n group: \"getter\",", "\n getConfigTreeNode: function (configAttributes) {\n if (configAttributes) {\n var nodeLabel = this.getNodeLabel(configAttributes);\n var node = {\n draggable: true,\n iconCls: this.iconCls,\n text: nodeLabel,\n configAttributes: configAttributes,\n isTarget: true,\n expanded: true,\n leaf: false,\n expandable: false\n };\n } else {", " //For building up operator list\n var configAttributes = {type: this.type, class: this.class, label: this.getDefaultText()};", " var node = {\n draggable: true,\n iconCls: this.iconCls,\n text: this.getDefaultText(),\n configAttributes: configAttributes,\n isTarget: true,\n leaf: true\n };\n }\n node.isOperator = true;\n return node;\n },", "\n getCopyNode: function (source) {\n var copy = source.createNode({\n iconCls: this.iconCls,\n text: source.data.cssClass,\n isTarget: true,\n leaf: false,\n expanded: true,\n isOperator: true,\n configAttributes: {\n label: source.data.configAttributes.label,\n type: this.type,\n class: this.class\n }\n });\n return copy;\n },", "\n getConfigDialog: function (node, params) {\n this.node = node;", " this.textfield = new Ext.form.TextField({\n fieldLabel: t('label'),\n length: 255,\n width: 200,", " value: this.node.data.configAttributes.label,\n listeners: {'change': pimcore.helpers.htmlEncodeTextField }", " });", " this.attributeField = new Ext.form.TextField({\n fieldLabel: t('attribute'),\n length: 255,\n width: 200,", " value: this.node.data.configAttributes.attribute,\n listeners: {'change': pimcore.helpers.htmlEncodeTextField }", " });", " this.param1Field = new Ext.form.TextField({\n fieldLabel: t('parameter'),\n length: 255,\n width: 200,", " value: this.node.data.configAttributes.param1,\n listeners: {'change': pimcore.helpers.htmlEncodeTextField }\n });", "\n this.returnLastResultField = new Ext.form.Checkbox({\n fieldLabel: t('return_last_result'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.returnLastResult\n });", "\n this.isArrayField = new Ext.form.Checkbox({\n fieldLabel: t('is_array'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.isArrayType\n });", " this.forwardAttributeField = new Ext.form.TextField({\n fieldLabel: t('forward_attribute'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.forwardAttribute\n });", " this.forwardParam1Field = new Ext.form.TextField({\n fieldLabel: t('forward_parameter'),\n length: 255,\n width: 200,\n value: this.node.data.configAttributes.forwardParam1\n });", "\n this.configPanel = new Ext.Panel({\n layout: \"form\",\n bodyStyle: \"padding: 10px;\",\n items: [this.textfield, this.attributeField, this.param1Field, this.isArrayField, this.returnLastResultField, this.forwardAttributeField, this.forwardParam1Field],\n buttons: [{\n text: t(\"apply\"),\n iconCls: \"pimcore_icon_apply\",\n handler: function () {\n this.commitData(params);\n }.bind(this)\n }]\n });", " this.window = new Ext.Window({\n width: 400,\n height: 450,\n modal: true,\n title: t('settings'),\n layout: \"fit\",\n items: [this.configPanel]\n });", " this.window.show();", " return this.window;\n },", " commitData: function (params) {\n this.node.set('isOperator', true);\n this.node.data.configAttributes.label = this.textfield.getValue();\n this.node.data.configAttributes.attribute = this.attributeField.getValue();\n this.node.data.configAttributes.param1 = this.param1Field.getValue();\n this.node.data.configAttributes.isArrayType = this.isArrayField.getValue();\n this.node.data.configAttributes.forwardAttribute = this.forwardAttributeField.getValue();\n this.node.data.configAttributes.forwardParam1 = this.forwardParam1Field.getValue();\n this.node.data.configAttributes.returnLastResult = this.returnLastResultField.getValue();", " var nodeLabel = this.getNodeLabel(this.node.data.configAttributes);\n this.node.set('text', nodeLabel);\n this.window.close();", " if (params && params.callback) {\n params.callback();\n }\n },", " getNodeLabel: function (configAttributes) {\n var nodeLabel = configAttributes.label ? configAttributes.label : this.getDefaultText();\n if (configAttributes.attribute) {\n var attr = configAttributes.attribute;\n if (configAttributes.param1) {\n attr += \" \" + configAttributes.param1;\n }", " nodeLabel += '<span class=\"pimcore_gridnode_hint\"> (' + Ext.util.Format.htmlEncode(attr) + ')</span>';", " }", " return nodeLabel;\n }\n }\n);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "pimcore.registerNS(\"pimcore.settings.metadata.predefined\");\npimcore.settings.metadata.predefined = Class.create({", " initialize: function () {\n this.getTabPanel();\n },", " activate: function () {\n var tabPanel = Ext.getCmp(\"pimcore_panel_tabs\");\n tabPanel.setActiveItem(\"predefined_metadata\");\n },", " getTabPanel: function () {", " if (!this.panel) {\n this.panel = new Ext.Panel({\n id: \"predefined_metadata\",\n title: t(\"predefined_metadata_definitions\"),\n iconCls: \"pimcore_icon_metadata\",\n border: false,\n layout: \"fit\",\n closable:true,\n items: [this.getRowEditor()]\n });", " var tabPanel = Ext.getCmp(\"pimcore_panel_tabs\");\n tabPanel.add(this.panel);\n tabPanel.setActiveItem(\"predefined_metadata\");", "\n this.panel.on(\"destroy\", function () {\n pimcore.globalmanager.remove(\"predefined_metadata\");\n }.bind(this));", " pimcore.layout.refresh();\n }", " return this.panel;\n },", " getRowEditor: function () {\n var url = Routing.generate('pimcore_admin_settings_metadata');", " this.store = pimcore.helpers.grid.buildDefaultStore(\n url,\n [\n 'id',\n {\n name: 'name',\n allowBlank: false,\n convert: function (v, r) {\n return v.replace(/[~]/g, \"---\");\n }\n },\n 'description','type',\n {name: 'data',\n convert: function (v, r) {\n let dataType = r.data.type;\n if (typeof pimcore.asset.metadata.tags[dataType].prototype.convertPredefinedGridData === \"function\") {\n v = pimcore.asset.metadata.tags[dataType].prototype.convertPredefinedGridData(v, r);\n }\n return v;\n }\n },'config', 'targetSubtype', 'language', 'creationDate' ,'modificationDate'\n ], null, {\n remoteSort: false,\n remoteFilter: false\n }\n );", " this.store.getProxy().getReader().setMessageProperty('message');\n this.store.getProxy().on('exception', function (proxy, response, operation) {\n pimcore.helpers.showNotification(t(\"error\"), t(operation.getError()), \"error\");\n this.store.load();\n }.bind(this));", " this.store.addListener('exception', function(proxy, mode, action, options, response) {\n Ext.Msg.show({\n title: t(\"error\"),\n msg: t(response.raw.message),\n buttons: Ext.Msg.OK,\n animEl: 'elId',\n icon: Ext.MessageBox.ERROR\n });\n });", " this.filterField = new Ext.form.TextField({\n xtype: \"textfield\",\n width: 200,\n style: \"margin: 0 10px 0 0;\",\n enableKeyEvents: true,\n listeners: {\n \"keydown\" : function (field, key) {\n if (key.getKey() == key.ENTER) {\n var input = field;\n var proxy = this.store.getProxy();\n proxy.extraParams.filter = input.getValue();\n this.store.load();\n }\n }.bind(this)\n }\n });", "\n var languagestore = [[\"\",t(\"none\")]];\n for (let i=0; i<pimcore.settings.websiteLanguages.length; i++) {\n languagestore.push([pimcore.settings.websiteLanguages[i],pimcore.settings.websiteLanguages[i]]);\n }", " var supportedTypes = pimcore.helpers.getAssetMetadataDataTypes(\"predefined\");\n var typeStore = [];", " for (let i = 0; i < supportedTypes.length; i++) {\n let type = supportedTypes[i];\n typeStore.push([type, t(type)]);\n }", " var metadataColumns = [\n {\n text: t(\"type\"),\n dataIndex: 'type',\n editable: false,\n width: 40,\n renderer: this.getTypeRenderer.bind(this),\n sortable: true\n },\n {text: t(\"name\"), width: 200, sortable: true, dataIndex: 'name',", " getEditor: function() { return new Ext.form.TextField({}); }", " },\n {text: t(\"group\"), width: 200, sortable: true, dataIndex: 'group',\n getEditor: function() { return new Ext.form.TextField({}); }\n },\n {text: t(\"description\"), sortable: true, dataIndex: 'description',\n getEditor: function() { return new Ext.form.TextArea({}); },\n renderer: function (value, metaData, record, rowIndex, colIndex, store) {\n if (empty(value)) {\n return \"\";\n }\n return nl2br(Ext.util.Format.htmlEncode(value));\n }\n },\n {text: t(\"type\"), width: 90, sortable: true,\n dataIndex: 'type',\n getEditor: function() {\n return new Ext.form.ComboBox({\n editable: false,\n store: typeStore", " })\n }\n },\n {text: t(\"value\"),\n flex: 510,\n sortable: true,\n dataIndex: 'data',\n editable: true,\n getEditor: this.getCellEditor.bind(this),\n renderer: this.getCellRenderer.bind(this)\n },\n {text: t(\"configuration\"),\n width: 100,\n sortable: false,\n dataIndex: 'config',\n getEditor: function() { return new Ext.form.TextField({}); }\n },\n {\n text: t('language'),\n sortable: true,\n dataIndex: \"language\",\n getEditor: function() {\n return new Ext.form.ComboBox({\n name: \"language\",\n store: languagestore,\n editable: false,\n triggerAction: 'all',\n mode: \"local\"\n });\n },\n width: 70\n },\n {\n text: t(\"target_subtype\"), width: 80, sortable: true, dataIndex: 'targetSubtype',\n getEditor: function() {\n return new Ext.form.ComboBox({\n editable: true,\n store: [\"image\", \"text\", \"audio\", \"video\", \"document\", \"archive\", \"unknown\"]\n });\n }\n },\n {\n xtype: 'actioncolumn',\n menuText: t('delete'),\n width: 40,\n items: [{\n getClass: function(v, meta, rec) {\n var klass = \"pimcore_action_column \";\n if(rec.data.writeable) {\n klass += \"pimcore_icon_minus\";\n }\n return klass;\n },\n tooltip: t('delete'),\n handler: function (grid, rowIndex) {\n let data = grid.getStore().getAt(rowIndex);\n pimcore.helpers.deleteConfirm(t('predefined_metadata'),\n Ext.util.Format.htmlEncode(data.data.name),\n function () {\n grid.getStore().removeAt(rowIndex);\n }.bind(this));\n }.bind(this)\n }]\n },\n {text: t(\"creationDate\"), sortable: true, dataIndex: 'creationDate', editable: false,\n hidden: true,\n renderer: function(d) {\n if (d !== undefined) {\n var date = new Date(d * 1000);\n return date.format(\"Y-m-d H:i:s\");\n }\n return \"\";\n }\n },\n {text: t(\"modificationDate\"), sortable: true, dataIndex: 'modificationDate', editable: false,\n hidden: true,\n renderer: function(d) {\n if (d !== undefined) {\n var date = new Date(d * 1000);\n return date.format(\"Y-m-d H:i:s\");\n }\n return \"\";\n }\n }\n ];", " this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {\n clicksToEdit: 1,\n listeners: {\n beforeedit: function(editor, context, eOpts) {\n //need to clear cached editors of cell-editing editor in order to\n //enable different editors per row\n editor.editors.each(function (e) {\n try {\n // complete edit, so the value is stored when hopping around with TAB\n e.completeEdit();\n Ext.destroy(e);\n } catch (exception) {\n // garbage collector was faster\n // already destroyed\n }\n });", " editor.editors.clear();\n },\n validateedit: function (editor, context, eOpts) {\n if (!context.record.data.writeable) {\n editor.cancelEdit();\n pimcore.helpers.showNotification(t(\"info\"), t(\"config_not_writeable\"), \"info\");\n return false;\n }\n }\n }\n });", " this.grid = Ext.create('Ext.grid.Panel', {\n frame: false,\n autoScroll: true,\n store: this.store,\n columnLines: true,\n stripeRows: true,\n bodyCls: \"pimcore_editable_grid\",\n trackMouseOver: true,\n columns: {\n items: metadataColumns,\n defaults: {\n renderer: Ext.util.Format.htmlEncode\n },\n },\n clicksToEdit: 1,\n selModel: Ext.create('Ext.selection.CellModel', {}),\n bbar: this.pagingtoolbar,\n autoExpandColumn: \"value_col\",\n plugins: [\n this.cellEditing\n ],", " viewConfig: {\n listeners: {\n rowupdated: this.updateRows.bind(this, \"rowupdated\"),\n refresh: this.updateRows.bind(this, \"refresh\")\n },\n forceFit: true,\n getRowClass: function (record, rowIndex) {\n return record.data.writeable ? '' : 'pimcore_grid_row_disabled';\n }\n },\n tbar: {\n cls: 'pimcore_main_toolbar',\n items: [\n {\n text: t('add'),\n handler: this.onAdd.bind(this),\n iconCls: \"pimcore_icon_add\",\n disabled: !pimcore.settings['predefined-asset-metadata-writeable']\n },\"->\",{\n text: t(\"filter\") + \"/\" + t(\"search\"),\n xtype: \"tbtext\",\n style: \"margin: 0 10px 0 0;\"\n },\n this.filterField\n ]\n }\n });", " this.grid.on(\"viewready\", this.updateRows.bind(this));\n this.store.on(\"update\", this.updateRows.bind(this));", " return this.grid;\n },", " getTypeRenderer: function (value, metaData, record, rowIndex, colIndex, store) {", " if (value == \"input\") {\n value = \"text\";\n }\n return '<div class=\"pimcore_icon_' + value + '\" recordid=' + record.id + '>&nbsp;</div>';\n },", " getCellRenderer: function (value, metaData, record, rowIndex, colIndex, store) {\n var data = store.getAt(rowIndex).data;\n var type = data.type;\n return pimcore.asset.metadata.tags[type].prototype.getGridCellRenderer(value, metaData, record, rowIndex, colIndex, store);\n },", " onAdd: function (btn, ev) {\n var model = this.grid.store.getModel();\n var newEntry = new model({\n name: t('new_definition'),\n key: \"new_key\",\n subtype: \"image\",\n type: \"input\"\n });", " this.grid.store.insert(0, newEntry);\n },", " updateRows: function (event) {\n var rows = Ext.get(this.grid.getEl().dom).query(\".x-grid-row\");", " for (let i = 0; i < rows.length; i++) {", " try {\n var list = Ext.get(rows[i]).query(\".x-grid-cell-first div div\");\n var firstItem = list[0];\n if (!firstItem) {\n continue;\n }\n var recordId = firstItem.getAttribute(\"recordid\");\n var data = this.grid.getStore().getById(recordId);\n if (!data) {\n continue;\n }", " data = data.data;", " if(in_array(data.name, this.disallowedKeys)) {\n Ext.get(rows[i]).addCls(\"pimcore_properties_hidden_row\");\n }", " pimcore.asset.metadata.tags[data.type].prototype.updatePredefinedGridRow(this.grid, rows[i], data);\n }\n catch (e) {\n console.log(e);\n }\n }\n },", " getCellEditor: function (record) {\n var data = record.data;\n var type = data.type;\n var editor = pimcore.asset.metadata.tags[type].prototype.getGridCellEditor(\"predefined\", record);\n return editor;\n }\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "pimcore.registerNS(\"pimcore.settings.metadata.predefined\");\npimcore.settings.metadata.predefined = Class.create({", " initialize: function () {\n this.getTabPanel();\n },", " activate: function () {\n var tabPanel = Ext.getCmp(\"pimcore_panel_tabs\");\n tabPanel.setActiveItem(\"predefined_metadata\");\n },", " getTabPanel: function () {", " if (!this.panel) {\n this.panel = new Ext.Panel({\n id: \"predefined_metadata\",\n title: t(\"predefined_metadata_definitions\"),\n iconCls: \"pimcore_icon_metadata\",\n border: false,\n layout: \"fit\",\n closable:true,\n items: [this.getRowEditor()]\n });", " var tabPanel = Ext.getCmp(\"pimcore_panel_tabs\");\n tabPanel.add(this.panel);\n tabPanel.setActiveItem(\"predefined_metadata\");", "\n this.panel.on(\"destroy\", function () {\n pimcore.globalmanager.remove(\"predefined_metadata\");\n }.bind(this));", " pimcore.layout.refresh();\n }", " return this.panel;\n },", " getRowEditor: function () {\n var url = Routing.generate('pimcore_admin_settings_metadata');", " this.store = pimcore.helpers.grid.buildDefaultStore(\n url,\n [\n 'id',\n {\n name: 'name',\n allowBlank: false,\n convert: function (v, r) {\n return v.replace(/[~]/g, \"---\");\n }\n },\n 'description','type',\n {name: 'data',\n convert: function (v, r) {\n let dataType = r.data.type;\n if (typeof pimcore.asset.metadata.tags[dataType].prototype.convertPredefinedGridData === \"function\") {\n v = pimcore.asset.metadata.tags[dataType].prototype.convertPredefinedGridData(v, r);\n }\n return v;\n }\n },'config', 'targetSubtype', 'language', 'creationDate' ,'modificationDate'\n ], null, {\n remoteSort: false,\n remoteFilter: false\n }\n );", " this.store.getProxy().getReader().setMessageProperty('message');\n this.store.getProxy().on('exception', function (proxy, response, operation) {\n pimcore.helpers.showNotification(t(\"error\"), t(operation.getError()), \"error\");\n this.store.load();\n }.bind(this));", " this.store.addListener('exception', function(proxy, mode, action, options, response) {\n Ext.Msg.show({\n title: t(\"error\"),\n msg: t(response.raw.message),\n buttons: Ext.Msg.OK,\n animEl: 'elId',\n icon: Ext.MessageBox.ERROR\n });\n });", " this.filterField = new Ext.form.TextField({\n xtype: \"textfield\",\n width: 200,\n style: \"margin: 0 10px 0 0;\",\n enableKeyEvents: true,\n listeners: {\n \"keydown\" : function (field, key) {\n if (key.getKey() == key.ENTER) {\n var input = field;\n var proxy = this.store.getProxy();\n proxy.extraParams.filter = input.getValue();\n this.store.load();\n }\n }.bind(this)\n }\n });", "\n var languagestore = [[\"\",t(\"none\")]];\n for (let i=0; i<pimcore.settings.websiteLanguages.length; i++) {\n languagestore.push([pimcore.settings.websiteLanguages[i],pimcore.settings.websiteLanguages[i]]);\n }", " var supportedTypes = pimcore.helpers.getAssetMetadataDataTypes(\"predefined\");\n var typeStore = [];", " for (let i = 0; i < supportedTypes.length; i++) {\n let type = supportedTypes[i];\n typeStore.push([type, t(type)]);\n }", " var metadataColumns = [\n {\n text: t(\"type\"),\n dataIndex: 'type',\n editable: false,\n width: 40,\n renderer: this.getTypeRenderer.bind(this),\n sortable: true\n },\n {text: t(\"name\"), width: 200, sortable: true, dataIndex: 'name',", " getEditor: function() { return new Ext.form.TextField({ listeners: {'change': pimcore.helpers.htmlEncodeTextField } }); }", " },\n {text: t(\"group\"), width: 200, sortable: true, dataIndex: 'group',\n getEditor: function() { return new Ext.form.TextField({}); }\n },\n {text: t(\"description\"), sortable: true, dataIndex: 'description',\n getEditor: function() { return new Ext.form.TextArea({}); },\n renderer: function (value, metaData, record, rowIndex, colIndex, store) {\n if (empty(value)) {\n return \"\";\n }\n return nl2br(Ext.util.Format.htmlEncode(value));\n }\n },\n {text: t(\"type\"), width: 90, sortable: true,\n dataIndex: 'type',\n getEditor: function() {\n return new Ext.form.ComboBox({\n editable: false,\n store: typeStore", " })\n }\n },\n {text: t(\"value\"),\n flex: 510,\n sortable: true,\n dataIndex: 'data',\n editable: true,\n getEditor: this.getCellEditor.bind(this),\n renderer: this.getCellRenderer.bind(this)\n },\n {text: t(\"configuration\"),\n width: 100,\n sortable: false,\n dataIndex: 'config',\n getEditor: function() { return new Ext.form.TextField({}); }\n },\n {\n text: t('language'),\n sortable: true,\n dataIndex: \"language\",\n getEditor: function() {\n return new Ext.form.ComboBox({\n name: \"language\",\n store: languagestore,\n editable: false,\n triggerAction: 'all',\n mode: \"local\"\n });\n },\n width: 70\n },\n {\n text: t(\"target_subtype\"), width: 80, sortable: true, dataIndex: 'targetSubtype',\n getEditor: function() {\n return new Ext.form.ComboBox({\n editable: true,\n store: [\"image\", \"text\", \"audio\", \"video\", \"document\", \"archive\", \"unknown\"]\n });\n }\n },\n {\n xtype: 'actioncolumn',\n menuText: t('delete'),\n width: 40,\n items: [{\n getClass: function(v, meta, rec) {\n var klass = \"pimcore_action_column \";\n if(rec.data.writeable) {\n klass += \"pimcore_icon_minus\";\n }\n return klass;\n },\n tooltip: t('delete'),\n handler: function (grid, rowIndex) {\n let data = grid.getStore().getAt(rowIndex);\n pimcore.helpers.deleteConfirm(t('predefined_metadata'),\n Ext.util.Format.htmlEncode(data.data.name),\n function () {\n grid.getStore().removeAt(rowIndex);\n }.bind(this));\n }.bind(this)\n }]\n },\n {text: t(\"creationDate\"), sortable: true, dataIndex: 'creationDate', editable: false,\n hidden: true,\n renderer: function(d) {\n if (d !== undefined) {\n var date = new Date(d * 1000);\n return date.format(\"Y-m-d H:i:s\");\n }\n return \"\";\n }\n },\n {text: t(\"modificationDate\"), sortable: true, dataIndex: 'modificationDate', editable: false,\n hidden: true,\n renderer: function(d) {\n if (d !== undefined) {\n var date = new Date(d * 1000);\n return date.format(\"Y-m-d H:i:s\");\n }\n return \"\";\n }\n }\n ];", " this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {\n clicksToEdit: 1,\n listeners: {\n beforeedit: function(editor, context, eOpts) {\n //need to clear cached editors of cell-editing editor in order to\n //enable different editors per row\n editor.editors.each(function (e) {\n try {\n // complete edit, so the value is stored when hopping around with TAB\n e.completeEdit();\n Ext.destroy(e);\n } catch (exception) {\n // garbage collector was faster\n // already destroyed\n }\n });", " editor.editors.clear();\n },\n validateedit: function (editor, context, eOpts) {\n if (!context.record.data.writeable) {\n editor.cancelEdit();\n pimcore.helpers.showNotification(t(\"info\"), t(\"config_not_writeable\"), \"info\");\n return false;\n }\n }\n }\n });", " this.grid = Ext.create('Ext.grid.Panel', {\n frame: false,\n autoScroll: true,\n store: this.store,\n columnLines: true,\n stripeRows: true,\n bodyCls: \"pimcore_editable_grid\",\n trackMouseOver: true,\n columns: {\n items: metadataColumns,\n defaults: {\n renderer: Ext.util.Format.htmlEncode\n },\n },\n clicksToEdit: 1,\n selModel: Ext.create('Ext.selection.CellModel', {}),\n bbar: this.pagingtoolbar,\n autoExpandColumn: \"value_col\",\n plugins: [\n this.cellEditing\n ],", " viewConfig: {\n listeners: {\n rowupdated: this.updateRows.bind(this, \"rowupdated\"),\n refresh: this.updateRows.bind(this, \"refresh\")\n },\n forceFit: true,\n getRowClass: function (record, rowIndex) {\n return record.data.writeable ? '' : 'pimcore_grid_row_disabled';\n }\n },\n tbar: {\n cls: 'pimcore_main_toolbar',\n items: [\n {\n text: t('add'),\n handler: this.onAdd.bind(this),\n iconCls: \"pimcore_icon_add\",\n disabled: !pimcore.settings['predefined-asset-metadata-writeable']\n },\"->\",{\n text: t(\"filter\") + \"/\" + t(\"search\"),\n xtype: \"tbtext\",\n style: \"margin: 0 10px 0 0;\"\n },\n this.filterField\n ]\n }\n });", " this.grid.on(\"viewready\", this.updateRows.bind(this));\n this.store.on(\"update\", this.updateRows.bind(this));", " return this.grid;\n },", " getTypeRenderer: function (value, metaData, record, rowIndex, colIndex, store) {", " if (value == \"input\") {\n value = \"text\";\n }\n return '<div class=\"pimcore_icon_' + value + '\" recordid=' + record.id + '>&nbsp;</div>';\n },", " getCellRenderer: function (value, metaData, record, rowIndex, colIndex, store) {\n var data = store.getAt(rowIndex).data;\n var type = data.type;\n return pimcore.asset.metadata.tags[type].prototype.getGridCellRenderer(value, metaData, record, rowIndex, colIndex, store);\n },", " onAdd: function (btn, ev) {\n var model = this.grid.store.getModel();\n var newEntry = new model({\n name: t('new_definition'),\n key: \"new_key\",\n subtype: \"image\",\n type: \"input\"\n });", " this.grid.store.insert(0, newEntry);\n },", " updateRows: function (event) {\n var rows = Ext.get(this.grid.getEl().dom).query(\".x-grid-row\");", " for (let i = 0; i < rows.length; i++) {", " try {\n var list = Ext.get(rows[i]).query(\".x-grid-cell-first div div\");\n var firstItem = list[0];\n if (!firstItem) {\n continue;\n }\n var recordId = firstItem.getAttribute(\"recordid\");\n var data = this.grid.getStore().getById(recordId);\n if (!data) {\n continue;\n }", " data = data.data;", " if(in_array(data.name, this.disallowedKeys)) {\n Ext.get(rows[i]).addCls(\"pimcore_properties_hidden_row\");\n }", " pimcore.asset.metadata.tags[data.type].prototype.updatePredefinedGridRow(this.grid, rows[i], data);\n }\n catch (e) {\n console.log(e);\n }\n }\n },", " getCellEditor: function (record) {\n var data = record.data;\n var type = data.type;\n var editor = pimcore.asset.metadata.tags[type].prototype.getGridCellEditor(\"predefined\", record);\n return editor;\n }\n});" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\DataObject\\GridColumnConfig\\Operator;", "use Pimcore\\DataObject\\GridColumnConfig\\ConfigElementInterface;", "", "use Pimcore\\Tool;", "abstract class AbstractOperator implements OperatorInterface\n{\n /**\n * @var string\n */\n protected $label;", " /**\n * @var array\n */\n protected array $context = [];", " /**\n * @var ConfigElementInterface[]\n */\n protected $childs;", " /**\n * @param \\stdClass $config\n * @param array $context\n */\n public function __construct(\\stdClass $config, array $context = [])\n {", " $this->label = $config->label;", " $this->childs = $config->childs;\n $this->context = $context;\n }", " /**\n * @return ConfigElementInterface[]\n */\n public function getChilds()\n {\n return $this->childs;\n }", " /**\n * @return bool\n */\n public function expandLocales()\n {\n return false;\n }", " /**\n * @return array\n */\n public function getContext()\n {\n return $this->context;\n }", " /**\n * @param array $context\n */\n public function setContext($context)\n {\n $this->context = $context;\n }", " /**\n * {@inheritdoc}\n */\n public function getLabel()\n {\n return $this->label;\n }", " /**\n * @param string $label\n */\n public function setLabel($label)\n {", " $this->label = $label;", " }", " /**\n * @return string[]\n */\n public function getValidLanguages()\n {\n return Tool::getValidLanguages();\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\DataObject\\GridColumnConfig\\Operator;", "use Pimcore\\DataObject\\GridColumnConfig\\ConfigElementInterface;", "use Pimcore\\Security\\SecurityHelper;", "use Pimcore\\Tool;", "abstract class AbstractOperator implements OperatorInterface\n{\n /**\n * @var string\n */\n protected $label;", " /**\n * @var array\n */\n protected array $context = [];", " /**\n * @var ConfigElementInterface[]\n */\n protected $childs;", " /**\n * @param \\stdClass $config\n * @param array $context\n */\n public function __construct(\\stdClass $config, array $context = [])\n {", " $this->label = SecurityHelper::convertHtmlSpecialChars($config->label);", " $this->childs = $config->childs;\n $this->context = $context;\n }", " /**\n * @return ConfigElementInterface[]\n */\n public function getChilds()\n {\n return $this->childs;\n }", " /**\n * @return bool\n */\n public function expandLocales()\n {\n return false;\n }", " /**\n * @return array\n */\n public function getContext()\n {\n return $this->context;\n }", " /**\n * @param array $context\n */\n public function setContext($context)\n {\n $this->context = $context;\n }", " /**\n * {@inheritdoc}\n */\n public function getLabel()\n {\n return $this->label;\n }", " /**\n * @param string $label\n */\n public function setLabel($label)\n {", " $this->label = SecurityHelper::convertHtmlSpecialChars($label);", " }", " /**\n * @return string[]\n */\n public function getValidLanguages()\n {\n return Tool::getValidLanguages();\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\DataObject\\GridColumnConfig\\Operator;", "use Pimcore\\Model\\AbstractModel;", "", "use Pimcore\\Tool\\Admin;", "/**\n * @internal\n */\nfinal class AnyGetter extends AbstractOperator\n{\n /**\n * @var string\n */\n private $attribute;", " /**\n * @var string\n */\n private $param1;", " /**\n * @var bool\n */\n private $isArrayType;", " /**\n * @var string\n */\n private $forwardAttribute;", " /**\n * @var string\n */\n private $forwardParam1;", " /**\n * @var bool\n */\n private $returnLastResult;", " /**\n * {@inheritdoc}\n */\n public function __construct(\\stdClass $config, $context = null)\n {\n if (!Admin::getCurrentUser()->isAdmin()) {\n throw new \\Exception('AnyGetter only allowed for admin users');\n }", " parent::__construct($config, $context);\n", " $this->attribute = $config->attribute ?? '';\n $this->param1 = $config->param1 ?? '';", " $this->isArrayType = $config->isArrayType ?? false;", " $this->forwardAttribute = $config->forwardAttribute ?? '';\n $this->forwardParam1 = $config->forwardParam1 ?? '';", " $this->returnLastResult = $config->returnLastResult ?? false;\n }", " /**\n * {@inheritdoc}\n */\n public function getLabeledValue($element)\n {\n $result = new \\stdClass();\n $result->label = $this->label;", " $childs = $this->getChilds();", " $getter = 'get'.ucfirst($this->attribute);\n $fallbackGetter = $this->attribute;", " if (!$childs) {\n $result->value = null;\n if ($this->attribute && method_exists($element, $getter)) {\n $result->value = $element->$getter($this->getParam1());\n } elseif ($this->attribute && method_exists($element, $fallbackGetter)) {\n $result->value = $element->$fallbackGetter($this->getParam1());\n }", " if ($result->value instanceof AbstractModel) {\n $result->value = $result->value->getObjectVars();\n }\n } else {\n if (count($childs) > 1) {\n $result->isArrayType = true;\n }\n $resultElements = [];", " if (!is_array($childs)) {\n $childs = [$childs];\n }", " foreach ($childs as $c) {\n $forwardObject = $element;", " if ($this->forwardAttribute) {\n $forwardGetter = 'get'.ucfirst($this->forwardAttribute);\n $forwardParam = $this->getForwardParam1();\n if (method_exists($element, $forwardGetter)) {\n $forwardObject = $element->$forwardGetter($forwardParam);\n if (!$forwardObject) {\n return $result;\n }\n } else {\n return $result;\n }\n }", " $valueContainer = $c->getLabeledValue($forwardObject);", " $value = $valueContainer->value;\n if ($value || $this->getReturnLastResult()) {\n $resultElementValue = $value;\n } else {\n $resultElementValue = null;\n }", " if ($this->getisArrayType()) {\n if (is_array($value)) {\n $subValues = [];\n foreach ($value as $o) {\n if ($o) {\n if ($this->attribute && method_exists($o, $getter)) {\n $subValues[] = $o->$getter($this->getParam1());\n } elseif ($this->attribute && method_exists($o, $fallbackGetter)) {\n $subValues[] = $o->$fallbackGetter($this->getParam1());\n }\n }\n }\n $resultElementValue = $subValues;\n }\n } else {\n $o = $value;\n if ($o) {\n if ($this->attribute && method_exists($o, $getter)) {\n $resultElementValue = $o->$getter($this->getParam1());\n } elseif ($this->attribute && method_exists($o, $fallbackGetter)) {\n $resultElementValue = $o->$fallbackGetter($this->getParam1());\n }\n }\n }\n $resultElements[] = $resultElementValue;\n }\n if (count($childs) == 1) {\n $result->value = $resultElements[0];\n } else {\n $result->value = $resultElements;\n }\n }", " return $result;\n }", " /**\n * @return string\n */\n public function getAttribute()\n {\n return $this->attribute;\n }", " /**\n * @param string $attribute\n */\n public function setAttribute($attribute)\n {", " $this->attribute = $attribute;", " }", " /**\n * @return string\n */\n public function getParam1()\n {\n return $this->param1;\n }", " /**\n * @param string $param1\n */\n public function setParam1($param1)\n {", " $this->param1 = $param1;", " }", " /**\n * @return string\n */\n public function getForwardAttribute()\n {\n return $this->forwardAttribute;\n }", " /**\n * @param string $forwardAttribute\n */\n public function setForwardAttribute($forwardAttribute)\n {\n $this->forwardAttribute = $forwardAttribute;\n }", " /**\n * @return string\n */\n public function getForwardParam1()\n {\n return $this->forwardParam1;\n }", " /**\n * @param string $forwardParam1\n */\n public function setForwardParam1($forwardParam1)\n {\n $this->forwardParam1 = $forwardParam1;\n }", " /**\n * @return bool\n */\n public function getIsArrayType()\n {\n return $this->isArrayType;\n }", " /**\n * @param bool $isArrayType\n */\n public function setIsArrayType($isArrayType)\n {\n $this->isArrayType = $isArrayType;\n }", " /**\n * @return bool\n */\n public function getReturnLastResult()\n {\n return $this->returnLastResult;\n }", " /**\n * @param bool $returnLastResult\n */\n public function setReturnLastResult($returnLastResult)\n {\n $this->returnLastResult = $returnLastResult;\n }\n}" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\DataObject\\GridColumnConfig\\Operator;", "use Pimcore\\Model\\AbstractModel;", "use Pimcore\\Security\\SecurityHelper;", "use Pimcore\\Tool\\Admin;", "/**\n * @internal\n */\nfinal class AnyGetter extends AbstractOperator\n{\n /**\n * @var string\n */\n private $attribute;", " /**\n * @var string\n */\n private $param1;", " /**\n * @var bool\n */\n private $isArrayType;", " /**\n * @var string\n */\n private $forwardAttribute;", " /**\n * @var string\n */\n private $forwardParam1;", " /**\n * @var bool\n */\n private $returnLastResult;", " /**\n * {@inheritdoc}\n */\n public function __construct(\\stdClass $config, $context = null)\n {\n if (!Admin::getCurrentUser()->isAdmin()) {\n throw new \\Exception('AnyGetter only allowed for admin users');\n }", " parent::__construct($config, $context);\n", " $this->attribute = SecurityHelper::convertHtmlSpecialChars($config->attribute ?? '');\n $this->param1 = SecurityHelper::convertHtmlSpecialChars($config->param1 ?? '');", " $this->isArrayType = $config->isArrayType ?? false;", " $this->forwardAttribute = $config->forwardAttribute ?? '';\n $this->forwardParam1 = $config->forwardParam1 ?? '';", " $this->returnLastResult = $config->returnLastResult ?? false;\n }", " /**\n * {@inheritdoc}\n */\n public function getLabeledValue($element)\n {\n $result = new \\stdClass();\n $result->label = $this->label;", " $childs = $this->getChilds();", " $getter = 'get'.ucfirst($this->attribute);\n $fallbackGetter = $this->attribute;", " if (!$childs) {\n $result->value = null;\n if ($this->attribute && method_exists($element, $getter)) {\n $result->value = $element->$getter($this->getParam1());\n } elseif ($this->attribute && method_exists($element, $fallbackGetter)) {\n $result->value = $element->$fallbackGetter($this->getParam1());\n }", " if ($result->value instanceof AbstractModel) {\n $result->value = $result->value->getObjectVars();\n }\n } else {\n if (count($childs) > 1) {\n $result->isArrayType = true;\n }\n $resultElements = [];", " if (!is_array($childs)) {\n $childs = [$childs];\n }", " foreach ($childs as $c) {\n $forwardObject = $element;", " if ($this->forwardAttribute) {\n $forwardGetter = 'get'.ucfirst($this->forwardAttribute);\n $forwardParam = $this->getForwardParam1();\n if (method_exists($element, $forwardGetter)) {\n $forwardObject = $element->$forwardGetter($forwardParam);\n if (!$forwardObject) {\n return $result;\n }\n } else {\n return $result;\n }\n }", " $valueContainer = $c->getLabeledValue($forwardObject);", " $value = $valueContainer->value;\n if ($value || $this->getReturnLastResult()) {\n $resultElementValue = $value;\n } else {\n $resultElementValue = null;\n }", " if ($this->getisArrayType()) {\n if (is_array($value)) {\n $subValues = [];\n foreach ($value as $o) {\n if ($o) {\n if ($this->attribute && method_exists($o, $getter)) {\n $subValues[] = $o->$getter($this->getParam1());\n } elseif ($this->attribute && method_exists($o, $fallbackGetter)) {\n $subValues[] = $o->$fallbackGetter($this->getParam1());\n }\n }\n }\n $resultElementValue = $subValues;\n }\n } else {\n $o = $value;\n if ($o) {\n if ($this->attribute && method_exists($o, $getter)) {\n $resultElementValue = $o->$getter($this->getParam1());\n } elseif ($this->attribute && method_exists($o, $fallbackGetter)) {\n $resultElementValue = $o->$fallbackGetter($this->getParam1());\n }\n }\n }\n $resultElements[] = $resultElementValue;\n }\n if (count($childs) == 1) {\n $result->value = $resultElements[0];\n } else {\n $result->value = $resultElements;\n }\n }", " return $result;\n }", " /**\n * @return string\n */\n public function getAttribute()\n {\n return $this->attribute;\n }", " /**\n * @param string $attribute\n */\n public function setAttribute($attribute)\n {", " $this->attribute = SecurityHelper::convertHtmlSpecialChars($attribute);", " }", " /**\n * @return string\n */\n public function getParam1()\n {\n return $this->param1;\n }", " /**\n * @param string $param1\n */\n public function setParam1($param1)\n {", " $this->param1 = SecurityHelper::convertHtmlSpecialChars($param1);", " }", " /**\n * @return string\n */\n public function getForwardAttribute()\n {\n return $this->forwardAttribute;\n }", " /**\n * @param string $forwardAttribute\n */\n public function setForwardAttribute($forwardAttribute)\n {\n $this->forwardAttribute = $forwardAttribute;\n }", " /**\n * @return string\n */\n public function getForwardParam1()\n {\n return $this->forwardParam1;\n }", " /**\n * @param string $forwardParam1\n */\n public function setForwardParam1($forwardParam1)\n {\n $this->forwardParam1 = $forwardParam1;\n }", " /**\n * @return bool\n */\n public function getIsArrayType()\n {\n return $this->isArrayType;\n }", " /**\n * @param bool $isArrayType\n */\n public function setIsArrayType($isArrayType)\n {\n $this->isArrayType = $isArrayType;\n }", " /**\n * @return bool\n */\n public function getReturnLastResult()\n {\n return $this->returnLastResult;\n }", " /**\n * @param bool $returnLastResult\n */\n public function setReturnLastResult($returnLastResult)\n {\n $this->returnLastResult = $returnLastResult;\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\Security;", "class SecurityHelper\n{\n public static function convertHtmlSpecialChars(?string $text): ?string\n {\n if(is_string($text)) {\n return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false);\n }", " return null;\n }", "", "}" ]
[ 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * Pimcore\n *\n * This source file is available under two different licenses:\n * - GNU General Public License version 3 (GPLv3)\n * - Pimcore Commercial License (PCL)\n * Full copyright and license information is available in\n * LICENSE.md which is distributed with this source code.\n *\n * @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)\n * @license http://www.pimcore.org/license GPLv3 and PCL\n */", "namespace Pimcore\\Security;", "class SecurityHelper\n{\n public static function convertHtmlSpecialChars(?string $text): ?string\n {\n if(is_string($text)) {\n return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false);\n }", " return null;\n }", "\n public static function convertHtmlSpecialCharsArrayKeys(array &$array, array $keys): void\n {\n foreach ($keys as $key) {\n if (array_key_exists($key, $array)) {\n $array[$key] = self::convertHtmlSpecialChars($array[$key]);\n }\n }\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [969, 357, 187, 142, 95, 202, 27], "buggy_code_start_loc": [35, 34, 86, 141, 18, 18, 27], "filenames": ["bundles/AdminBundle/Controller/Admin/Asset/AssetHelperController.php", "bundles/AdminBundle/Controller/Admin/DataObject/DataObjectHelperController.php", "bundles/AdminBundle/Resources/public/js/pimcore/object/gridcolumn/operator/AnyGetter.js", "bundles/AdminBundle/Resources/public/js/pimcore/settings/metadata/predefined.js", "lib/DataObject/GridColumnConfig/Operator/AbstractOperator.php", "lib/DataObject/GridColumnConfig/Operator/AnyGetter.php", "lib/Security/SecurityHelper.php"], "fixing_code_end_loc": [971, 366, 190, 142, 96, 203, 37], "fixing_code_start_loc": [36, 35, 86, 141, 19, 19, 28], "message": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:pimcore:pimcore:*:*:*:*:*:*:*:*", "matchCriteriaId": "72C537D6-67BA-4562-B853-F99E6C14315C", "versionEndExcluding": "10.5.21", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Cross-site Scripting (XSS) - Reflected in GitHub repository pimcore/pimcore prior to 10.5.21."}], "evaluatorComment": null, "id": "CVE-2023-2339", "lastModified": "2023-05-04T20:07:25.237", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 6.1, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 2.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-04-27T12:15:09.300", "references": [{"source": "security@huntr.dev", "tags": ["Patch"], "url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch"], "url": "https://huntr.dev/bounties/bb1537a5-fe7b-4c77-a582-10a82435fbc2"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/pimcore/pimcore/commit/6946f8a5a0a93b516c49f17a5b45044eebd73480"}, "type": "CWE-79"}
22
Determine whether the {function_name} code is vulnerable or not.
[ "using System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Markdig;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.AspNetCore.Mvc;\nusing Ombi.Attributes;", "namespace Ombi.Controllers.V2\n{\n [Admin]\n public class SystemController : V2Controller\n {\n private readonly IWebHostEnvironment _hosting;\n private readonly HttpClient _client;", " public SystemController(IWebHostEnvironment hosting, IHttpClientFactory httpClientFactory)\n {\n _hosting = hosting;\n _client = httpClientFactory.CreateClient();\n }", " [HttpGet(\"news\")]\n public async Task<IActionResult> GetNews()\n {\n var result = await _client.GetAsync(\"https://raw.githubusercontent.com/Ombi-app/Ombi.News/main/README.md\");\n var content = await result.Content.ReadAsStringAsync();\n var md = Markdown.ToHtml(content);\n return Ok(md);\n }", " [HttpGet(\"logs\")]\n public IActionResult GetLogFiles()\n {\n var logsFolder = Path.Combine(string.IsNullOrEmpty(Ombi.Helpers.StartupSingleton.Instance.StoragePath) ? _hosting.ContentRootPath : Helpers.StartupSingleton.Instance.StoragePath, \"Logs\");\n var files = Directory\n .EnumerateFiles(logsFolder, \"*.txt\", SearchOption.TopDirectoryOnly)\n .Select(Path.GetFileName)\n .OrderByDescending(name => name);", " return Ok(files);\n }", " [HttpGet(\"logs/{logFileName}\")]", " public async Task<IActionResult> ReadLogFile(string logFileName, CancellationToken token)", " {", " var logFile = Path.Combine(string.IsNullOrEmpty(Ombi.Helpers.StartupSingleton.Instance.StoragePath) ? _hosting.ContentRootPath : Helpers.StartupSingleton.Instance.StoragePath, \"Logs\", logFileName);\n using (var fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n using (StreamReader reader = new StreamReader(fs))", " {", "", " return Ok(await reader.ReadToEndAsync());\n }", "", " }", " [HttpGet(\"logs/download/{logFileName}\")]", " public IActionResult Download(string logFileName, CancellationToken token)", " {", " var logFile = Path.Combine(string.IsNullOrEmpty(Ombi.Helpers.StartupSingleton.Instance.StoragePath) ? _hosting.ContentRootPath : Helpers.StartupSingleton.Instance.StoragePath, \"Logs\", logFileName);\n using (var fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n using (StreamReader reader = new StreamReader(fs))", " {", "", " return File(reader.BaseStream, \"application/octet-stream\", logFileName);\n }", "", " }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [65], "buggy_code_start_loc": [47], "filenames": ["src/Ombi/Controllers/V2/SystemController.cs"], "fixing_code_end_loc": [74], "fixing_code_start_loc": [47], "message": "Ombi is an open source application which allows users to request specific media from popular self-hosted streaming servers. Versions prior to 4.38.2 contain an arbitrary file read vulnerability where an Ombi administrative user may access files available to the Ombi server process on the host operating system. Ombi administrators may not always be local system administrators and so this may violate the security expectations of the system. The arbitrary file read vulnerability was present in `ReadLogFile` and `Download` endpoints in `SystemControllers.cs` as the parameter `logFileName` is not sanitized before being combined with the `Logs` directory. When using `Path.Combine(arg1, arg2, arg3)`, an attacker may be able to escape to folders/files outside of `Path.Combine(arg1, arg2)` by using \"..\" in `arg3`. In addition, by specifying an absolute path for `arg3`, `Path.Combine` will completely ignore the first two arguments and just return just `arg3`. This vulnerability can lead to information disclosure. The Ombi `documentation` suggests running Ombi as a Service with Administrator privileges. An attacker targeting such an application may be able to read the files of any Windows user on the host machine and certain system files. This issue has been addressed in commit `b8a8f029` and in release version 4.38.2. Users are advised to upgrade. There are no known workarounds for this vulnerability. This issue is also tracked as GHSL-2023-088.\n", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ombi:ombi:*:*:*:*:*:*:*:*", "matchCriteriaId": "6D5D19E8-9FC0-4510-AF83-E15914C70F84", "versionEndExcluding": "4.38.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ombi is an open source application which allows users to request specific media from popular self-hosted streaming servers. Versions prior to 4.38.2 contain an arbitrary file read vulnerability where an Ombi administrative user may access files available to the Ombi server process on the host operating system. Ombi administrators may not always be local system administrators and so this may violate the security expectations of the system. The arbitrary file read vulnerability was present in `ReadLogFile` and `Download` endpoints in `SystemControllers.cs` as the parameter `logFileName` is not sanitized before being combined with the `Logs` directory. When using `Path.Combine(arg1, arg2, arg3)`, an attacker may be able to escape to folders/files outside of `Path.Combine(arg1, arg2)` by using \"..\" in `arg3`. In addition, by specifying an absolute path for `arg3`, `Path.Combine` will completely ignore the first two arguments and just return just `arg3`. This vulnerability can lead to information disclosure. The Ombi `documentation` suggests running Ombi as a Service with Administrator privileges. An attacker targeting such an application may be able to read the files of any Windows user on the host machine and certain system files. This issue has been addressed in commit `b8a8f029` and in release version 4.38.2. Users are advised to upgrade. There are no known workarounds for this vulnerability. This issue is also tracked as GHSL-2023-088.\n"}], "evaluatorComment": null, "id": "CVE-2023-32322", "lastModified": "2023-05-26T13:51:42.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-18T17:15:09.003", "references": [{"source": "security-advisories@github.com", "tags": ["Product"], "url": "https://docs.ombi.app/guides/installation/#windows"}, {"source": "security-advisories@github.com", "tags": ["Product"], "url": "https://github.com/Ombi-app/Ombi/blob/v4.36.1/src/Ombi/Controllers/V2/SystemController.cs#L46"}, {"source": "security-advisories@github.com", "tags": ["Product"], "url": "https://github.com/Ombi-app/Ombi/blob/v4.36.1/src/Ombi/Controllers/V2/SystemController.cs#L58"}, {"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/Ombi-app/Ombi/commit/b8a8f029d80454d582bc4a2a05175106809335d0"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Mitigation", "Third Party Advisory"], "url": "https://github.com/Ombi-app/Ombi/security/advisories/GHSA-28j3-84m7-gpjp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Ombi-app/Ombi/commit/b8a8f029d80454d582bc4a2a05175106809335d0"}, "type": "CWE-22"}
23
Determine whether the {function_name} code is vulnerable or not.
[ "using System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Markdig;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.AspNetCore.Mvc;\nusing Ombi.Attributes;", "namespace Ombi.Controllers.V2\n{\n [Admin]\n public class SystemController : V2Controller\n {\n private readonly IWebHostEnvironment _hosting;\n private readonly HttpClient _client;", " public SystemController(IWebHostEnvironment hosting, IHttpClientFactory httpClientFactory)\n {\n _hosting = hosting;\n _client = httpClientFactory.CreateClient();\n }", " [HttpGet(\"news\")]\n public async Task<IActionResult> GetNews()\n {\n var result = await _client.GetAsync(\"https://raw.githubusercontent.com/Ombi-app/Ombi.News/main/README.md\");\n var content = await result.Content.ReadAsStringAsync();\n var md = Markdown.ToHtml(content);\n return Ok(md);\n }", " [HttpGet(\"logs\")]\n public IActionResult GetLogFiles()\n {\n var logsFolder = Path.Combine(string.IsNullOrEmpty(Ombi.Helpers.StartupSingleton.Instance.StoragePath) ? _hosting.ContentRootPath : Helpers.StartupSingleton.Instance.StoragePath, \"Logs\");\n var files = Directory\n .EnumerateFiles(logsFolder, \"*.txt\", SearchOption.TopDirectoryOnly)\n .Select(Path.GetFileName)\n .OrderByDescending(name => name);", " return Ok(files);\n }", " [HttpGet(\"logs/{logFileName}\")]", " public async Task<IActionResult> ReadLogFile(string logFileName)", " {", " var logsFolder = Path.Combine(string.IsNullOrEmpty(Ombi.Helpers.StartupSingleton.Instance.StoragePath) ? _hosting.ContentRootPath : Helpers.StartupSingleton.Instance.StoragePath, \"Logs\");\n var files = Directory.EnumerateFiles(logsFolder);\n var matchingFile = files.FirstOrDefault(x => Path.GetFileName(x).Equals(logFileName));\n if (matchingFile != null)", " {", " using var fs = new FileStream(matchingFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n using StreamReader reader = new(fs);", " return Ok(await reader.ReadToEndAsync());\n }", " return NotFound();", " }", " [HttpGet(\"logs/download/{logFileName}\")]", " public IActionResult Download(string logFileName)", " {", " var logsFolder = Path.Combine(string.IsNullOrEmpty(Ombi.Helpers.StartupSingleton.Instance.StoragePath) ? _hosting.ContentRootPath : Helpers.StartupSingleton.Instance.StoragePath, \"Logs\");\n var files = Directory.EnumerateFiles(logsFolder);\n var matchingFile = files.FirstOrDefault(x => Path.GetFileName(x).Equals(logFileName));\n if (matchingFile != null)", " {", " using var fs = new FileStream(matchingFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);\n using StreamReader reader = new(fs);", " return File(reader.BaseStream, \"application/octet-stream\", logFileName);\n }", " return NotFound();", " }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [65], "buggy_code_start_loc": [47], "filenames": ["src/Ombi/Controllers/V2/SystemController.cs"], "fixing_code_end_loc": [74], "fixing_code_start_loc": [47], "message": "Ombi is an open source application which allows users to request specific media from popular self-hosted streaming servers. Versions prior to 4.38.2 contain an arbitrary file read vulnerability where an Ombi administrative user may access files available to the Ombi server process on the host operating system. Ombi administrators may not always be local system administrators and so this may violate the security expectations of the system. The arbitrary file read vulnerability was present in `ReadLogFile` and `Download` endpoints in `SystemControllers.cs` as the parameter `logFileName` is not sanitized before being combined with the `Logs` directory. When using `Path.Combine(arg1, arg2, arg3)`, an attacker may be able to escape to folders/files outside of `Path.Combine(arg1, arg2)` by using \"..\" in `arg3`. In addition, by specifying an absolute path for `arg3`, `Path.Combine` will completely ignore the first two arguments and just return just `arg3`. This vulnerability can lead to information disclosure. The Ombi `documentation` suggests running Ombi as a Service with Administrator privileges. An attacker targeting such an application may be able to read the files of any Windows user on the host machine and certain system files. This issue has been addressed in commit `b8a8f029` and in release version 4.38.2. Users are advised to upgrade. There are no known workarounds for this vulnerability. This issue is also tracked as GHSL-2023-088.\n", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ombi:ombi:*:*:*:*:*:*:*:*", "matchCriteriaId": "6D5D19E8-9FC0-4510-AF83-E15914C70F84", "versionEndExcluding": "4.38.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Ombi is an open source application which allows users to request specific media from popular self-hosted streaming servers. Versions prior to 4.38.2 contain an arbitrary file read vulnerability where an Ombi administrative user may access files available to the Ombi server process on the host operating system. Ombi administrators may not always be local system administrators and so this may violate the security expectations of the system. The arbitrary file read vulnerability was present in `ReadLogFile` and `Download` endpoints in `SystemControllers.cs` as the parameter `logFileName` is not sanitized before being combined with the `Logs` directory. When using `Path.Combine(arg1, arg2, arg3)`, an attacker may be able to escape to folders/files outside of `Path.Combine(arg1, arg2)` by using \"..\" in `arg3`. In addition, by specifying an absolute path for `arg3`, `Path.Combine` will completely ignore the first two arguments and just return just `arg3`. This vulnerability can lead to information disclosure. The Ombi `documentation` suggests running Ombi as a Service with Administrator privileges. An attacker targeting such an application may be able to read the files of any Windows user on the host machine and certain system files. This issue has been addressed in commit `b8a8f029` and in release version 4.38.2. Users are advised to upgrade. There are no known workarounds for this vulnerability. This issue is also tracked as GHSL-2023-088.\n"}], "evaluatorComment": null, "id": "CVE-2023-32322", "lastModified": "2023-05-26T13:51:42.143", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2023-05-18T17:15:09.003", "references": [{"source": "security-advisories@github.com", "tags": ["Product"], "url": "https://docs.ombi.app/guides/installation/#windows"}, {"source": "security-advisories@github.com", "tags": ["Product"], "url": "https://github.com/Ombi-app/Ombi/blob/v4.36.1/src/Ombi/Controllers/V2/SystemController.cs#L46"}, {"source": "security-advisories@github.com", "tags": ["Product"], "url": "https://github.com/Ombi-app/Ombi/blob/v4.36.1/src/Ombi/Controllers/V2/SystemController.cs#L58"}, {"source": "security-advisories@github.com", "tags": ["Patch"], "url": "https://github.com/Ombi-app/Ombi/commit/b8a8f029d80454d582bc4a2a05175106809335d0"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Mitigation", "Third Party Advisory"], "url": "https://github.com/Ombi-app/Ombi/security/advisories/GHSA-28j3-84m7-gpjp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-22"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-22"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/Ombi-app/Ombi/commit/b8a8f029d80454d582bc4a2a05175106809335d0"}, "type": "CWE-22"}
23
Determine whether the {function_name} code is vulnerable or not.
[ "![Rdiffweb Banner](https://gitlab.com/ikus-soft/rdiffweb/-/raw/master/doc/_static/banner.png)", "<p align=\"center\">\n<strong>\n<a href=\"https://www.rdiffweb.org\">website</a>\nβ€’ <a href=\"https://www.ikus-soft.com/archive/rdiffweb/doc/latest/html/\">docs</a>\nβ€’ <a href=\"https://groups.google.com/d/forum/rdiffweb\">community</a>\nβ€’ <a href=\"https://rdiffweb-demo.ikus-soft.com/\">demo</a>\n</strong>\n</p>", "<p align=\"center\">\n<a href=\"LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/github/license/ikus060/rdiffweb\"></a>\n<a href=\"https://gitlab.com/ikus-soft/rdiffweb/pipelines\"><img alt=\"Build\" src=\"https://gitlab.com/ikus-soft/rdiffweb/badges/master/pipeline.svg\"></a>\n<a href=\"https://sonar.ikus-soft.com/dashboard?id=rdiffweb\"><img alt=\"Quality Gate Minarca Client\" src=\"https://sonar.ikus-soft.com/api/project_badges/measure?project=rdiffweb&metric=alert_status\"></a>\n<a href=\"https://sonar.ikus-soft.com/dashboard?id=rdiffweb\"><img alt=\"Coverage\" src=\"https://sonar.ikus-soft.com/api/project_badges/measure?project=rdiffweb&metric=coverage\"></a>\n</p>", "<h1 align=\"center\">\nWelcome to Rdiffweb\n</h1>", "Rdiffweb is a web application that allows you to view repositories generated\nby [rdiff-backup](https://rdiff-backup.net/). The purpose of this\napplication is to ease the management of backups and quickly restore your data\nwith a rich and powerful web interface.", "Rdiffweb is written in Python and is released as open source project under the \nGNU GENERAL PUBLIC LICENSE (GPL). All source code and documentation are\nCopyright Rdiffweb contributors.", "Rdiffweb is actively developed by [IKUS Soft](https://www.ikus-soft.com/)\nsince November 2014.", "The Rdiffweb source code is hosted on [Gitlab](https://gitlab.com/ikus-soft/rdiffweb)\nand mirrored to [Github](https://github.com/ikus060/rdiffweb).", "The Rdiffweb website is https://rdiffweb.org/.", "## Features", "With its rich web interface Rdiffweb provide a notable list of features:", " * Browse your backup\n * Restore single file or multiple files as an archived\n * Users authentication via local database and LDAP\n * Users authorization\n * Email notification when backup is not successful\n * Configurable repository encoding\n * Configurable retention period\n * Backup statistics visualization using graphs\n * SSH Keys management\n * Disk quota visualization\n * File and folder deletion", "## Demo", "If you quickly want to check how Rdiffweb is behaving, you may try our demo server hosted on:", "[https://rdiffweb-demo.ikus-soft.com/](https://rdiffweb-demo.ikus-soft.com/)", "Use the following credential to login:", " * Username: admin\n * Password: admin123", "## Installation & Docker usage", "For detailed installation steps, read the [Installation documentation](https://www.ikus-soft.com/archive/rdiffweb/doc/latest/html/installation.html).", "## Current Build Status", "[![Build Status](https://gitlab.com/ikus-soft/rdiffweb/badges/master/pipeline.svg)](https://gitlab.com/ikus-soft/rdiffweb/pipelines)", "## Download", "You should read the [Documentation](https://www.ikus-soft.com/archive/rdiffweb/doc/latest/html/index.html) to properly install Rdiffweb in your environment.", "**Docker**", " docker pull ikus060/rdiffweb\n \n**Debian**", " curl -L https://www.ikus-soft.com/archive/rdiffweb/public.key | apt-key add - \n echo \"deb https://nexus.ikus-soft.com/repository/apt-release-bullseye/ bullseye main\" > /etc/apt/sources.list.d/rdiffweb.list\n apt update\n apt install rdiffweb", "**Pypi**", " pip install rdiffweb", "## Support", "### Mailing list", "Rdiffweb users should use the [Rdiffweb mailing list](https://groups.google.com/forum/#!forum/rdiffweb).", "### Bug Reports", "Bug reports should be reported on the Rdiffweb Gitlab at https://gitlab.com/ikus-soft/rdiffweb/-/issues", "### Professional support", "Professional support for Rdiffweb is available by contacting [IKUS Soft](https://www.ikus-soft.com/en/support/#form).", "# Changelog", "## Next Release - 2.5.0", "This next release focus on two-factor-authentication as a measure to increase security of user's account.", "* Store User's session information into database\n* Update ldap plugin to load additional attributes from LDAP server\n* Improve `/status` page error handling when `session_statistics` cannot be read\n* Add support for Ubuntu Jammy\n* Upgrade from Bootstrap v3 to v4 #204\n* Replace Fontello by Font-Awesome v4\n* Use CSS variables `var()` to customize themes\n* Remove usage of Jquery.validate\n* Replace custom timsort by jquery DataTables #205\n* Add Active Session managements #203\n * Active session should be visible in user's profiles\n * Active session may be revoked by user\n * Active session should be visible in administration view\n * Action session may be revoke by administrator\n * Show number of active users within the last 24 hours in dashboard\n* Handle migration of older Rdiffweb database by adding the missing `repos.Encoding`, `repos.keepdays` and `users.role` columns #185\n* Replace deprecated references of `disutils.spawn.find_executable()` by `shutil.which()` #208\n* Add two-factor authentication with email verification #201\n* Generate a new session on login and 2FA #220\n* Enforce permission on /etc/rdiffweb configuration folder\n* Enforce validation on fullname, username and email\n* Limit incorrect attempts to change the user's password to prevent brute force attacks #225 [CVE-2022-3273](https://nvd.nist.gov/vuln/detail/CVE-2022-3273)", "", "\nBreaking changes:", "* Drop Ubuntu Hirsute & Impish (End-of-life)\n* `session-dir` is deprecated and should be replace by `rate-limit-dir`. User's session are stored in database.\n* previous `.css` customization are not barkward compatible", "## 2.4.10 (2022-10-03)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Mitigate path traversal vulnerability [CVE-2022-3389](https://nvd.nist.gov/vuln/detail/CVE-2022-3389)", "## 2.4.9 (2022-09-28)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Add `Cache-Control` and other security headers [CVE-2022-3292](https://nvd.nist.gov/vuln/detail/CVE-2022-3292)\n* Enforce password policy using `password-score` based on [zxcvbn](https://github.com/dropbox/zxcvbn) [CVE-2022-3326](https://nvd.nist.gov/vuln/detail/CVE-2022-3326)", "## 2.4.8 (2022-09-26)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Clean-up invalid path on error page\n* Limit username field length [CVE-2022-3290](https://nvd.nist.gov/vuln/detail/CVE-2022-3290)\n* Limit user's email field length [CVE-2022-3272](https://nvd.nist.gov/vuln/detail/CVE-2022-3272)\n* Limit user's root directory field length [CVE-2022-3295](https://nvd.nist.gov/vuln/detail/CVE-2022-3295)\n* Limit SSH Key title field length [CVE-2022-3298](https://nvd.nist.gov/vuln/detail/CVE-2022-3298)", "## 2.4.7 (2002-09-21)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Generate a new session on login and 2FA #220 [CVE-2022-3269](https://nvd.nist.gov/vuln/detail/CVE-2022-3269)\n* Mitigate CSRF on user's settings #221 [CVE-2022-3274](https://nvd.nist.gov/vuln/detail/CVE-2022-3274)", "## 2.4.6 (2022-09-20)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Support MarkupSafe<3 for Debian bookworm\n* Mitigate CSRF on user's notification settings #216 [CVE-2022-3233](https://nvd.nist.gov/vuln/detail/CVE-2022-3233)\n* Mitigate CSRF on repository settings #217 [CVE-2022-3267](https://nvd.nist.gov/vuln/detail/CVE-2022-3267)\n* Use 'Secure' Attribute with Sensitive Cookie in HTTPS Session on HTTP Error #218 [CVE-2022-3174](https://nvd.nist.gov/vuln/detail/CVE-2022-3174)", "## 2.4.5 (2002-09-16)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Mitigate CSRF on repository deletion and user deletion [CVE-2022-3232](https://nvd.nist.gov/vuln/detail/CVE-2022-3232) #214 #215", "## 2.4.4 (2002-09-15)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Use `X-Real-IP` to identify client IP address to mitigate Brute-Force attack #213", "## 2.4.3 (2022-09-14)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Mitigate CSRF in profile's SSH Keys [CVE-2022-3221](https://nvd.nist.gov/vuln/detail/CVE-2022-3221) #212", "## 2.4.2 (2022-09-12)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Use 'Secure' Attribute with Sensitive Cookie in HTTPS Session. [CVE-2022-3174](https://nvd.nist.gov/vuln/detail/CVE-2022-3174) #209\n* Avoid leakage of the stack trace in the default error page. [CVE-2022-3175](https://nvd.nist.gov/vuln/detail/CVE-2022-3175) #210\n* Enforce minimum and maximum password length [CVE-2022-3175](https://nvd.nist.gov/vuln/detail/CVE-2022-3179) #211", "## 2.4.1 (2022-09-08)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Add Clickjacking Defense [CVE-2022-3167](https://nvd.nist.gov/vuln/detail/CVE-2022-3167)\n* Drop Ubuntu Hirsute & Impish (End-of-life)", "## 2.4.0 (2022-06-21)", "This new release brings a lot of improvement since the last version, multiple bug fixes\nto make the application stable. A couple of new features to improve the overall\nusability and a new security feature to block a brute force attack.", "* Add RateLimit to login page and API to mitigate robots attacks #167\n* Send email notification only if `email-sender` option is defined to avoid raising exception in logs #176\n* Support file restore cancellation without leaving `rdiffweb-restore` process in `<defunct>` state #174\n* Replace `python-ldap` by `ldap3` a pure python implementation to avoid dependencies on `sasl` and `ldap` binaries #186\n* Reffactor core module to allow better extendability and reusability #183\n* Add support for Debian Bookworm #180\n* Add support for Ubuntu Impish #175\n* Add rdiff-backup version to administration view\n* Run unit test during Debian build package\n* Refresh repository list automatically when required #188 #189\n* Fix error 500 displayed in status page #191\n* Improve repository browsing speed by minimizing the number of I/O call #192\n* Publish Docker image directly to DockerHub #144\n* Add REST API to manage sshkeys", "Breaking changes:", "* Ldap Password changes is not supported anymore.\n* Ldap Check Shadow expire config is not supported anymore. It should be replace by a custom filter.\n* Drop CentOS 7 and CentOS 8 support", "## 2.3.9 (2022-01-05)", "Maintenance release to fix minor issues", "* Improve date parsing for `backup.log` to avoid printing exception in logs #170\n* Return HTTP error 403 for invalid symlink to avoid returning a misleading HTTP 500 Server Error #168\n* Show a user friendly error message when trying to create a new user with an existing username #169\n* Handle repository without last-backup date during the notification process to ensure notifications are sent #171\n* Replace CherryPy `storage_type` by `storage_class` to avoid warning in logs\n* Update code to avoid deprecation warning where applicable\n* Add Flake8 validation to improve code quality\n* Remove Ubuntu Groovy support", "## 2.3.8 (2021-12-01)", "* Push all artefacts to nexus server including binaries and documentation\n* Fix `Chart.js` loading on Debian bullseye #164\n* Update installation steps documentation\n* Improve LDAP authentication to lookup entire directory\n* Fix usage of `--ldap-add-user-default-userroot` to avoid error related to wrong encoding\n* Improve authentication mechanics\n* Avoid raising an HTTP error 500 when login form receive invalid payload\n* Mitigate open redirect vulnerability in login form", "## 2.3.7 (2021-10-21)", " * To avoid backward compatibility issue, revert CSRF Token validation\n * Mitigate CSRF vulnerability using cookies with `SameSite=Lax`\n * Mitigate CSRF vulnerability by validating the `Origin` header when a form is submited\n * Improve usage of WTForm for all form validation\n * Update installation stepd for debian #162\n * Build Ubuntu packages and publish them to our APT repo", "## 2.3.6 (2021-10-20)", " * Broken build", "## 2.3.5 (2021-10-18)", " * Mitigate CSRF vulnerability to user, ssh and repo management with CSRF Token", "## 2.3.4 (2021-09-20)", " * Skip email notification if `email-host` configuration is not provided #157\n * Skip email notification when the new attribute value has the same value #159\n * USE LDAP `mail` attribute when creating new user from LDAP directory #156", "## 2.3.3 (2021-09-10)", " * Provide a new theme `blue` to match IKUS Soft colors #158", "## 2.3.2 (2021-09-07)", " * Automatically update user's repository list based on user's home directory", "## 2.3.1 (2021-07-14)", " * Update default `session-dir` location to `/var/lib/rdiffweb/session` to avoid using `/var/run` #148", "## 2.3.0 (2021-07-06)", " * Improve timezone handling to display date with local timezone using javascript #143\n * Improve charts by replacing d3js by chartkick #122\n * Replace the status view by something meaningful with chartkick #122\n * Provide Docker image with Rdiffweb `docker pull ikus060/rdiffweb` #55\n * Fix file and folder sorting #143", "## 2.2.0 (2021-05-11)\n \n * Debian package:\n * Add rdiff-backup as dependencies to comply with Debian packaging rules\n * Multiple other fixed to control files\n * Use debhelper-compat (= 13)\n * Use debhelper-compat (= 13)\n * Run test during packaging\n * Create default folder `/var/run/rdiffweb/sessions` to store user session\n * Use ConfigArgPare for configuration to support configuration file, environment variables and arguments to configure rdiffweb #114\n * Fix cache in localization module\n * Add `ldap-add-default-role` and `ldap-add-default-userroot` option to define default value for role and user root when creating user from LDAP #125\n * Support PostgreSQL database by replacing our storage layer by SQLAlchemy #126\n * Fix to retrieve user quota only for valid user_root #135\n * Add option `disable-ssh-keys` to disable SSH Key management\n * Use absolute URL everywhere\n * Add support for `X-Forwarded-For`, `X-Forwarded-proto` and other reverse proxy header when generating absolute URL\n * Drop Debian Stretch support\n * Implement a new background scheduler using apscheduler #82\n * Use background job to send email notification to avoid blocking web page loading #47\n * Use background job to delete repository to avoid blocking web page loading #48\n * Allow deleting a specific file or folder from the history using `rdiff-backup-delete` #128\n * Improve support for `session-dir` #131\n * Add option `admin-password` to define administrator password for better security\n * Improve performance of repository browsing \n * Add a new view to display logs of a specific repository\n * Allow downloading the log\n * Define a default limit to graph statistics to make it display faster\n * Fix `get-quota-cmd` option to properly return a value", "## 2.1.0 (2021-01-15)", "* Debian package: Remove dh-systemd from Debian build dependencies (https://bugs.debian.org/871312we)\n* Improve Quota management:\n * `QuotaSetCmd`, `QuotaGetCmd` and `QuotaUsedCmd` options could be used to customize how to set the quota for your environment.\n * Display user's quota in User View\n * Display user's quota in Admin View\n * Allow admin to update user quota from Admin View when `QuotaSetCmd` is defined.\n * Allow admin to define user quota using human readable value (e.g.: GiB, TiB, etc.)\n * Improve logging around quota management\n* Improve robustness when service is starting\n* Improve robustness when repository has wrong permission defined (e.g.: when some files not readable)\n* Add user id in Admin view\n* Replace `UserObject(1)` by the actual username in log file to improve debugging", "## 2.0.0 (2020-12-04)", "* Re-implement logic to update repositories views to remove duplicates and avoid nesting repo. #107\n* Handle elapsed time of days in the graph. Thanks [Nathaniel van Diepen](https://github.com/Eeems) contributions.\n* Rebrand all link to ikus-soft.com\n* Update documentation to install rdiffweb\n* Remove obsolete minify dependency\n* Drop support for python2\n* Provide null translation if translation catalogues are not found\n* Pass a LANG environment variable to rdiff-backup restore process to fix encoding issue #112\n* Remove obsolete python shebang\n* Remove execution bit (+x) on python modules\n* Provide `--help` and `--version` on `rdiffweb` executable\n* Improve cherrypy version detection\n* Do not update translation files (.mo) during build", "## 1.5.0 (2020-06-24)", "This minor release introduce official support of rdiffweb on Debian Bullseye. It also includes some usability improvements.", " * Change formatting of Last Backup date for \"Updated 3 weeks ago\" to ease the readability\n * Add support for Debian Bullseye\n * Add support for Python 3.8 (#104)\n * Add warning in the users list view when a root directory is invalid (#30)\n * Add options to control search depthness (#1)\n * Print a warning in the log when the \"DefaultTheme\" value is not valid (#90)", "## 1.4.0 (2020-05-20)", "Thanks to our sponsor, this release introduce a feature to have better control over the user's permission by defining 3 different levels of privilege: Admin, Maintainer and User. This addition allows you to have better control on what your users can or can't do.", " * Fix single repository discovery when a user's home is a rdiff-backup repository\n * [SPONSORED] Add a new setting at the user level to define the user's role. Admin,\n Maintainer and User. Admin are allowed to do everything. Maintainer are\n allow to browse and delete repo. Users are only allowed to browse. #94\n * Add \"Powered by\" in the web interface footer #91\n * Display a nice error message when trying to delete admin user #93\n * Introduce usage of wtforms and flash in admin users for better form validation. #96 #97\n * Update French translation", "## 1.3.2 (2020-04-23)", "This minor releases fixed issues found while testing release 1.3.0.", " * Fix lookup of executable rdiff-backup and rdiffweb-restore to search in current virtualenv first\n * Fix repository view when multiple repo path are conflicting\n * Fix logging of rdiffweb-restore subprocess", "## 1.3.1 (2020-04-10)", "This minor release enforces security of the password stored in rdiffweb database to make use of a better encryption using SSHA.\nOnly new passwords will make use of the SSHA scheme.", " * Enforce password encryption by using SSHA scheme #88", "## 1.3.0 (2020-04-07)", "This release focuses on improving the restore of big archives. The download should be much faster to start. Major enhancement was made to offload the processing outside the web server. And all of this is still compatible with rdiff-backup v1.2.8 and the latest v2.0.0.", " * Restore file and folder in a subprocess to make the download start faster\n * Fix encoding of archive on Python3.6 (CentOS 7) by using PAX format\n * Add support to restore files and folders using rdiff-backup2\n * Remove obsolete dependencies `pysqlite2`\n * Fix issue creating duplicate entries of repository in the database", "## 1.2.2 (2020-03-05)", "This release provides little improvement to the v1.2.x including official support of rdiff-backup v2.0.0.", " * Enhance the repository to invite users to refresh the repository when the view is empty.\n * Support rdiff-backup v2.0.0\n * Deprecate support for cherrypy 4, 5, 6 and 7\n * Improve loading of repository data (cache status and entries)\n * Restore compatibility with SQLite 3.7 (CentOS7)", "Known issues:", " * Filename encoding in tar.gz and zip file might not be accurate if you are running Python 3.6 (CentOS7)", "\n## 1.2.1 (2020-02-08)", "Little bug fix following the previous release", " * Fix 404 error when trying to access other users repo as admin\n * Fix logging format for cherrypy logs to matches rdiffweb format\n * Add log rotation by default", "## 1.2.0 (2020-01-30)", "This release focus on improving the database layers for better extendability to add more type of data and to support more databases backend like postgresql in the near future.", " * Add explicit testing for Debian Stretch & Buster\n * Change the persistence layers\n * Minimize number of SQL queries\n * Add object lazy loading\n * Add object data caching\n * Fix bugs with SQLite <= 3.16 (Debian Stretch)", "## 1.1.0 (2019-10-31)", "This release focus on improving the admin area and building the fundation for repository access control list (ACL).", " * Update documentation from PDSL web site\n * Improve the navigation bar layout\n * Update the login page headline\n * Update jinja2 version to allow 2.10.x\n * Show server log in admin area\n * Reduce code smell\n * Add System information in admin area\n * Validate credential using local database before LDAP\n * Reffactoring templates macros\n * Enhance user's view search bar\n * Change repository URL to username/repopath\n * Add System information in admin area\n * Improve testcases\n * Clean-up obsolete code\n * Fix issue with captital case encoding name\n * Fix compilation of less files\n * Fix google font import", "## 1.0.3 (2019-10-04)\n * Removing the auto update repos", "## 1.0.2 (2019-10-01)\n * Create \"admin\" user if missing\n * Update french translation", "## 1.0.1 (2019-09-22)\n * Update installation documentation \n * Fix removal of SSH Key\n * Return meaningful error to the user trying to add an existing SSH key", "## 1.0.0 (2019-09-11)\n * Make repository removal more robust\n * Improve performance of librdiff\n * Add new RESTful api\n * Return the right HTTP 401 or 402 error code for authentication\n * Fix bug introduce by upgrade to Jinja2 + python3\n * Store ssh keys in database and disk\n * Add support for theme (default, orange)\n * Remove deprecated profiling code\n * Add disk usage support / quota\n * Add support of cherrypy v18\n * Drop support of cherrypy v3.2.2\n * Add wsgi entry point\n * Replace the plugins architecture to ease implementation\n * Numerous bug fixes", "## 0.10.9 (2019-05-22)\n * Better error handling when error.log file are not valid gzip file" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [135, 159, 210], "buggy_code_start_loc": [135, 90, 85], "filenames": ["README.md", "rdiffweb/controller/page_pref_general.py", "rdiffweb/controller/tests/test_page_prefs_general.py"], "fixing_code_end_loc": [137, 171, 231], "fixing_code_start_loc": [136, 91, 85], "message": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB8BEAE7-49D4-46D5-86FD-BBB48BA14234", "versionEndExcluding": null, "versionEndIncluding": "2.4.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "E967F2E5-0F47-436B-9DC7-4F8D051F5615", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "039D2014-4F4C-4B3F-81B1-EFA08EE3D513", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "37EFE887-5C53-48EA-974C-25F36D6014EC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4."}, {"lang": "es", "value": "Unos Requisitos de Contrase\u00f1a D\u00e9biles en el repositorio de GitHub ikus060/rdiffweb versiones anteriores a 2.5.0a4"}], "evaluatorComment": null, "id": "CVE-2022-3376", "lastModified": "2022-10-12T02:58:12.453", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-10-06T18:16:21.107", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/a9021e93-6d18-4ac1-98ce-550c4697a4ed"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-521"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-521"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, "type": "CWE-521"}
24
Determine whether the {function_name} code is vulnerable or not.
[ "![Rdiffweb Banner](https://gitlab.com/ikus-soft/rdiffweb/-/raw/master/doc/_static/banner.png)", "<p align=\"center\">\n<strong>\n<a href=\"https://www.rdiffweb.org\">website</a>\nβ€’ <a href=\"https://www.ikus-soft.com/archive/rdiffweb/doc/latest/html/\">docs</a>\nβ€’ <a href=\"https://groups.google.com/d/forum/rdiffweb\">community</a>\nβ€’ <a href=\"https://rdiffweb-demo.ikus-soft.com/\">demo</a>\n</strong>\n</p>", "<p align=\"center\">\n<a href=\"LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/github/license/ikus060/rdiffweb\"></a>\n<a href=\"https://gitlab.com/ikus-soft/rdiffweb/pipelines\"><img alt=\"Build\" src=\"https://gitlab.com/ikus-soft/rdiffweb/badges/master/pipeline.svg\"></a>\n<a href=\"https://sonar.ikus-soft.com/dashboard?id=rdiffweb\"><img alt=\"Quality Gate Minarca Client\" src=\"https://sonar.ikus-soft.com/api/project_badges/measure?project=rdiffweb&metric=alert_status\"></a>\n<a href=\"https://sonar.ikus-soft.com/dashboard?id=rdiffweb\"><img alt=\"Coverage\" src=\"https://sonar.ikus-soft.com/api/project_badges/measure?project=rdiffweb&metric=coverage\"></a>\n</p>", "<h1 align=\"center\">\nWelcome to Rdiffweb\n</h1>", "Rdiffweb is a web application that allows you to view repositories generated\nby [rdiff-backup](https://rdiff-backup.net/). The purpose of this\napplication is to ease the management of backups and quickly restore your data\nwith a rich and powerful web interface.", "Rdiffweb is written in Python and is released as open source project under the \nGNU GENERAL PUBLIC LICENSE (GPL). All source code and documentation are\nCopyright Rdiffweb contributors.", "Rdiffweb is actively developed by [IKUS Soft](https://www.ikus-soft.com/)\nsince November 2014.", "The Rdiffweb source code is hosted on [Gitlab](https://gitlab.com/ikus-soft/rdiffweb)\nand mirrored to [Github](https://github.com/ikus060/rdiffweb).", "The Rdiffweb website is https://rdiffweb.org/.", "## Features", "With its rich web interface Rdiffweb provide a notable list of features:", " * Browse your backup\n * Restore single file or multiple files as an archived\n * Users authentication via local database and LDAP\n * Users authorization\n * Email notification when backup is not successful\n * Configurable repository encoding\n * Configurable retention period\n * Backup statistics visualization using graphs\n * SSH Keys management\n * Disk quota visualization\n * File and folder deletion", "## Demo", "If you quickly want to check how Rdiffweb is behaving, you may try our demo server hosted on:", "[https://rdiffweb-demo.ikus-soft.com/](https://rdiffweb-demo.ikus-soft.com/)", "Use the following credential to login:", " * Username: admin\n * Password: admin123", "## Installation & Docker usage", "For detailed installation steps, read the [Installation documentation](https://www.ikus-soft.com/archive/rdiffweb/doc/latest/html/installation.html).", "## Current Build Status", "[![Build Status](https://gitlab.com/ikus-soft/rdiffweb/badges/master/pipeline.svg)](https://gitlab.com/ikus-soft/rdiffweb/pipelines)", "## Download", "You should read the [Documentation](https://www.ikus-soft.com/archive/rdiffweb/doc/latest/html/index.html) to properly install Rdiffweb in your environment.", "**Docker**", " docker pull ikus060/rdiffweb\n \n**Debian**", " curl -L https://www.ikus-soft.com/archive/rdiffweb/public.key | apt-key add - \n echo \"deb https://nexus.ikus-soft.com/repository/apt-release-bullseye/ bullseye main\" > /etc/apt/sources.list.d/rdiffweb.list\n apt update\n apt install rdiffweb", "**Pypi**", " pip install rdiffweb", "## Support", "### Mailing list", "Rdiffweb users should use the [Rdiffweb mailing list](https://groups.google.com/forum/#!forum/rdiffweb).", "### Bug Reports", "Bug reports should be reported on the Rdiffweb Gitlab at https://gitlab.com/ikus-soft/rdiffweb/-/issues", "### Professional support", "Professional support for Rdiffweb is available by contacting [IKUS Soft](https://www.ikus-soft.com/en/support/#form).", "# Changelog", "## Next Release - 2.5.0", "This next release focus on two-factor-authentication as a measure to increase security of user's account.", "* Store User's session information into database\n* Update ldap plugin to load additional attributes from LDAP server\n* Improve `/status` page error handling when `session_statistics` cannot be read\n* Add support for Ubuntu Jammy\n* Upgrade from Bootstrap v3 to v4 #204\n* Replace Fontello by Font-Awesome v4\n* Use CSS variables `var()` to customize themes\n* Remove usage of Jquery.validate\n* Replace custom timsort by jquery DataTables #205\n* Add Active Session managements #203\n * Active session should be visible in user's profiles\n * Active session may be revoked by user\n * Active session should be visible in administration view\n * Action session may be revoke by administrator\n * Show number of active users within the last 24 hours in dashboard\n* Handle migration of older Rdiffweb database by adding the missing `repos.Encoding`, `repos.keepdays` and `users.role` columns #185\n* Replace deprecated references of `disutils.spawn.find_executable()` by `shutil.which()` #208\n* Add two-factor authentication with email verification #201\n* Generate a new session on login and 2FA #220\n* Enforce permission on /etc/rdiffweb configuration folder\n* Enforce validation on fullname, username and email\n* Limit incorrect attempts to change the user's password to prevent brute force attacks #225 [CVE-2022-3273](https://nvd.nist.gov/vuln/detail/CVE-2022-3273)", "* Enforce password policy new password cannot be set as new password [CVE-2022-3376](https://nvd.nist.gov/vuln/detail/CVE-2022-3376)", "\nBreaking changes:", "* Drop Ubuntu Hirsute & Impish (End-of-life)\n* `session-dir` is deprecated and should be replace by `rate-limit-dir`. User's session are stored in database.\n* previous `.css` customization are not barkward compatible", "## 2.4.10 (2022-10-03)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Mitigate path traversal vulnerability [CVE-2022-3389](https://nvd.nist.gov/vuln/detail/CVE-2022-3389)", "## 2.4.9 (2022-09-28)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Add `Cache-Control` and other security headers [CVE-2022-3292](https://nvd.nist.gov/vuln/detail/CVE-2022-3292)\n* Enforce password policy using `password-score` based on [zxcvbn](https://github.com/dropbox/zxcvbn) [CVE-2022-3326](https://nvd.nist.gov/vuln/detail/CVE-2022-3326)", "## 2.4.8 (2022-09-26)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Clean-up invalid path on error page\n* Limit username field length [CVE-2022-3290](https://nvd.nist.gov/vuln/detail/CVE-2022-3290)\n* Limit user's email field length [CVE-2022-3272](https://nvd.nist.gov/vuln/detail/CVE-2022-3272)\n* Limit user's root directory field length [CVE-2022-3295](https://nvd.nist.gov/vuln/detail/CVE-2022-3295)\n* Limit SSH Key title field length [CVE-2022-3298](https://nvd.nist.gov/vuln/detail/CVE-2022-3298)", "## 2.4.7 (2002-09-21)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Generate a new session on login and 2FA #220 [CVE-2022-3269](https://nvd.nist.gov/vuln/detail/CVE-2022-3269)\n* Mitigate CSRF on user's settings #221 [CVE-2022-3274](https://nvd.nist.gov/vuln/detail/CVE-2022-3274)", "## 2.4.6 (2022-09-20)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Support MarkupSafe<3 for Debian bookworm\n* Mitigate CSRF on user's notification settings #216 [CVE-2022-3233](https://nvd.nist.gov/vuln/detail/CVE-2022-3233)\n* Mitigate CSRF on repository settings #217 [CVE-2022-3267](https://nvd.nist.gov/vuln/detail/CVE-2022-3267)\n* Use 'Secure' Attribute with Sensitive Cookie in HTTPS Session on HTTP Error #218 [CVE-2022-3174](https://nvd.nist.gov/vuln/detail/CVE-2022-3174)", "## 2.4.5 (2002-09-16)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Mitigate CSRF on repository deletion and user deletion [CVE-2022-3232](https://nvd.nist.gov/vuln/detail/CVE-2022-3232) #214 #215", "## 2.4.4 (2002-09-15)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Use `X-Real-IP` to identify client IP address to mitigate Brute-Force attack #213", "## 2.4.3 (2022-09-14)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Mitigate CSRF in profile's SSH Keys [CVE-2022-3221](https://nvd.nist.gov/vuln/detail/CVE-2022-3221) #212", "## 2.4.2 (2022-09-12)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Use 'Secure' Attribute with Sensitive Cookie in HTTPS Session. [CVE-2022-3174](https://nvd.nist.gov/vuln/detail/CVE-2022-3174) #209\n* Avoid leakage of the stack trace in the default error page. [CVE-2022-3175](https://nvd.nist.gov/vuln/detail/CVE-2022-3175) #210\n* Enforce minimum and maximum password length [CVE-2022-3175](https://nvd.nist.gov/vuln/detail/CVE-2022-3179) #211", "## 2.4.1 (2022-09-08)", "This releases include a security fix. If you are using an earlier version, you should upgrade to this release immediately.", "* Add Clickjacking Defense [CVE-2022-3167](https://nvd.nist.gov/vuln/detail/CVE-2022-3167)\n* Drop Ubuntu Hirsute & Impish (End-of-life)", "## 2.4.0 (2022-06-21)", "This new release brings a lot of improvement since the last version, multiple bug fixes\nto make the application stable. A couple of new features to improve the overall\nusability and a new security feature to block a brute force attack.", "* Add RateLimit to login page and API to mitigate robots attacks #167\n* Send email notification only if `email-sender` option is defined to avoid raising exception in logs #176\n* Support file restore cancellation without leaving `rdiffweb-restore` process in `<defunct>` state #174\n* Replace `python-ldap` by `ldap3` a pure python implementation to avoid dependencies on `sasl` and `ldap` binaries #186\n* Reffactor core module to allow better extendability and reusability #183\n* Add support for Debian Bookworm #180\n* Add support for Ubuntu Impish #175\n* Add rdiff-backup version to administration view\n* Run unit test during Debian build package\n* Refresh repository list automatically when required #188 #189\n* Fix error 500 displayed in status page #191\n* Improve repository browsing speed by minimizing the number of I/O call #192\n* Publish Docker image directly to DockerHub #144\n* Add REST API to manage sshkeys", "Breaking changes:", "* Ldap Password changes is not supported anymore.\n* Ldap Check Shadow expire config is not supported anymore. It should be replace by a custom filter.\n* Drop CentOS 7 and CentOS 8 support", "## 2.3.9 (2022-01-05)", "Maintenance release to fix minor issues", "* Improve date parsing for `backup.log` to avoid printing exception in logs #170\n* Return HTTP error 403 for invalid symlink to avoid returning a misleading HTTP 500 Server Error #168\n* Show a user friendly error message when trying to create a new user with an existing username #169\n* Handle repository without last-backup date during the notification process to ensure notifications are sent #171\n* Replace CherryPy `storage_type` by `storage_class` to avoid warning in logs\n* Update code to avoid deprecation warning where applicable\n* Add Flake8 validation to improve code quality\n* Remove Ubuntu Groovy support", "## 2.3.8 (2021-12-01)", "* Push all artefacts to nexus server including binaries and documentation\n* Fix `Chart.js` loading on Debian bullseye #164\n* Update installation steps documentation\n* Improve LDAP authentication to lookup entire directory\n* Fix usage of `--ldap-add-user-default-userroot` to avoid error related to wrong encoding\n* Improve authentication mechanics\n* Avoid raising an HTTP error 500 when login form receive invalid payload\n* Mitigate open redirect vulnerability in login form", "## 2.3.7 (2021-10-21)", " * To avoid backward compatibility issue, revert CSRF Token validation\n * Mitigate CSRF vulnerability using cookies with `SameSite=Lax`\n * Mitigate CSRF vulnerability by validating the `Origin` header when a form is submited\n * Improve usage of WTForm for all form validation\n * Update installation stepd for debian #162\n * Build Ubuntu packages and publish them to our APT repo", "## 2.3.6 (2021-10-20)", " * Broken build", "## 2.3.5 (2021-10-18)", " * Mitigate CSRF vulnerability to user, ssh and repo management with CSRF Token", "## 2.3.4 (2021-09-20)", " * Skip email notification if `email-host` configuration is not provided #157\n * Skip email notification when the new attribute value has the same value #159\n * USE LDAP `mail` attribute when creating new user from LDAP directory #156", "## 2.3.3 (2021-09-10)", " * Provide a new theme `blue` to match IKUS Soft colors #158", "## 2.3.2 (2021-09-07)", " * Automatically update user's repository list based on user's home directory", "## 2.3.1 (2021-07-14)", " * Update default `session-dir` location to `/var/lib/rdiffweb/session` to avoid using `/var/run` #148", "## 2.3.0 (2021-07-06)", " * Improve timezone handling to display date with local timezone using javascript #143\n * Improve charts by replacing d3js by chartkick #122\n * Replace the status view by something meaningful with chartkick #122\n * Provide Docker image with Rdiffweb `docker pull ikus060/rdiffweb` #55\n * Fix file and folder sorting #143", "## 2.2.0 (2021-05-11)\n \n * Debian package:\n * Add rdiff-backup as dependencies to comply with Debian packaging rules\n * Multiple other fixed to control files\n * Use debhelper-compat (= 13)\n * Use debhelper-compat (= 13)\n * Run test during packaging\n * Create default folder `/var/run/rdiffweb/sessions` to store user session\n * Use ConfigArgPare for configuration to support configuration file, environment variables and arguments to configure rdiffweb #114\n * Fix cache in localization module\n * Add `ldap-add-default-role` and `ldap-add-default-userroot` option to define default value for role and user root when creating user from LDAP #125\n * Support PostgreSQL database by replacing our storage layer by SQLAlchemy #126\n * Fix to retrieve user quota only for valid user_root #135\n * Add option `disable-ssh-keys` to disable SSH Key management\n * Use absolute URL everywhere\n * Add support for `X-Forwarded-For`, `X-Forwarded-proto` and other reverse proxy header when generating absolute URL\n * Drop Debian Stretch support\n * Implement a new background scheduler using apscheduler #82\n * Use background job to send email notification to avoid blocking web page loading #47\n * Use background job to delete repository to avoid blocking web page loading #48\n * Allow deleting a specific file or folder from the history using `rdiff-backup-delete` #128\n * Improve support for `session-dir` #131\n * Add option `admin-password` to define administrator password for better security\n * Improve performance of repository browsing \n * Add a new view to display logs of a specific repository\n * Allow downloading the log\n * Define a default limit to graph statistics to make it display faster\n * Fix `get-quota-cmd` option to properly return a value", "## 2.1.0 (2021-01-15)", "* Debian package: Remove dh-systemd from Debian build dependencies (https://bugs.debian.org/871312we)\n* Improve Quota management:\n * `QuotaSetCmd`, `QuotaGetCmd` and `QuotaUsedCmd` options could be used to customize how to set the quota for your environment.\n * Display user's quota in User View\n * Display user's quota in Admin View\n * Allow admin to update user quota from Admin View when `QuotaSetCmd` is defined.\n * Allow admin to define user quota using human readable value (e.g.: GiB, TiB, etc.)\n * Improve logging around quota management\n* Improve robustness when service is starting\n* Improve robustness when repository has wrong permission defined (e.g.: when some files not readable)\n* Add user id in Admin view\n* Replace `UserObject(1)` by the actual username in log file to improve debugging", "## 2.0.0 (2020-12-04)", "* Re-implement logic to update repositories views to remove duplicates and avoid nesting repo. #107\n* Handle elapsed time of days in the graph. Thanks [Nathaniel van Diepen](https://github.com/Eeems) contributions.\n* Rebrand all link to ikus-soft.com\n* Update documentation to install rdiffweb\n* Remove obsolete minify dependency\n* Drop support for python2\n* Provide null translation if translation catalogues are not found\n* Pass a LANG environment variable to rdiff-backup restore process to fix encoding issue #112\n* Remove obsolete python shebang\n* Remove execution bit (+x) on python modules\n* Provide `--help` and `--version` on `rdiffweb` executable\n* Improve cherrypy version detection\n* Do not update translation files (.mo) during build", "## 1.5.0 (2020-06-24)", "This minor release introduce official support of rdiffweb on Debian Bullseye. It also includes some usability improvements.", " * Change formatting of Last Backup date for \"Updated 3 weeks ago\" to ease the readability\n * Add support for Debian Bullseye\n * Add support for Python 3.8 (#104)\n * Add warning in the users list view when a root directory is invalid (#30)\n * Add options to control search depthness (#1)\n * Print a warning in the log when the \"DefaultTheme\" value is not valid (#90)", "## 1.4.0 (2020-05-20)", "Thanks to our sponsor, this release introduce a feature to have better control over the user's permission by defining 3 different levels of privilege: Admin, Maintainer and User. This addition allows you to have better control on what your users can or can't do.", " * Fix single repository discovery when a user's home is a rdiff-backup repository\n * [SPONSORED] Add a new setting at the user level to define the user's role. Admin,\n Maintainer and User. Admin are allowed to do everything. Maintainer are\n allow to browse and delete repo. Users are only allowed to browse. #94\n * Add \"Powered by\" in the web interface footer #91\n * Display a nice error message when trying to delete admin user #93\n * Introduce usage of wtforms and flash in admin users for better form validation. #96 #97\n * Update French translation", "## 1.3.2 (2020-04-23)", "This minor releases fixed issues found while testing release 1.3.0.", " * Fix lookup of executable rdiff-backup and rdiffweb-restore to search in current virtualenv first\n * Fix repository view when multiple repo path are conflicting\n * Fix logging of rdiffweb-restore subprocess", "## 1.3.1 (2020-04-10)", "This minor release enforces security of the password stored in rdiffweb database to make use of a better encryption using SSHA.\nOnly new passwords will make use of the SSHA scheme.", " * Enforce password encryption by using SSHA scheme #88", "## 1.3.0 (2020-04-07)", "This release focuses on improving the restore of big archives. The download should be much faster to start. Major enhancement was made to offload the processing outside the web server. And all of this is still compatible with rdiff-backup v1.2.8 and the latest v2.0.0.", " * Restore file and folder in a subprocess to make the download start faster\n * Fix encoding of archive on Python3.6 (CentOS 7) by using PAX format\n * Add support to restore files and folders using rdiff-backup2\n * Remove obsolete dependencies `pysqlite2`\n * Fix issue creating duplicate entries of repository in the database", "## 1.2.2 (2020-03-05)", "This release provides little improvement to the v1.2.x including official support of rdiff-backup v2.0.0.", " * Enhance the repository to invite users to refresh the repository when the view is empty.\n * Support rdiff-backup v2.0.0\n * Deprecate support for cherrypy 4, 5, 6 and 7\n * Improve loading of repository data (cache status and entries)\n * Restore compatibility with SQLite 3.7 (CentOS7)", "Known issues:", " * Filename encoding in tar.gz and zip file might not be accurate if you are running Python 3.6 (CentOS7)", "\n## 1.2.1 (2020-02-08)", "Little bug fix following the previous release", " * Fix 404 error when trying to access other users repo as admin\n * Fix logging format for cherrypy logs to matches rdiffweb format\n * Add log rotation by default", "## 1.2.0 (2020-01-30)", "This release focus on improving the database layers for better extendability to add more type of data and to support more databases backend like postgresql in the near future.", " * Add explicit testing for Debian Stretch & Buster\n * Change the persistence layers\n * Minimize number of SQL queries\n * Add object lazy loading\n * Add object data caching\n * Fix bugs with SQLite <= 3.16 (Debian Stretch)", "## 1.1.0 (2019-10-31)", "This release focus on improving the admin area and building the fundation for repository access control list (ACL).", " * Update documentation from PDSL web site\n * Improve the navigation bar layout\n * Update the login page headline\n * Update jinja2 version to allow 2.10.x\n * Show server log in admin area\n * Reduce code smell\n * Add System information in admin area\n * Validate credential using local database before LDAP\n * Reffactoring templates macros\n * Enhance user's view search bar\n * Change repository URL to username/repopath\n * Add System information in admin area\n * Improve testcases\n * Clean-up obsolete code\n * Fix issue with captital case encoding name\n * Fix compilation of less files\n * Fix google font import", "## 1.0.3 (2019-10-04)\n * Removing the auto update repos", "## 1.0.2 (2019-10-01)\n * Create \"admin\" user if missing\n * Update french translation", "## 1.0.1 (2019-09-22)\n * Update installation documentation \n * Fix removal of SSH Key\n * Return meaningful error to the user trying to add an existing SSH key", "## 1.0.0 (2019-09-11)\n * Make repository removal more robust\n * Improve performance of librdiff\n * Add new RESTful api\n * Return the right HTTP 401 or 402 error code for authentication\n * Fix bug introduce by upgrade to Jinja2 + python3\n * Store ssh keys in database and disk\n * Add support for theme (default, orange)\n * Remove deprecated profiling code\n * Add disk usage support / quota\n * Add support of cherrypy v18\n * Drop support of cherrypy v3.2.2\n * Add wsgi entry point\n * Replace the plugins architecture to ease implementation\n * Numerous bug fixes", "## 0.10.9 (2019-05-22)\n * Better error handling when error.log file are not valid gzip file" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [135, 159, 210], "buggy_code_start_loc": [135, 90, 85], "filenames": ["README.md", "rdiffweb/controller/page_pref_general.py", "rdiffweb/controller/tests/test_page_prefs_general.py"], "fixing_code_end_loc": [137, 171, 231], "fixing_code_start_loc": [136, 91, 85], "message": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB8BEAE7-49D4-46D5-86FD-BBB48BA14234", "versionEndExcluding": null, "versionEndIncluding": "2.4.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "E967F2E5-0F47-436B-9DC7-4F8D051F5615", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "039D2014-4F4C-4B3F-81B1-EFA08EE3D513", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "37EFE887-5C53-48EA-974C-25F36D6014EC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4."}, {"lang": "es", "value": "Unos Requisitos de Contrase\u00f1a D\u00e9biles en el repositorio de GitHub ikus060/rdiffweb versiones anteriores a 2.5.0a4"}], "evaluatorComment": null, "id": "CVE-2022-3376", "lastModified": "2022-10-12T02:58:12.453", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-10-06T18:16:21.107", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/a9021e93-6d18-4ac1-98ce-550c4697a4ed"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-521"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-521"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, "type": "CWE-521"}
24
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n# rdiffweb, A web interface to rdiff-backup repositories\n# Copyright (C) 2012-2021 rdiffweb contributors\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nDefault preference page to show general user information. It allows user\nto change password ans refresh it's repository view.\n\"\"\"", "import cherrypy\nfrom wtforms.fields import HiddenField, PasswordField, StringField, SubmitField\nfrom wtforms.fields.html5 import EmailField\nfrom wtforms.validators import DataRequired, EqualTo, InputRequired, Length, Optional, Regexp", "from rdiffweb.controller import Controller, flash\nfrom rdiffweb.controller.form import CherryForm\nfrom rdiffweb.core.model import UserObject\nfrom rdiffweb.tools.i18n import gettext_lazy as _", "# Maximum number of password change attempt before logout\nCHANGE_PASSWORD_MAX_ATTEMPT = 5\nCHANGE_PASSWORD_ATTEMPTS = 'change_password_attempts'", "\nclass UserProfileForm(CherryForm):\n action = HiddenField(default='set_profile_info')\n username = StringField(_('Username'), render_kw={'readonly': True})\n fullname = StringField(\n _('Fullname'),\n validators=[\n Optional(),\n Length(max=256, message=_('Fullname too long.')),\n Regexp(UserObject.PATTERN_FULLNAME, message=_('Must not contain any special characters.')),\n ],\n )\n email = EmailField(\n _('Email'),\n validators=[\n DataRequired(),\n Length(max=256, message=_(\"Email too long.\")),\n Regexp(UserObject.PATTERN_EMAIL, message=_(\"Must be a valid email address.\")),\n ],\n )\n set_profile_info = SubmitField(_('Save changes'))", " def is_submitted(self):\n # Validate only if action is set_profile_info\n return super().is_submitted() and self.action.data == 'set_profile_info'", " def populate_obj(self, user):\n user.fullname = self.fullname.data\n user.email = self.email.data\n user.add()", "\nclass UserPasswordForm(CherryForm):\n action = HiddenField(default='set_password')\n current = PasswordField(\n _('Current password'),\n validators=[InputRequired(_(\"Current password is missing.\"))],\n description=_(\"You must provide your current password in order to change it.\"),\n )\n new = PasswordField(\n _('New password'),\n validators=[\n InputRequired(_(\"New password is missing.\")),\n EqualTo('confirm', message=_(\"The new password and its confirmation do not match.\")),\n ],\n )\n confirm = PasswordField(\n _('Confirm new password'), validators=[InputRequired(_(\"Confirmation password is missing.\"))]\n )\n set_password = SubmitField(_('Update password'))", " def is_submitted(self):\n # Validate only if action is set_profile_info\n return super().is_submitted() and self.action.data == 'set_password'\n", "", " def populate_obj(self, user):\n # Check if current password is \"valid\" if Not, rate limit the\n # number of attempts and logout user after too many invalid attempts.\n if not user.validate_password(self.current.data):\n cherrypy.session[CHANGE_PASSWORD_ATTEMPTS] = cherrypy.session.get(CHANGE_PASSWORD_ATTEMPTS, 0) + 1\n attempts = cherrypy.session[CHANGE_PASSWORD_ATTEMPTS]\n if attempts >= CHANGE_PASSWORD_MAX_ATTEMPT:\n cherrypy.session.clear()\n cherrypy.session.regenerate()\n flash(\n _(\"You were logged out because you entered the wrong password too many times.\"),\n level='warning',\n )\n raise cherrypy.HTTPRedirect('/login/')", " flash(_(\"Wrong current password.\"), level='warning')\n else:\n # Clear number of attempts\n if CHANGE_PASSWORD_ATTEMPTS in cherrypy.session:\n del cherrypy.session[CHANGE_PASSWORD_ATTEMPTS]\n # If Valid, update password\n try:\n user.set_password(self.new.data)\n flash(_(\"Password updated successfully.\"), level='success')\n except ValueError as e:\n flash(str(e), level='warning')", "", "class RefreshForm(CherryForm):\n action = HiddenField(default='update_repos')\n update_repos = SubmitField(\n _('Refresh repositories'),\n description=_(\n \"Refresh the list of repositories associated to your account. If you recently add a new repository and it doesn't show, you may try to refresh the list.\"\n ),\n )", " def is_submitted(self):\n # Validate only if action is set_profile_info\n return super().is_submitted() and self.action.data == 'update_repos'", " def populate_obj(self, user):\n try:\n user.refresh_repos(delete=True)\n flash(_(\"Repositories successfully updated\"), level='success')\n except ValueError as e:\n flash(str(e), level='warning')", "\nclass PagePrefsGeneral(Controller):\n \"\"\"\n Plugin to change user profile and password.\n \"\"\"", " @cherrypy.expose\n def default(self, **kwargs):\n # Process the parameters.\n profile_form = UserProfileForm(obj=self.app.currentuser)\n password_form = UserPasswordForm()\n refresh_form = RefreshForm()\n if profile_form.is_submitted():\n if profile_form.validate():\n profile_form.populate_obj(self.app.currentuser)\n flash(_(\"Profile updated successfully.\"), level='success')", "", " else:\n flash(profile_form.error_message, level='error')\n elif password_form.is_submitted():\n if password_form.validate():", " password_form.populate_obj(self.app.currentuser)", " else:\n flash(password_form.error_message, level='error')\n elif refresh_form.is_submitted():\n if refresh_form.validate():\n refresh_form.populate_obj(self.app.currentuser)\n else:\n flash(refresh_form.error_message, level='error')\n params = {\n 'profile_form': profile_form,\n 'password_form': password_form,\n 'refresh_form': refresh_form,\n }\n return self._compile_template(\"prefs_general.html\", **params)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [135, 159, 210], "buggy_code_start_loc": [135, 90, 85], "filenames": ["README.md", "rdiffweb/controller/page_pref_general.py", "rdiffweb/controller/tests/test_page_prefs_general.py"], "fixing_code_end_loc": [137, 171, 231], "fixing_code_start_loc": [136, 91, 85], "message": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB8BEAE7-49D4-46D5-86FD-BBB48BA14234", "versionEndExcluding": null, "versionEndIncluding": "2.4.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "E967F2E5-0F47-436B-9DC7-4F8D051F5615", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "039D2014-4F4C-4B3F-81B1-EFA08EE3D513", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "37EFE887-5C53-48EA-974C-25F36D6014EC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4."}, {"lang": "es", "value": "Unos Requisitos de Contrase\u00f1a D\u00e9biles en el repositorio de GitHub ikus060/rdiffweb versiones anteriores a 2.5.0a4"}], "evaluatorComment": null, "id": "CVE-2022-3376", "lastModified": "2022-10-12T02:58:12.453", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-10-06T18:16:21.107", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/a9021e93-6d18-4ac1-98ce-550c4697a4ed"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-521"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-521"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, "type": "CWE-521"}
24
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n# rdiffweb, A web interface to rdiff-backup repositories\n# Copyright (C) 2012-2021 rdiffweb contributors\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nDefault preference page to show general user information. It allows user\nto change password ans refresh it's repository view.\n\"\"\"", "import cherrypy\nfrom wtforms.fields import HiddenField, PasswordField, StringField, SubmitField\nfrom wtforms.fields.html5 import EmailField\nfrom wtforms.validators import DataRequired, EqualTo, InputRequired, Length, Optional, Regexp", "from rdiffweb.controller import Controller, flash\nfrom rdiffweb.controller.form import CherryForm\nfrom rdiffweb.core.model import UserObject\nfrom rdiffweb.tools.i18n import gettext_lazy as _", "# Maximum number of password change attempt before logout\nCHANGE_PASSWORD_MAX_ATTEMPT = 5\nCHANGE_PASSWORD_ATTEMPTS = 'change_password_attempts'", "\nclass UserProfileForm(CherryForm):\n action = HiddenField(default='set_profile_info')\n username = StringField(_('Username'), render_kw={'readonly': True})\n fullname = StringField(\n _('Fullname'),\n validators=[\n Optional(),\n Length(max=256, message=_('Fullname too long.')),\n Regexp(UserObject.PATTERN_FULLNAME, message=_('Must not contain any special characters.')),\n ],\n )\n email = EmailField(\n _('Email'),\n validators=[\n DataRequired(),\n Length(max=256, message=_(\"Email too long.\")),\n Regexp(UserObject.PATTERN_EMAIL, message=_(\"Must be a valid email address.\")),\n ],\n )\n set_profile_info = SubmitField(_('Save changes'))", " def is_submitted(self):\n # Validate only if action is set_profile_info\n return super().is_submitted() and self.action.data == 'set_profile_info'", " def populate_obj(self, user):\n user.fullname = self.fullname.data\n user.email = self.email.data\n user.add()", "\nclass UserPasswordForm(CherryForm):\n action = HiddenField(default='set_password')\n current = PasswordField(\n _('Current password'),\n validators=[InputRequired(_(\"Current password is missing.\"))],\n description=_(\"You must provide your current password in order to change it.\"),\n )\n new = PasswordField(\n _('New password'),\n validators=[\n InputRequired(_(\"New password is missing.\")),\n EqualTo('confirm', message=_(\"The new password and its confirmation do not match.\")),\n ],\n )\n confirm = PasswordField(\n _('Confirm new password'), validators=[InputRequired(_(\"Confirmation password is missing.\"))]\n )\n set_password = SubmitField(_('Update password'))", " def is_submitted(self):\n # Validate only if action is set_profile_info\n return super().is_submitted() and self.action.data == 'set_password'\n", " def validate_new(self, field):\n \"\"\"\n Make sure new password if not equals to old password.\n \"\"\"\n if self.new.data and self.new.data == self.current.data:\n raise ValueError(_('The new password must be different from the current password.'))\n", " def populate_obj(self, user):\n # Check if current password is \"valid\" if Not, rate limit the\n # number of attempts and logout user after too many invalid attempts.\n if not user.validate_password(self.current.data):\n cherrypy.session[CHANGE_PASSWORD_ATTEMPTS] = cherrypy.session.get(CHANGE_PASSWORD_ATTEMPTS, 0) + 1\n attempts = cherrypy.session[CHANGE_PASSWORD_ATTEMPTS]\n if attempts >= CHANGE_PASSWORD_MAX_ATTEMPT:\n cherrypy.session.clear()\n cherrypy.session.regenerate()\n flash(\n _(\"You were logged out because you entered the wrong password too many times.\"),\n level='warning',\n )\n raise cherrypy.HTTPRedirect('/login/')", " self.current.errors = [_(\"Wrong current password.\")]\n return False", " # Clear number of attempts\n if CHANGE_PASSWORD_ATTEMPTS in cherrypy.session:\n del cherrypy.session[CHANGE_PASSWORD_ATTEMPTS]", " try:\n user.set_password(self.new.data)\n return True\n except ValueError as e:\n self.new.errors = [str(e)]\n return False", "", "class RefreshForm(CherryForm):\n action = HiddenField(default='update_repos')\n update_repos = SubmitField(\n _('Refresh repositories'),\n description=_(\n \"Refresh the list of repositories associated to your account. If you recently add a new repository and it doesn't show, you may try to refresh the list.\"\n ),\n )", " def is_submitted(self):\n # Validate only if action is set_profile_info\n return super().is_submitted() and self.action.data == 'update_repos'", " def populate_obj(self, user):\n try:\n user.refresh_repos(delete=True)\n flash(_(\"Repositories successfully updated\"), level='success')\n except ValueError as e:\n flash(str(e), level='warning')", "\nclass PagePrefsGeneral(Controller):\n \"\"\"\n Plugin to change user profile and password.\n \"\"\"", " @cherrypy.expose\n def default(self, **kwargs):\n # Process the parameters.\n profile_form = UserProfileForm(obj=self.app.currentuser)\n password_form = UserPasswordForm()\n refresh_form = RefreshForm()\n if profile_form.is_submitted():\n if profile_form.validate():\n profile_form.populate_obj(self.app.currentuser)\n flash(_(\"Profile updated successfully.\"), level='success')", " raise cherrypy.HTTPRedirect(\"\")", " else:\n flash(profile_form.error_message, level='error')\n elif password_form.is_submitted():\n if password_form.validate():", " if password_form.populate_obj(self.app.currentuser):\n flash(_(\"Password updated successfully.\"), level='success')\n raise cherrypy.HTTPRedirect(\"\")", " else:\n flash(password_form.error_message, level='error')\n elif refresh_form.is_submitted():\n if refresh_form.validate():\n refresh_form.populate_obj(self.app.currentuser)\n else:\n flash(refresh_form.error_message, level='error')\n params = {\n 'profile_form': profile_form,\n 'password_form': password_form,\n 'refresh_form': refresh_form,\n }\n return self._compile_template(\"prefs_general.html\", **params)" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [135, 159, 210], "buggy_code_start_loc": [135, 90, 85], "filenames": ["README.md", "rdiffweb/controller/page_pref_general.py", "rdiffweb/controller/tests/test_page_prefs_general.py"], "fixing_code_end_loc": [137, 171, 231], "fixing_code_start_loc": [136, 91, 85], "message": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB8BEAE7-49D4-46D5-86FD-BBB48BA14234", "versionEndExcluding": null, "versionEndIncluding": "2.4.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "E967F2E5-0F47-436B-9DC7-4F8D051F5615", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "039D2014-4F4C-4B3F-81B1-EFA08EE3D513", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "37EFE887-5C53-48EA-974C-25F36D6014EC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4."}, {"lang": "es", "value": "Unos Requisitos de Contrase\u00f1a D\u00e9biles en el repositorio de GitHub ikus060/rdiffweb versiones anteriores a 2.5.0a4"}], "evaluatorComment": null, "id": "CVE-2022-3376", "lastModified": "2022-10-12T02:58:12.453", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-10-06T18:16:21.107", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/a9021e93-6d18-4ac1-98ce-550c4697a4ed"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-521"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-521"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, "type": "CWE-521"}
24
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n# rdiffweb, A web interface to rdiff-backup repositories\n# Copyright (C) 2012-2021 rdiffweb contributors\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nCreated on Dec 26, 2015", "@author: Patrik Dufresne\n\"\"\"", "from unittest.mock import MagicMock", "import cherrypy\nfrom parameterized import parameterized", "import rdiffweb.test\nfrom rdiffweb.core.model import RepoObject, UserObject", "\nclass PagePrefGeneralTest(rdiffweb.test.WebCase):", " PREFS = \"/prefs/general\"", " login = True", " def setUp(self):\n self.listener = MagicMock()\n cherrypy.engine.subscribe('user_password_changed', self.listener.user_password_changed, priority=50)\n return super().setUp()", " def tearDown(self):\n cherrypy.engine.unsubscribe('user_password_changed', self.listener.user_password_changed)\n return super().tearDown()", " def _set_password(\n self,\n current,\n new_password,\n confirm,\n ):\n b = {\n 'action': 'set_password',\n 'current': current,\n 'new': new_password,\n 'confirm': confirm,\n }\n return self.getPage(self.PREFS, method='POST', body=b)", " def _set_profile_info(self, email, fullname=None):\n b = {\n 'action': 'set_profile_info',\n 'email': email,\n }\n if fullname:\n b['fullname'] = fullname\n return self.getPage(self.PREFS, method='POST', body=b)", " def test_get_page(self):\n # When querying the page\n self.getPage(self.PREFS)\n # Then the page is returned\n self.assertStatus(200)\n self.assertInBody('User profile')", " def test_change_username_noop(self):\n # Given an authenticated user\n # When updating the username\n self.getPage(\n self.PREFS,\n method='POST',\n body={'action': 'set_profile_info', 'email': 'test@test.com', 'username': 'test'},\n )", " self.assertStatus(200)", " self.assertInBody(\"Profile updated successfully.\")\n # Then database is updated with fullname\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertIsNotNone(user)\n self.assertEqual(\"test@test.com\", user.email)", " @parameterized.expand(\n [\n # Invalid\n ('@test.com', False),\n ('test.com', False),\n ('test@te_st.com', False),\n ('test@test.com, test2@test.com', False),\n # Valid\n ('test', True),\n ('My Fullname', True),\n ]\n )\n def test_change_fullname(self, new_fullname, expected_valid):\n # Given an authenticated user\n # When update the fullname\n self._set_profile_info(\"test@test.com\", new_fullname)", " self.assertStatus(200)", " if expected_valid:", "", " self.assertInBody(\"Profile updated successfully.\")\n # Then database is updated with fullname\n self.assertInBody(new_fullname)\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertEqual(new_fullname, user.fullname)\n else:", "", " self.assertNotInBody(\"Profile updated successfully.\")", " def test_change_fullname_method_get(self):\n # Given an authenticated user\n # When trying to update full name using GET method\n self.getPage(self.PREFS + '?action=set_profile_info&email=test@test.com')\n # Then nothing happen\n self.assertStatus(200)\n self.assertNotInBody(\"Profile updated successfully.\")\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertEqual(\"\", user.fullname)", " def test_change_fullname_too_long(self):\n # Given an authenticated user\n # When update the fullname\n self._set_profile_info(\"test@test.com\", \"Fullname\" * 50)\n # Then page return with error message\n self.assertStatus(200)\n self.assertNotInBody(\"Profile updated successfully.\")\n self.assertInBody(\"Fullname too long.\")\n # Then database is not updated\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertEqual(\"\", user.fullname)", " def test_change_email(self):\n self._set_profile_info(\"test@test.com\")", " self.assertStatus(200)", " self.assertInBody(\"Profile updated successfully.\")", " @parameterized.expand(\n [\n # Invalid\n ('@test.com', False),\n ('test.com', False),\n ('test', False),\n ('test@te_st.com', False),\n ('test@test.com, test2@test.com', False),\n # Valid\n ('test@test.com', True),\n ]\n )\n def test_change_email_with_invalid_email(self, new_email, expected_valid):\n self._set_profile_info(new_email)", " self.assertStatus(200)", " if expected_valid:", "", " self.assertInBody(\"Profile updated successfully.\")\n self.assertNotInBody(\"Must be a valid email address.\")\n else:", "", " self.assertNotInBody(\"Profile updated successfully.\")\n self.assertInBody(\"Must be a valid email address.\")", " def test_change_email_with_too_long(self):\n self._set_profile_info((\"test1\" * 50) + \"@test.com\")\n self.assertInBody(\"Email too long.\")", " def test_change_password(self):\n self.listener.user_password_changed.reset_mock()\n # When udating user's password\n self._set_password(self.PASSWORD, \"pr3j5Dwi\", \"pr3j5Dwi\")", "", " self.assertInBody(\"Password updated successfully.\")\n # Then a notification is raised\n self.listener.user_password_changed.assert_called_once()", " def test_change_password_with_wrong_confirmation(self):\n self._set_password(self.PASSWORD, \"t\", \"a\")\n self.assertInBody(\"The new password and its confirmation do not match.\")", " def test_change_password_with_wrong_password(self):\n self._set_password(\"oups\", \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertInBody(\"Wrong current password\")", " def test_change_password_with_too_short(self):\n self._set_password(self.PASSWORD, \"short\", \"short\")\n self.assertInBody(\"Password must have between 8 and 128 characters.\")", " def test_change_password_with_too_long(self):\n new_password = 'a' * 129\n self._set_password(self.PASSWORD, new_password, new_password)\n self.assertInBody(\"Password must have between 8 and 128 characters.\")", " def test_change_password_too_many_attemps(self):\n # When udating user's password with wrong current password 5 times\n for _i in range(1, 5):\n self._set_password('wrong', \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertStatus(200)\n self.assertInBody(\"Wrong current password.\")\n # Then user session is cleared and user is redirect to login page\n self._set_password('wrong', \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertStatus(303)\n self.assertHeaderItemValue('Location', self.baseurl + '/login/')\n # Then a warning message is displayed on login page\n self.getPage('/login/')\n self.assertStatus(200)\n self.assertInBody('You were logged out because you entered the wrong password too many times.')\n", "", " def test_change_password_method_get(self):\n # Given an authenticated user\n # Trying to update password with GET method\n self.getPage(self.PREFS + '?action=set_password&new=pr3j5Dwi&confirm=pr3j5Dwi&current=' + self.PASSWORD)\n # Then nothing happen\n self.assertStatus(200)\n self.assertNotInBody(\"Password updated successfully.\")", " def test_invalid_pref(self):\n \"\"\"\n Check if invalid prefs url is 404 Not Found.\n \"\"\"\n self.getPage(\"/prefs/invalid/\")\n self.assertStatus(404)", " def test_update_repos(self):\n # Given a user with invalid repositories\n userobj = UserObject.get_user(self.USERNAME)\n RepoObject(userid=userobj.userid, repopath='invalid').add()\n self.assertEqual(['broker-repo', 'invalid', 'testcases'], sorted([r.name for r in userobj.repo_objs]))\n # When updating the repository list\n self.getPage(self.PREFS, method='POST', body={'action': 'update_repos'})\n self.assertStatus(200)\n # Then a success message is displayed\n self.assertInBody('Repositories successfully updated')\n # Then the list is free of inexisting repos.\n userobj.expire()\n self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in userobj.repo_objs]))" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [135, 159, 210], "buggy_code_start_loc": [135, 90, 85], "filenames": ["README.md", "rdiffweb/controller/page_pref_general.py", "rdiffweb/controller/tests/test_page_prefs_general.py"], "fixing_code_end_loc": [137, 171, 231], "fixing_code_start_loc": [136, 91, 85], "message": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB8BEAE7-49D4-46D5-86FD-BBB48BA14234", "versionEndExcluding": null, "versionEndIncluding": "2.4.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "E967F2E5-0F47-436B-9DC7-4F8D051F5615", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "039D2014-4F4C-4B3F-81B1-EFA08EE3D513", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "37EFE887-5C53-48EA-974C-25F36D6014EC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4."}, {"lang": "es", "value": "Unos Requisitos de Contrase\u00f1a D\u00e9biles en el repositorio de GitHub ikus060/rdiffweb versiones anteriores a 2.5.0a4"}], "evaluatorComment": null, "id": "CVE-2022-3376", "lastModified": "2022-10-12T02:58:12.453", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-10-06T18:16:21.107", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/a9021e93-6d18-4ac1-98ce-550c4697a4ed"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-521"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-521"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, "type": "CWE-521"}
24
Determine whether the {function_name} code is vulnerable or not.
[ "# -*- coding: utf-8 -*-\n# rdiffweb, A web interface to rdiff-backup repositories\n# Copyright (C) 2012-2021 rdiffweb contributors\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\nCreated on Dec 26, 2015", "@author: Patrik Dufresne\n\"\"\"", "from unittest.mock import MagicMock", "import cherrypy\nfrom parameterized import parameterized", "import rdiffweb.test\nfrom rdiffweb.core.model import RepoObject, UserObject", "\nclass PagePrefGeneralTest(rdiffweb.test.WebCase):", " PREFS = \"/prefs/general\"", " login = True", " def setUp(self):\n self.listener = MagicMock()\n cherrypy.engine.subscribe('user_password_changed', self.listener.user_password_changed, priority=50)\n return super().setUp()", " def tearDown(self):\n cherrypy.engine.unsubscribe('user_password_changed', self.listener.user_password_changed)\n return super().tearDown()", " def _set_password(\n self,\n current,\n new_password,\n confirm,\n ):\n b = {\n 'action': 'set_password',\n 'current': current,\n 'new': new_password,\n 'confirm': confirm,\n }\n return self.getPage(self.PREFS, method='POST', body=b)", " def _set_profile_info(self, email, fullname=None):\n b = {\n 'action': 'set_profile_info',\n 'email': email,\n }\n if fullname:\n b['fullname'] = fullname\n return self.getPage(self.PREFS, method='POST', body=b)", " def test_get_page(self):\n # When querying the page\n self.getPage(self.PREFS)\n # Then the page is returned\n self.assertStatus(200)\n self.assertInBody('User profile')", " def test_change_username_noop(self):\n # Given an authenticated user\n # When updating the username\n self.getPage(\n self.PREFS,\n method='POST',\n body={'action': 'set_profile_info', 'email': 'test@test.com', 'username': 'test'},\n )", " self.assertStatus(303)\n self.getPage(self.PREFS)", " self.assertInBody(\"Profile updated successfully.\")\n # Then database is updated with fullname\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertIsNotNone(user)\n self.assertEqual(\"test@test.com\", user.email)", " @parameterized.expand(\n [\n # Invalid\n ('@test.com', False),\n ('test.com', False),\n ('test@te_st.com', False),\n ('test@test.com, test2@test.com', False),\n # Valid\n ('test', True),\n ('My Fullname', True),\n ]\n )\n def test_change_fullname(self, new_fullname, expected_valid):\n # Given an authenticated user\n # When update the fullname\n self._set_profile_info(\"test@test.com\", new_fullname)", "", " if expected_valid:", " self.assertStatus(303)\n self.getPage(self.PREFS)", " self.assertInBody(\"Profile updated successfully.\")\n # Then database is updated with fullname\n self.assertInBody(new_fullname)\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertEqual(new_fullname, user.fullname)\n else:", " self.assertStatus(200)", " self.assertNotInBody(\"Profile updated successfully.\")", " def test_change_fullname_method_get(self):\n # Given an authenticated user\n # When trying to update full name using GET method\n self.getPage(self.PREFS + '?action=set_profile_info&email=test@test.com')\n # Then nothing happen\n self.assertStatus(200)\n self.assertNotInBody(\"Profile updated successfully.\")\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertEqual(\"\", user.fullname)", " def test_change_fullname_too_long(self):\n # Given an authenticated user\n # When update the fullname\n self._set_profile_info(\"test@test.com\", \"Fullname\" * 50)\n # Then page return with error message\n self.assertStatus(200)\n self.assertNotInBody(\"Profile updated successfully.\")\n self.assertInBody(\"Fullname too long.\")\n # Then database is not updated\n user = UserObject.query.filter(UserObject.username == self.USERNAME).first()\n self.assertEqual(\"\", user.fullname)", " def test_change_email(self):\n self._set_profile_info(\"test@test.com\")", " self.assertStatus(303)\n self.getPage(self.PREFS)", " self.assertInBody(\"Profile updated successfully.\")", " @parameterized.expand(\n [\n # Invalid\n ('@test.com', False),\n ('test.com', False),\n ('test', False),\n ('test@te_st.com', False),\n ('test@test.com, test2@test.com', False),\n # Valid\n ('test@test.com', True),\n ]\n )\n def test_change_email_with_invalid_email(self, new_email, expected_valid):\n self._set_profile_info(new_email)", "", " if expected_valid:", " self.assertStatus(303)\n self.getPage(self.PREFS)", " self.assertInBody(\"Profile updated successfully.\")\n self.assertNotInBody(\"Must be a valid email address.\")\n else:", " self.assertStatus(200)", " self.assertNotInBody(\"Profile updated successfully.\")\n self.assertInBody(\"Must be a valid email address.\")", " def test_change_email_with_too_long(self):\n self._set_profile_info((\"test1\" * 50) + \"@test.com\")\n self.assertInBody(\"Email too long.\")", " def test_change_password(self):\n self.listener.user_password_changed.reset_mock()\n # When udating user's password\n self._set_password(self.PASSWORD, \"pr3j5Dwi\", \"pr3j5Dwi\")", " # Then user is redirect to same page\n self.assertStatus(303)\n # Then the page return success message.\n self.getPage(self.PREFS)", " self.assertInBody(\"Password updated successfully.\")\n # Then a notification is raised\n self.listener.user_password_changed.assert_called_once()", " def test_change_password_with_wrong_confirmation(self):\n self._set_password(self.PASSWORD, \"t\", \"a\")\n self.assertInBody(\"The new password and its confirmation do not match.\")", " def test_change_password_with_wrong_password(self):\n self._set_password(\"oups\", \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertInBody(\"Wrong current password\")", " def test_change_password_with_too_short(self):\n self._set_password(self.PASSWORD, \"short\", \"short\")\n self.assertInBody(\"Password must have between 8 and 128 characters.\")", " def test_change_password_with_too_long(self):\n new_password = 'a' * 129\n self._set_password(self.PASSWORD, new_password, new_password)\n self.assertInBody(\"Password must have between 8 and 128 characters.\")", " def test_change_password_too_many_attemps(self):\n # When udating user's password with wrong current password 5 times\n for _i in range(1, 5):\n self._set_password('wrong', \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertStatus(200)\n self.assertInBody(\"Wrong current password.\")\n # Then user session is cleared and user is redirect to login page\n self._set_password('wrong', \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertStatus(303)\n self.assertHeaderItemValue('Location', self.baseurl + '/login/')\n # Then a warning message is displayed on login page\n self.getPage('/login/')\n self.assertStatus(200)\n self.assertInBody('You were logged out because you entered the wrong password too many times.')\n", " def test_change_password_with_same_value(self):\n # Given a user with a password\n self._set_password(self.PASSWORD, \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertStatus(303)\n # When updating the pasword with the same password\n self._set_password(\"pr3j5Dwi\", \"pr3j5Dwi\", \"pr3j5Dwi\")\n self.assertStatus(200)\n # Then an error should be displayed\n self.assertInBody(\"The new password must be different from the current password.\")\n", " def test_change_password_method_get(self):\n # Given an authenticated user\n # Trying to update password with GET method\n self.getPage(self.PREFS + '?action=set_password&new=pr3j5Dwi&confirm=pr3j5Dwi&current=' + self.PASSWORD)\n # Then nothing happen\n self.assertStatus(200)\n self.assertNotInBody(\"Password updated successfully.\")", " def test_invalid_pref(self):\n \"\"\"\n Check if invalid prefs url is 404 Not Found.\n \"\"\"\n self.getPage(\"/prefs/invalid/\")\n self.assertStatus(404)", " def test_update_repos(self):\n # Given a user with invalid repositories\n userobj = UserObject.get_user(self.USERNAME)\n RepoObject(userid=userobj.userid, repopath='invalid').add()\n self.assertEqual(['broker-repo', 'invalid', 'testcases'], sorted([r.name for r in userobj.repo_objs]))\n # When updating the repository list\n self.getPage(self.PREFS, method='POST', body={'action': 'update_repos'})\n self.assertStatus(200)\n # Then a success message is displayed\n self.assertInBody('Repositories successfully updated')\n # Then the list is free of inexisting repos.\n userobj.expire()\n self.assertEqual(['broker-repo', 'testcases'], sorted([r.name for r in userobj.repo_objs]))" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [135, 159, 210], "buggy_code_start_loc": [135, 90, 85], "filenames": ["README.md", "rdiffweb/controller/page_pref_general.py", "rdiffweb/controller/tests/test_page_prefs_general.py"], "fixing_code_end_loc": [137, 171, 231], "fixing_code_start_loc": [136, 91, 85], "message": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:*:*:*:*:*:*:*:*", "matchCriteriaId": "FB8BEAE7-49D4-46D5-86FD-BBB48BA14234", "versionEndExcluding": null, "versionEndIncluding": "2.4.10", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha1:*:*:*:*:*:*", "matchCriteriaId": "E967F2E5-0F47-436B-9DC7-4F8D051F5615", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha2:*:*:*:*:*:*", "matchCriteriaId": "039D2014-4F4C-4B3F-81B1-EFA08EE3D513", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:ikus-soft:rdiffweb:2.5.0:alpha3:*:*:*:*:*:*", "matchCriteriaId": "37EFE887-5C53-48EA-974C-25F36D6014EC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Weak Password Requirements in GitHub repository ikus060/rdiffweb prior to 2.5.0a4."}, {"lang": "es", "value": "Unos Requisitos de Contrase\u00f1a D\u00e9biles en el repositorio de GitHub ikus060/rdiffweb versiones anteriores a 2.5.0a4"}], "evaluatorComment": null, "id": "CVE-2022-3376", "lastModified": "2022-10-12T02:58:12.453", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "PHYSICAL", "availabilityImpact": "LOW", "baseScore": 3.5, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:P/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:L", "version": "3.0"}, "exploitabilityScore": 0.9, "impactScore": 2.5, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "LOW", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-10-06T18:16:21.107", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/a9021e93-6d18-4ac1-98ce-550c4697a4ed"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-521"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-521"}], "source": "security@huntr.dev", "type": "Secondary"}]}, "github_commit_url": "https://github.com/ikus060/rdiffweb/commit/2ffc2af65c8f8113b06e0b89929c604bcdf844b9"}, "type": "CWE-521"}
24
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * C_Document.class.php\n *\n * @package OpenEMR\n * @link https://www.open-emr.org\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "require_once(__DIR__ . \"/../library/forms.inc\");\nrequire_once(__DIR__ . \"/../library/patient.inc\");", "use OpenEMR\\Common\\Acl\\AclMain;\nuse OpenEMR\\Common\\Crypto\\CryptoGen;\nuse OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Common\\Twig\\TwigContainer;\nuse OpenEMR\\Services\\FacilityService;\nuse OpenEMR\\Services\\PatientService;\nuse OpenEMR\\Events\\PatientDocuments\\PatientDocumentTreeViewFilterEvent;", "class C_Document extends Controller\n{\n public $documents;\n public $document_categories;\n public $tree;\n public $_config;\n public $manual_set_owner = false; // allows manual setting of a document owner/service\n public $facilityService;\n public $patientService;\n public $_last_node;\n private $Document;\n private $cryptoGen;", " public function __construct($template_mod = \"general\")\n {\n parent::__construct();\n $this->facilityService = new FacilityService();\n $this->patientService = new PatientService();\n $this->documents = array();\n $this->template_mod = $template_mod;\n $this->assign(\"FORM_ACTION\", $GLOBALS['webroot'] . \"/controller.php?\" . attr($_SERVER['QUERY_STRING'] ?? ''));\n $this->assign(\"CURRENT_ACTION\", $GLOBALS['webroot'] . \"/controller.php?\" . \"document&\");", " if (php_sapi_name() !== 'cli') {\n // skip when this is being called via command line for the ccda importing\n $this->assign(\"CSRF_TOKEN_FORM\", CsrfUtils::collectCsrfToken());\n }", " $this->assign(\"IMAGES_STATIC_RELATIVE\", $GLOBALS['images_static_relative']);", " //get global config options for this namespace\n $this->_config = $GLOBALS['oer_config']['documents'];", " $this->_args = array(\"patient_id\" => ($_GET['patient_id'] ?? null));", " $this->assign(\"STYLE\", $GLOBALS['style']);\n $t = new CategoryTree(1);\n //print_r($t->tree);\n $this->tree = $t;\n $this->Document = new Document();", " // Create a crypto object that will be used for for encryption/decryption\n $this->cryptoGen = new CryptoGen();\n }", " public function upload_action($patient_id, $category_id)\n {\n $category_name = $this->tree->get_node_name($category_id);\n $this->assign(\"category_id\", $category_id);\n $this->assign(\"category_name\", $category_name);\n $this->assign(\"hide_encryption\", $GLOBALS['hide_document_encryption']);\n $this->assign(\"patient_id\", $patient_id);", " // Added by Rod to support document template download from general_upload.html.\n // Cloned from similar stuff in manage_document_templates.php.\n $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';\n $templates_options = \"<option value=''>-- \" . xlt('Select Template') . \" --</option>\";\n if (file_exists($templatedir)) {\n $dh = opendir($templatedir);\n }\n if (!empty($dh)) {\n $templateslist = array();\n while (false !== ($sfname = readdir($dh))) {\n if (substr($sfname, 0, 1) == '.') {\n continue;\n }\n $templateslist[$sfname] = $sfname;\n }\n closedir($dh);\n ksort($templateslist);\n foreach ($templateslist as $sfname) {\n $templates_options .= \"<option value='\" . attr($sfname) .\n \"'>\" . text($sfname) . \"</option>\";\n }\n }\n $this->assign(\"TEMPLATES_LIST\", $templates_options);", " // duplicate template list for new template form editor sjp 05/20/2019\n // will call as module or individual template.\n $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';\n $templates_options = \"<option value=''>-- \" . xlt('Open Forms Module') . \" --</option>\";\n if (file_exists($templatedir)) {\n $dh = opendir($templatedir);\n }\n if ($dh) {\n $templateslist = array();\n while (false !== ($sfname = readdir($dh))) {\n if (substr($sfname, 0, 1) == '.') {\n continue;\n }\n if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {\n $templateslist[$sfname] = $sfname;\n }\n }\n closedir($dh);\n ksort($templateslist);\n foreach ($templateslist as $sfname) {\n $optname = str_replace('_', ' ', basename($sfname, \".tpl\"));\n $templates_options .= \"<option value='\" . attr($sfname) . \"'>\" . text($optname) . \"</option>\";\n }\n }\n $this->assign(\"TEMPLATES_LIST_PATIENT\", $templates_options);", " $activity = $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_upload.html\");\n $this->assign(\"activity\", $activity);\n return $this->list_action($patient_id);\n }", " public function zip_dicom_folder($study_name = null)\n {\n $zip = new ZipArchive();\n $zip_name = $GLOBALS['temporary_files_dir'] . \"/\" . $study_name;\n if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {\n foreach ($_FILES['dicom_folder']['name'] as $i => $name) {\n $zfn = $GLOBALS['temporary_files_dir'] . \"/\" . $name;\n $fparts = pathinfo($name);\n if (empty($fparts['extension'])) {\n // viewer requires lowercase.\n $fparts['extension'] = \"dcm\";\n $name = $fparts['filename'] . \".dcm\";\n }\n if ($fparts['extension'] == \"DCM\") {\n // viewer requires lowercase.\n $fparts['extension'] = \"dcm\";\n $name = $fparts['filename'] . \".dcm\";\n }\n // required extension for viewer\n if ($fparts['extension'] != \"dcm\") {\n continue;\n }\n move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);\n $zip->addFile($zfn, $name);\n }\n $zip->close();\n } else {\n return false;\n }\n $file_array['name'][] = $study_name;\n $file_array['type'][] = 'zip';\n $file_array['tmp_name'][] = $zip_name;\n $file_array['error'][] = '';\n $file_array['size'][] = filesize($zip_name);\n return $file_array;\n }", " //Upload multiple files on single click\n public function upload_action_process()\n {", " // Collect a manually set owner if this has been set\n // Used when want to manually assign the owning user/service such as the Direct mechanism\n $non_HTTP_owner = false;\n if ($this->manual_set_owner) {\n $non_HTTP_owner = $this->manual_set_owner;\n }", " $couchDB = false;\n $harddisk = false;\n if ($GLOBALS['document_storage_method'] == 0) {\n $harddisk = true;\n }\n if ($GLOBALS['document_storage_method'] == 1) {\n $couchDB = true;\n }", " if ($_POST['process'] != \"true\") {\n return;\n }", " $doDecryption = false;\n $encrypted = $_POST['encrypted'] ?? false;\n $passphrase = $_POST['passphrase'] ?? '';\n if (\n !$GLOBALS['hide_document_encryption'] &&\n $encrypted && $passphrase\n ) {\n $doDecryption = true;\n }", " if (is_numeric($_POST['category_id'])) {\n $category_id = $_POST['category_id'];\n }", " $patient_id = 0;\n if (isset($_GET['patient_id']) && !$couchDB) {\n $patient_id = $_GET['patient_id'];\n } elseif (is_numeric($_POST['patient_id'])) {\n $patient_id = $_POST['patient_id'];\n }", " if (!empty($_FILES['dicom_folder']['name'][0])) {\n // let's zip um up then pass along new zip\n $study_name = $_POST['destination'] ? (trim($_POST['destination']) . \".zip\") : 'DicomStudy.zip';\n $study_name = preg_replace('/\\s+/', '_', $study_name);\n $_POST['destination'] = \"\";\n $zipped = $this->zip_dicom_folder($study_name);\n if ($zipped) {\n $_FILES['file'] = $zipped;\n }\n // and off we go! just fall through and let routine\n // do its normal file processing..\n }", " $sentUploadStatus = array();\n if (count($_FILES['file']['name']) > 0) {\n $upl_inc = 0;", " foreach ($_FILES['file']['name'] as $key => $value) {\n $fname = $value;\n $error = \"\";\n if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {\n $fname = $value;\n if (empty($fname)) {\n $fname = htmlentities(\"<empty>\");\n }\n $error = xl(\"Error number\") . \": \" . $_FILES['file']['error'][$key] . \" \" . xl(\"occurred while uploading file named\") . \": \" . $fname . \"\\n\";\n if ($_FILES['file']['size'][$key] == 0) {\n $error .= xl(\"The system does not permit uploading files of with size 0.\") . \"\\n\";\n }\n } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {\n $error = xl(\"The system does not permit uploading files with MIME content type\") . \" - \" . mime_content_type($_FILES['file']['tmp_name'][$key]) . \".\\n\";\n } else {\n // Test for a zip of DICOM images\n if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {\n $za = new ZipArchive();\n $handler = $za->open($_FILES['file']['tmp_name'][$key]);\n if ($handler) {\n $mimetype = \"application/dicom+zip\";\n for ($i = 0; $i < $za->numFiles; $i++) {\n $stat = $za->statIndex($i);\n $fp = $za->getStream($stat['name']);\n if ($fp) {\n $head = fread($fp, 256);\n fclose($fp);\n if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.\n $mimetype = \"application/zip\";\n break;\n }\n unset($head);\n // if here -then a DICOM\n $parts = pathinfo($stat['name']);\n if ($parts['extension'] != \"dcm\" || empty($parts['extension'])) { // required extension for viewer\n $new_name = $parts['filename'] . \".dcm\";\n $za->renameIndex($i, $new_name);\n $za->renameName($parts['filename'], $new_name);\n }\n } else { // Rarely here\n $mimetype = \"application/zip\";\n break;\n }\n }\n $za->close();\n if ($mimetype == \"application/dicom+zip\") {", " $_FILES['file']['type'][$key] = $mimetype;", " sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!\n $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.\n }\n }\n }\n $tmpfile = fopen($_FILES['file']['tmp_name'][$key], \"r\");\n $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);\n fclose($tmpfile);\n if ($doDecryption) {\n $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);\n if ($filetext === false) {\n error_log(\"OpenEMR Error: Unable to decrypt a document since decryption failed.\");\n $filetext = \"\";\n }\n }\n if ($_POST['destination'] != '') {\n $fname = $_POST['destination'];\n }", " // set mime, test for single DICOM and assign extension if missing.\n $mimetype = $_FILES['file']['type'][$key];", " if (strpos($filetext, 'DICM') !== false) {\n $mimetype = 'application/dicom';\n $parts = pathinfo($fname);\n if (!$parts['extension']) {\n $fname .= '.dcm';\n }", "", " }\n $d = new Document();\n $rc = $d->createDocument(\n $patient_id,\n $category_id,\n $fname,\n $mimetype,\n $filetext,\n empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],\n empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],\n $non_HTTP_owner,\n $_FILES['file']['tmp_name'][$key]\n );\n if ($rc) {\n $error .= $rc . \"\\n\";\n } else {\n $this->assign(\"upload_success\", \"true\");\n }\n $sentUploadStatus[] = $d;\n $this->assign(\"file\", $sentUploadStatus);\n }", " // Option to run a custom plugin for each file upload.\n // This was initially created to delete the original source file in a custom setting.\n $upload_plugin = $GLOBALS['OE_SITE_DIR'] . \"/documentUpload.plugin.php\";\n if (file_exists($upload_plugin)) {\n include_once($upload_plugin);\n }\n $upload_plugin_pp = 'documentUploadPostProcess';\n if (function_exists($upload_plugin_pp)) {\n $tmp = call_user_func($upload_plugin_pp, $value, $d);\n if ($tmp) {\n $error = $tmp;\n }\n }\n // Following is just an example of code in such a plugin file.\n /*****************************************************\n public function documentUploadPostProcess($filename, &$d) {\n $userid = $_SESSION['authUserID'];\n $row = sqlQuery(\"SELECT username FROM users WHERE id = ?\", array($userid));\n $owner = strtolower($row['username']);\n $dn = '1_' . ucfirst($owner);\n $filepath = \"/shared_network_directory/$dn/$filename\";\n if (@unlink($filepath)) return '';\n return \"Failed to delete '$filepath'.\";\n }\n *****************************************************/\n }\n }", " $this->assign(\"error\", $error);\n //$this->_state = false;\n $_POST['process'] = \"\";\n //return $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_upload.html\");\n }", " public function note_action_process($patient_id)\n {\n // this public function is a dual public function that will set up a note associated with a document or send a document via email.", " if ($_POST['process'] != \"true\") {\n return;\n }", " $n = new Note();\n $n->set_owner($_SESSION['authUserID']);\n parent::populate_object($n);\n if ($_POST['identifier'] == \"no\") {\n // associate a note with a document\n $n->persist();\n } elseif ($_POST['identifier'] == \"yes\") {\n // send the document via email\n $d = new Document($_POST['foreign_id']);\n $url = $d->get_url();\n $storagemethod = $d->get_storagemethod();\n $couch_docid = $d->get_couch_docid();\n $couch_revid = $d->get_couch_revid();\n if ($couch_docid && $couch_revid) {\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc($couch_docid);\n $content = $resp->data;\n if ($content == '' && $GLOBALS['couchdb_log'] == 1) {\n $log_content = date('Y-m-d H:i:s') . \" ==> Retrieving document\\r\\n\";\n $log_content = date('Y-m-d H:i:s') . \" ==> URL: \" . $url . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Document Id: \" . $couch_docid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Revision Id: \" . $couch_revid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Failed to fetch document content from CouchDB.\\r\\n\";\n //$log_content .= date('Y-m-d H:i:s').\" ==> Will try to download file from HardDisk if exists.\\r\\n\\r\\n\";\n $this->document_upload_download_log($d->get_foreign_id(), $log_content);\n die(xlt(\"File retrieval from CouchDB failed\"));\n }\n // place it in a temporary file and will remove the file below after emailed\n $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date(\"YmdHis\") . $d->get_url_file();\n $fh = fopen($temp_couchdb_url, \"w\");\n fwrite($fh, base64_decode($content));\n fclose($fh);\n $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens\n } else {\n $url = preg_replace(\"|^(.*)://|\", \"\", $url);\n // Collect filename and path\n $from_all = explode(\"/\", $url);\n $from_filename = array_pop($from_all);\n $from_pathname_array = array();\n for ($i = 0; $i < $d->get_path_depth(); $i++) {\n $from_pathname_array[] = array_pop($from_all);\n }\n $from_pathname_array = array_reverse($from_pathname_array);\n $from_pathname = implode(\"/\", $from_pathname_array);\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;\n }\n if (!file_exists($temp_url)) {\n echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $temp_url;\n }\n $url = $temp_url;\n $pdetails = getPatientData($patient_id);\n $pname = $pdetails['fname'] . \" \" . $pdetails['lname'];\n $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);\n if ($couch_docid && $couch_revid) {\n // remove the temporary couchdb file\n unlink($temp_couchdb_url);\n }\n }\n $this->_state = false;\n $_POST['process'] = \"\";\n return $this->view_action($patient_id, $n->get_foreign_id());\n }", " public function default_action()\n {\n return $this->list_action();\n }", " public function view_action(string $patient_id = null, $doc_id)\n {\n global $ISSUE_TYPES;", " require_once(dirname(__FILE__) . \"/../library/lists.inc\");", " $d = new Document($doc_id);\n $notes = $d->get_notes();", " $this->assign(\"csrf_token_form\", CsrfUtils::collectCsrfToken());", " $this->assign(\"file\", $d);\n $this->assign(\"web_path\", $this->_link(\"retrieve\") . \"document_id=\" . urlencode($d->get_id()) . \"&\");\n $this->assign(\"NOTE_ACTION\", $this->_link(\"note\"));\n $this->assign(\"MOVE_ACTION\", $this->_link(\"move\") . \"document_id=\" . urlencode($d->get_id()) . \"&process=true\");\n $this->assign(\"hide_encryption\", $GLOBALS['hide_document_encryption']);\n $this->assign(\"assets_static_relative\", $GLOBALS['assets_static_relative']);\n $this->assign(\"webroot\", $GLOBALS['webroot']);", " // Added by Rod to support document delete:\n $delete_string = '';\n if (AclMain::aclCheckCore('patients', 'docs_rm')) {\n $delete_string = \"<a href='' class='btn btn-danger' onclick='return deleteme(\" . attr_js($d->get_id()) .\n \")'>\" . xlt('Delete') . \"</a>\";\n }\n $this->assign(\"delete_string\", $delete_string);\n $this->assign(\"REFRESH_ACTION\", $this->_link(\"list\"));", " $this->assign(\"VALIDATE_ACTION\", $this->_link(\"validate\") .\n \"document_id=\" . $d->get_id() . \"&process=true\");", " // Added by Rod to support document date update:\n $this->assign(\"DOCDATE\", $d->get_docdate());\n $this->assign(\"UPDATE_ACTION\", $this->_link(\"update\") .\n \"document_id=\" . $d->get_id() . \"&process=true\");", " // Added by Rod to support document issue update:\n $issues_options = \"<option value='0'>-- \" . xlt('Select Issue') . \" --</option>\";\n $ires = sqlStatement(\"SELECT id, type, title, begdate FROM lists WHERE \" .\n \"pid = ? \" . // AND enddate IS NULL \" .\n \"ORDER BY type, begdate\", array($patient_id));\n while ($irow = sqlFetchArray($ires)) {\n $desc = $irow['type'];\n if ($ISSUE_TYPES[$desc]) {\n $desc = $ISSUE_TYPES[$desc][2];\n }\n $desc .= \": \" . text($irow['begdate']) . \" \" . text(substr($irow['title'], 0, 40));\n $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';\n $issues_options .= \"<option value='\" . attr($irow['id']) . \"'$sel>$desc</option>\";\n }\n $this->assign(\"ISSUES_LIST\", $issues_options);", " // For tagging to encounter\n // Populate the dropdown with patient's encounter list\n $this->assign(\"TAG_ACTION\", $this->_link(\"tag\") . \"document_id=\" . urlencode($d->get_id()) . \"&process=true\");\n $encOptions = \"<option value='0'>-- \" . xlt('Select Encounter') . \" --</option>\";\n $result_docs = sqlStatement(\"SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe \" .\n \"LEFT JOIN openemr_postcalendar_categories ON fe.pc_catid=openemr_postcalendar_categories.pc_catid WHERE fe.pid = ? ORDER BY fe.date desc\", array($patient_id));\n if (sqlNumRows($result_docs) > 0) {\n while ($row_result_docs = sqlFetchArray($result_docs)) {\n $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';\n $encOptions .= \"<option value='\" . attr($row_result_docs['encounter']) . \"' $sel_enc>\" . text(oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date'])))) . \"-\" . text(xl_appt_category($row_result_docs['pc_catname'])) . \"</option>\";\n }\n }\n $this->assign(\"ENC_LIST\", $encOptions);", " //clear encounter tag\n if ($d->get_encounter_id() != 0) {\n $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . \"document_id=\" . urlencode($d->get_id()));\n } else {\n $this->assign('clear_encounter_tag', 'javascript:void(0)');\n }", " //Populate the dropdown with category list\n $visit_category_list = \"<option value='0'>-- \" . xlt('Select One') . \" --</option>\";\n $cres = sqlStatement(\"SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname\");\n while ($crow = sqlFetchArray($cres)) {\n $catid = $crow['pc_catid'];\n if ($catid < 9 && $catid != 5) {\n continue; // Applying same logic as in new encounter page.\n }\n $visit_category_list .= \"<option value='\" . attr($catid) . \"'>\" . text(xl_appt_category($crow['pc_catname'])) . \"</option>\\n\";\n }\n $this->assign(\"VISIT_CATEGORY_LIST\", $visit_category_list);", " $this->assign(\"notes\", $notes);", " $this->assign(\"PROCEDURE_TAG_ACTION\", $this->_link(\"image_procedure\") . \"document_id=\" . urlencode($d->get_id()));\n // Populate the dropdown with procedure order list\n $imgOptions = \"<option value='0'>-- \" . xlt('Select Procedure') . \" --</option>\";\n $imgOrders = sqlStatement(\"select procedure_name,po.procedure_order_id,procedure_code,poc.procedure_order_title from procedure_order po inner join procedure_order_code poc on poc.procedure_order_id = po.procedure_order_id where po.patient_id = ?\", array($patient_id));\n $mapping = $this->get_mapped_procedure($d->get_id());\n if (sqlNumRows($imgOrders) > 0) {\n while ($row = sqlFetchArray($imgOrders)) {\n $sel_proc = '';\n if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {\n $sel_proc = 'selected';\n }\n $imgOptions .= \"<option value='\" . attr($row['procedure_order_id']) . \"' data-code='\" . attr($row['procedure_code']) . \"' $sel_proc>\" . text($row['procedure_name'] . ' - ' . $row['procedure_code'] . ' : ' . ucfirst($row['procedure_order_title'])) . \"</option>\";\n }\n }", " $this->assign('TAG_PROCEDURE_LIST', $imgOptions);", " $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . \"document_id=\" . urlencode($d->get_id()));", " $this->_last_node = null;", " $menu = new HTML_TreeMenu();", " //pass an empty array because we don't want the documents for each category showing up in this list box\n $rnode = $this->array_recurse($this->tree->tree, $patient_id, array());\n $menu->addItem($rnode);\n $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array(\"promoText\" => xl('Move Document to Category:')));", " $this->assign(\"tree_html_listbox\", $treeMenu_listbox->toHTML());", " $activity = $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_view.html\");\n $this->assign(\"activity\", $activity);", " return $this->list_action($patient_id);\n }", " /**\n * Retrieve file from hard disk / CouchDB.\n * In case that file isn't download this public function will return thumbnail image (if exist).\n * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.\n * @param (string) $context - given a special document scenario (e.g.: patient avatar, custom image viewer document, etc), the context can be set so that a switch statement can execute a custom strategy.\n * */\n public function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = \"normal\")\n {\n $encrypted = $_POST['encrypted'] ?? false;\n $passphrase = $_POST['passphrase'] ?? '';\n $doEncryption = false;\n if (\n !$GLOBALS['hide_document_encryption'] &&\n $encrypted == \"true\" &&\n $passphrase\n ) {\n $doEncryption = true;\n }", " //controller public function ruins booleans, so need to manually re-convert to booleans\n if ($as_file == \"true\") {\n $as_file = true;\n } elseif ($as_file == \"false\") {\n $as_file = false;\n }\n if ($original_file == \"true\") {\n $original_file = true;\n } elseif ($original_file == \"false\") {\n $original_file = false;\n }\n if ($disable_exit == \"true\") {\n $disable_exit = true;\n } elseif ($disable_exit == \"false\") {\n $disable_exit = false;\n }\n if ($show_original == \"true\") {\n $show_original = true;\n } elseif ($show_original == \"false\") {\n $show_original = false;\n }", " switch ($context) {\n case \"patient_picture\":\n $document_id = $this->patientService->getPatientPictureDocumentId($patient_id);\n break;\n }", " $d = new Document($document_id);\n $url = $d->get_url();\n $th_url = $d->get_thumb_url();", " $storagemethod = $d->get_storagemethod();\n $couch_docid = $d->get_couch_docid();\n $couch_revid = $d->get_couch_revid();", " if ($couch_docid && $couch_revid && $original_file) {\n // standard case for collecting a document from couchdb\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc($couch_docid);\n //Take thumbnail file when is not null and file is presented online\n if (!$as_file && !is_null($th_url) && !$show_original) {\n $content = $resp->th_data;\n } else {\n $content = $resp->data;\n }\n if ($content == '' && $GLOBALS['couchdb_log'] == 1) {\n $log_content = date('Y-m-d H:i:s') . \" ==> Retrieving document\\r\\n\";\n $log_content = date('Y-m-d H:i:s') . \" ==> URL: \" . $url . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Document Id: \" . $couch_docid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Revision Id: \" . $couch_revid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Failed to fetch document content from CouchDB.\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Will try to download file from HardDisk if exists.\\r\\n\\r\\n\";\n $this->document_upload_download_log($d->get_foreign_id(), $log_content);\n die(xlt(\"File retrieval from CouchDB failed\"));\n }\n if ($d->get_encrypted() == 1) {\n $filetext = $this->cryptoGen->decryptStandard($content, null, 'database');\n } else {\n $filetext = base64_decode($content);\n }\n if ($disable_exit == true) {\n return $filetext;\n }\n header('Content-Description: File Transfer');\n header('Content-Transfer-Encoding: binary');\n header('Expires: 0');\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n if ($doEncryption) {\n $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);\n header('Content-Disposition: attachment; filename=\"' . \"/encrypted_aes_\" . $d->get_name() . '\"');\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Length: \" . strlen($ciphertext));\n echo $ciphertext;\n } else {\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: \" . $d->get_mimetype());\n header(\"Content-Length: \" . strlen($filetext));\n echo $filetext;\n }\n exit;//exits only if file download from CouchDB is successfull.\n }\n if ($couch_docid && $couch_revid) {\n //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table\n //try to convert it if it has not yet been converted\n //first, see if the converted jpg already exists\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc(\"converted_\" . $couch_docid);\n $content = $resp->data;\n if ($content == '') {\n //create the converted jpg\n $couchM = new CouchDB();\n $respM = $couchM->retrieve_doc($couch_docid);\n if ($d->get_encrypted() == 1) {\n $contentM = $this->cryptoGen->decryptStandard($respM->data, null, 'database');\n } else {\n $contentM = base64_decode($respM->data);\n }\n if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {\n $log_content = date('Y-m-d H:i:s') . \" ==> Retrieving document\\r\\n\";\n $log_content = date('Y-m-d H:i:s') . \" ==> URL: \" . $url . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Document Id: \" . $couch_docid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Revision Id: \" . $couch_revid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Failed to fetch document content from CouchDB.\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Will try to download file from HardDisk if exists.\\r\\n\\r\\n\";\n $this->document_upload_download_log($d->get_foreign_id(), $log_content);\n die(xlt(\"File retrieval from CouchDB failed\"));\n }\n // place the from-file into a temporary file\n $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n file_put_contents($from_file_tmp_name, $contentM);\n // prepare a temporary file for the to-file\n $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n $to_file_tmp_name = $to_file_tmp . \".jpg\";\n // convert file to jpg\n exec(\"convert -density 200 \" . escapeshellarg($from_file_tmp_name) . \" -append -resize 850 \" . escapeshellarg($to_file_tmp_name));\n // remove from tmp file\n unlink($from_file_tmp_name);\n // save the to-file if a to-file was created in above convert call\n if (is_file($to_file_tmp_name)) {\n $couchI = new CouchDB();\n if ($d->get_encrypted() == 1) {\n $document = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');\n } else {\n $document = base64_encode(file_get_contents($to_file_tmp_name));\n }\n $couchI->save_doc(['_id' => \"converted_\" . $couch_docid, 'data' => $document]);\n // remove to tmp files\n unlink($to_file_tmp);\n unlink($to_file_tmp_name);\n } else {\n error_log(\"ERROR: Document '\" . errorLogEscape($d->get_name()) . \"' cannot be converted to JPEG. Perhaps ImageMagick is not installed?\");\n }\n // now collect the newly created converted jpg\n $couchF = new CouchDB();\n $respF = $couchF->retrieve_doc(\"converted_\" . $couch_docid);\n if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard($respF->data, null, 'database');\n } else {\n $content = base64_decode($respF->data);\n }\n } else {\n // decrypt/decode when converted jpg already exists\n if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');\n } else {\n $content = base64_decode($resp->data);\n }\n }\n $filetext = $content;\n if ($disable_exit == true) {\n return $filetext;\n }\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: image/jpeg\");\n header(\"Content-Length: \" . strlen($filetext));\n echo $filetext;\n exit;\n }", " //Take thumbnail file when is not null and file is presented online\n if (!$as_file && !is_null($th_url) && !$show_original) {\n $url = $th_url;\n }", " //strip url of protocol handler\n $url = preg_replace(\"|^(.*)://|\", \"\", $url);", " //change full path to current webroot. this is for documents that may have\n //been moved from a different filesystem and the full path in the database\n //is not current. this is also for documents that may of been moved to\n //different patients. Note that the path_depth is used to see how far down\n //the path to go. For example, originally the path_depth was always 1, which\n //only allowed things like documents/1/<file>, but now can have more structured\n //directories. For example a path_depth of 2 can give documents/encounters/1/<file>\n // etc.\n // NOTE that $from_filename and basename($url) are the same thing\n $from_all = explode(\"/\", $url);\n $from_filename = array_pop($from_all);\n $from_pathname_array = array();\n for ($i = 0; $i < $d->get_path_depth(); $i++) {\n $from_pathname_array[] = array_pop($from_all);\n }\n $from_pathname_array = array_reverse($from_pathname_array);\n $from_pathname = implode(\"/\", $from_pathname_array);\n if ($couch_docid && $couch_revid) {\n //for couchDB no URL is available in the table, hence using the foreign_id which is patientID\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;\n } else {\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;\n }", " if (file_exists($temp_url)) {\n $url = $temp_url;\n }", " if (!file_exists($url)) {\n echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $url;\n } else {\n if ($original_file) {\n //normal case when serving the file referenced in database\n if ($d->get_encrypted() == 1) {\n $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');\n } else {\n if (!is_dir($url)) {\n $filetext = file_get_contents($url);\n }\n }\n if ($disable_exit == true) {\n return $filetext ?? '';\n }\n header('Content-Description: File Transfer');\n header('Content-Transfer-Encoding: binary');\n header('Expires: 0');\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n if ($doEncryption) {\n $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);\n header('Content-Disposition: attachment; filename=\"' . \"/encrypted_aes_\" . $d->get_name() . '\"');\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Length: \" . strlen($ciphertext));\n echo $ciphertext;\n } else {\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: \" . $d->get_mimetype());\n header(\"Content-Length: \" . strlen($filetext ?? ''));\n echo $filetext ?? '';\n }\n exit;\n } else {\n //special case when retrieving a document that has been converted to a jpg and not directly referenced in database\n //try to convert it if it has not yet been converted\n $originalUrl = $url;\n if (strrpos(basename_international($url), '.') === false) {\n $convertedFile = basename_international($url) . '_converted.jpg';\n } else {\n $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';\n }\n $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;\n if (!is_file($url)) {\n if ($d->get_encrypted() == 1) {\n // decrypt the from-file into a temporary file\n $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');\n $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n file_put_contents($from_file_tmp_name, $from_file_unencrypted);\n // prepare a temporary file for the unencrypted to-file\n $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n $to_file_tmp_name = $to_file_tmp . \".jpg\";\n // convert file to jpg\n exec(\"convert -density 200 \" . escapeshellarg($from_file_tmp_name) . \" -append -resize 850 \" . escapeshellarg($to_file_tmp_name));\n // remove unencrypted tmp file\n unlink($from_file_tmp_name);\n // make the encrypted to-file if a to-file was created in above convert call\n if (is_file($to_file_tmp_name)) {\n $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');\n file_put_contents($url, $to_file_encrypted);\n // remove unencrypted tmp files\n unlink($to_file_tmp);\n unlink($to_file_tmp_name);\n }\n } else {\n // convert file to jpg\n exec(\"convert -density 200 \" . escapeshellarg($originalUrl) . \" -append -resize 850 \" . escapeshellarg($url));\n }\n }\n if (is_file($url)) {\n if ($d->get_encrypted() == 1) {\n $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');\n } else {\n $filetext = file_get_contents($url);\n }\n } else {\n $filetext = '';\n error_log(\"ERROR: Document '\" . errorLogEscape(basename_international($url)) . \"' cannot be converted to JPEG. Perhaps ImageMagick is not installed?\");\n }\n if ($disable_exit == true) {\n return $filetext;\n }\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: image/jpeg\");\n header(\"Content-Length: \" . strlen($filetext));\n echo $filetext;\n exit;\n }\n }\n }", " public function move_action_process(string $patient_id = null, $document_id)\n {\n if ($_POST['process'] != \"true\") {\n return;\n }", " $messages = '';", " $new_category_id = $_POST['new_category_id'];\n $new_patient_id = $_POST['new_patient_id'];", " //move to new category\n if (is_numeric($new_category_id) && is_numeric($document_id)) {\n $sql = \"UPDATE categories_to_documents set category_id = ? where document_id = ?\";\n $messages .= xl('Document moved to new category', '', '', ' \\'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\\' ') . \"\\n\";\n //echo $sql;\n $this->tree->_db->Execute($sql, [$new_category_id, $document_id]);\n }", " //move to new patient\n if (is_numeric($new_patient_id) && is_numeric($document_id)) {\n $d = new Document($document_id);\n $sql = \"SELECT pid from patient_data where pid = ?\";\n $result = $d->_db->Execute($sql, [$new_patient_id]);", " if (!$result || $result->EOF) {\n //patient id does not exist\n $messages .= xl('Document could not be moved to patient id', '', '', ' \\'') . $new_patient_id . xl('because that id does not exist.', '', '\\' ') . \"\\n\";\n } else {\n $changefailed = !$d->change_patient($new_patient_id);", " $this->_state = false;\n if (!$changefailed) {\n $messages .= xl('Document moved to patient id', '', '', ' \\'') . $new_patient_id . xl('successfully.', '', '\\' ') . \"\\n\";\n } else {\n $messages .= xl('Document moved to patient id', '', '', ' \\'') . $new_patient_id . xl('Failed.', '', '\\' ') . \"\\n\";\n }\n $this->assign(\"messages\", $messages);\n return $this->list_action($patient_id);\n }\n }", " $this->_state = false;\n $this->assign(\"messages\", $messages);\n return $this->view_action($patient_id, $document_id);\n }", " public function validate_action_process(string $patient_id = null, $document_id)\n {", " $d = new Document($document_id);\n if ($d->couch_docid && $d->couch_revid) {\n $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';\n $url = $file_path . $d->get_url();\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc($d->couch_docid);\n if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');\n } else {\n $content = base64_decode($resp->data);\n }\n } else {\n $url = $d->get_url();", " //strip url of protocol handler\n $url = preg_replace(\"|^(.*)://|\", \"\", $url);", " //change full path to current webroot. this is for documents that may have\n //been moved from a different filesystem and the full path in the database\n //is not current. this is also for documents that may of been moved to\n //different patients. Note that the path_depth is used to see how far down\n //the path to go. For example, originally the path_depth was always 1, which\n //only allowed things like documents/1/<file>, but now can have more structured\n //directories. For example a path_depth of 2 can give documents/encounters/1/<file>\n // etc.\n // NOTE that $from_filename and basename($url) are the same thing\n $from_all = explode(\"/\", $url);\n $from_filename = array_pop($from_all);\n $from_pathname_array = array();\n for ($i = 0; $i < $d->get_path_depth(); $i++) {\n $from_pathname_array[] = array_pop($from_all);\n }\n $from_pathname_array = array_reverse($from_pathname_array);\n $from_pathname = implode(\"/\", $from_pathname_array);\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;\n if (file_exists($temp_url)) {\n $url = $temp_url;\n }", " if ($_POST['process'] != \"true\") {\n die(\"process is '\" . text($_POST['process']) . \"', expected 'true'\");\n return;\n }", " if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');\n } else {\n $content = file_get_contents($url);\n }\n }", " if (!empty($d->get_hash()) && (strlen($d->get_hash()) < 50)) {\n // backward compatibility for documents that were hashed prior to OpenEMR 6.0.0\n $current_hash = sha1($content);\n } else {\n $current_hash = hash('sha3-512', $content);\n }\n $messages = xl('Current Hash') . \": \" . $current_hash . \" | \";\n $messages .= xl('Stored Hash') . \": \" . $d->get_hash();\n if ($d->get_hash() == '') {\n $d->hash = $current_hash;\n $d->persist();\n $d->populate();\n $messages .= xl('Hash did not exist for this file. A new hash was generated.');\n } elseif ($current_hash != $d->get_hash()) {\n $messages .= xl('Hash does not match. Data integrity has been compromised.');\n } else {\n $messages = xl('Document passed integrity check.') . ' | ' . $messages;\n }\n $this->_state = false;\n $this->assign(\"messages\", $messages);\n return $this->view_action($patient_id, $document_id);\n }", " // Added by Rod for metadata update.\n //\n public function update_action_process(string $patient_id = null, $document_id)\n {", " if ($_POST['process'] != \"true\") {\n die(\"process is '\" . $_POST['process'] . \"', expected 'true'\");\n return;\n }", " $docdate = $_POST['docdate'];\n $docname = $_POST['docname'];\n $issue_id = $_POST['issue_id'];", " if (is_numeric($document_id)) {\n $messages = '';\n $d = new Document($document_id);\n $file_name = $d->get_name();\n if (\n $docname != '' &&\n $docname != $file_name\n ) {\n // Rename\n $d->set_name($docname);\n $d->persist();\n $d->populate();\n $messages .= xl('Document successfully renamed.') . \"<br />\";\n }", " if (preg_match('/^\\d\\d\\d\\d-\\d+-\\d+$/', $docdate)) {\n $docdate = \"$docdate\";\n } else {\n $docdate = \"NULL\";\n }\n if (!is_numeric($issue_id)) {\n $issue_id = 0;\n }\n $couch_docid = $d->get_couch_docid();\n $couch_revid = $d->get_couch_revid();\n if ($couch_docid && $couch_revid) {\n $sql = \"UPDATE documents SET docdate = ?, url = ?, list_id = ? WHERE id = ?\";\n $this->tree->_db->Execute($sql, [$docdate, $_POST['docname'], $issue_id, $document_id]);\n } else {\n $sql = \"UPDATE documents SET docdate = ?, list_id = ? WHERE id = ?\";\n $this->tree->_db->Execute($sql, [$docdate, $issue_id, $document_id]);\n }\n $messages .= xl('Document date and issue updated successfully') . \"<br />\";\n }", " $this->_state = false;\n $this->assign(\"messages\", $messages);\n return $this->view_action($patient_id, $document_id);\n }", " public function list_action($patient_id = \"\")\n {\n $this->_last_node = null;\n $categories_list = $this->tree->_get_categories_array($patient_id);\n //print_r($categories_list);", " $menu = new HTML_TreeMenu();\n $rnode = $this->array_recurse($this->tree->tree, $patient_id, $categories_list);\n $menu->addItem($rnode);\n $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));\n $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));\n $this->assign(\"tree_html\", $treeMenu->toHTML());", " $is_new = isset($_GET['patient_name']) ? 1 : false;\n $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl(\"Patient search or select.\");\n $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';\n $used_msg = xl('Current patient unavailable here. Use Patient Documents');\n if ($cur_pid == '00') {\n if (!AclMain::aclCheckCore('patients', 'docs', '', ['write', 'addonly'])) {\n echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl(\"Documents\")]);\n exit;\n }\n $cur_pid = '0';\n $is_new = 1;\n }\n if (!AclMain::aclCheckCore('patients', 'docs')) {\n echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl(\"Documents\")]);\n exit;\n }\n $this->assign('is_new', $is_new);\n $this->assign('place_hld', $place_hld);\n $this->assign('cur_pid', $cur_pid);\n $this->assign('used_msg', $used_msg);\n $this->assign('demo_pid', ($_SESSION['pid'] ?? null));", " return $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_list.html\");\n }", " public function &array_recurse($array, $patient_id, $categories = array())\n {\n if (!is_array($array)) {\n $array = array();\n }\n $node = &$this->_last_node;\n $current_node = &$node;\n $expandedIcon = 'folder-expanded.gif';\n foreach ($array as $id => $ar) {\n $icon = 'folder.gif';\n if (is_array($ar) || !empty($id)) {\n if ($node == null) {\n //echo \"r:\" . $this->tree->get_node_name($id) . \"<br />\";\n $rnode = new HTML_TreeNode(array(\"id\" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => false));\n $this->_last_node = &$rnode;\n $node = &$rnode;\n $current_node = &$rnode;\n } else {\n //echo \"p:\" . $this->tree->get_node_name($id) . \"<br />\";\n $this->_last_node = &$node->addItem(new HTML_TreeNode(array(\"id\" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));\n $current_node = &$this->_last_node;\n }", " $this->array_recurse($ar, $patient_id, $categories);\n } else {\n if ($id === 0 && !empty($ar)) {\n $info = $this->tree->get_node_info($id);\n //echo \"b:\" . $this->tree->get_node_name($id) . \"<br />\";\n $current_node = &$node->addItem(new HTML_TreeNode(array(\"id\" => $id, 'text' => $info['value'], 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));\n } else {\n //there is a third case that is implicit here when title === 0 and $ar is empty, in that case we do not want to do anything\n //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO\n if ($id !== 0 && is_object($node)) {\n //echo \"n:\" . $this->tree->get_node_name($id) . \"<br />\";\n $current_node = &$node->addItem(new HTML_TreeNode(array(\"id\" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));\n }\n }\n }", " // If there are documents in this document category, then add their\n // attributes to the current node.\n $icon = \"file3.png\";\n if (!empty($categories[$id]) && is_array($categories[$id])) {\n foreach ($categories[$id] as $doc) {\n $link = $this->_link(\"view\") . \"doc_id=\" . urlencode($doc['document_id']) . \"&\";\n // If user has no access then there will be no link.\n if (!AclMain::aclCheckAcoSpec($doc['aco_spec'])) {\n $link = '';\n }\n // CCD view\n $nodeInfo = $this->tree->get_node_info($id);\n $treeViewFilterEvent = new PatientDocumentTreeViewFilterEvent();\n $treeViewFilterEvent->setCategoryTreeNode($this->tree);\n $treeViewFilterEvent->setDocumentId($doc['document_id']);\n $treeViewFilterEvent->setDocumentName($doc['document_name']);\n $treeViewFilterEvent->setCategoryId($id);\n $treeViewFilterEvent->setCategoryInfo($nodeInfo);\n $treeViewFilterEvent->setPid($patient_id);", " $htmlNode = new HTML_TreeNode(array(\n 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],\n 'link' => $link,\n 'icon' => $icon,\n 'expandedIcon' => $expandedIcon\n ));", " $treeViewFilterEvent->setHtmlTreeNode($htmlNode);\n $filteredEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch($treeViewFilterEvent, PatientDocumentTreeViewFilterEvent::EVENT_NAME);\n if ($filteredEvent->getHtmlTreeNode() != null) {\n $current_node->addItem($filteredEvent->getHtmlTreeNode());\n } else {\n // add the original node if we got back nothing from the server\n $current_node->addItem($htmlNode);\n }\n }\n }\n }\n return $node;\n }", " //public function for logging the errors in writing file to CouchDB/Hard Disk\n public function document_upload_download_log($patientid, $content)\n {\n $log_path = $GLOBALS['OE_SITE_DIR'] . \"/documents/couchdb/\";\n $log_file = 'log.txt';\n if (!is_dir($log_path)) {\n mkdir($log_path, 0777, true);\n }", " $LOG = file_get_contents($log_path . $log_file);", " if ($this->cryptoGen->cryptCheckStandard($LOG)) {\n $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');\n }", " $LOG .= $content;", " if (!empty($LOG)) {\n if ($GLOBALS['drive_encryption']) {\n $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');\n }\n file_put_contents($log_path . $log_file, $LOG);\n }\n }", " public function document_send($email, $body, $attfile, $pname)\n {\n if (empty($email)) {\n $this->assign(\"process_result\", \"Email could not be sent, the address supplied: '$email' was empty or invalid.\");\n return;\n }", " $desc = \"Please check the attached patient document.\\n Content:\" . $body;\n $mail = new MyMailer();\n $from_name = $GLOBALS[\"practice_return_email_path\"];\n $from = $GLOBALS[\"practice_return_email_path\"];\n $mail->AddReplyTo($from, $from_name);\n $mail->SetFrom($from, $from);\n $to = $email ;\n $to_name = $email;\n $mail->AddAddress($to, $to_name);\n $subject = \"Patient documents\";\n $mail->Subject = $subject;\n $mail->Body = $desc;\n $mail->AddAttachment($attfile);\n if ($mail->Send()) {\n $retstatus = \"email_sent\";\n } else {\n $email_status = $mail->ErrorInfo;\n //echo \"EMAIL ERROR: \".$email_status;\n $retstatus = \"email_fail\";\n }\n }", "//place to hold optional code\n//$first_node = array_keys($t->tree);\n //$first_node = $first_node[0];\n //$node1 = new HTML_TreeNode(array('text' => $t->get_node_name($first_node), 'link' => \"test.php\", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true), array('onclick' => \"alert('foo'); return false\", 'onexpand' => \"alert('Expanded')\"));", " //$this->_last_node = &$node1;", "// public function to tag a document to an encounter.\n public function tag_action_process(string $patient_id = null, $document_id)\n {\n if ($_POST['process'] != \"true\") {\n die(\"process is '\" . text($_POST['process']) . \"', expected 'true'\");\n return;\n }", " // Create Encounter and Tag it.\n $event_date = date('Y-m-d H:i:s');\n $encounter_id = $_POST['encounter_id'];\n $encounter_check = $_POST['encounter_check'];\n $visit_category_id = $_POST['visit_category_id'];", " if (is_numeric($document_id)) {\n $messages = '';\n $d = new Document($document_id);\n $file_name = $d->get_url_file();\n if (!is_numeric($encounter_id)) {\n $encounter_id = 0;\n }", " $encounter_check = ( $encounter_check == 'on') ? 1 : 0;\n if ($encounter_check) {\n $provider_id = $_SESSION['authUserID'] ;", " // Get the logged in user's facility\n $facilityRow = sqlQuery(\"SELECT username, facility, facility_id FROM users WHERE id = ?\", array(\"$provider_id\"));\n $username = $facilityRow['username'];\n $facility = $facilityRow['facility'];\n $facility_id = $facilityRow['facility_id'];\n // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility\n $billingFacility = $this->facilityService->getPrimaryBusinessEntity();\n $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;", " $conn = $GLOBALS['adodb']['db'];\n $encounter = $conn->GenID(\"sequences\");\n $query = \"INSERT INTO form_encounter SET\n\t\t\t\t\t\tdate = ?,\n\t\t\t\t\t\treason = ?,\n\t\t\t\t\t\tfacility = ?,\n\t\t\t\t\t\tsensitivity = 'normal',\n\t\t\t\t\t\tpc_catid = ?,\n\t\t\t\t\t\tfacility_id = ?,\n\t\t\t\t\t\tbilling_facility = ?,\n\t\t\t\t\t\tprovider_id = ?,\n\t\t\t\t\t\tpid = ?,\n\t\t\t\t\t\tencounter = ?\";\n $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);\n $formID = sqlInsert($query, $bindArray);\n addForm($encounter, \"New Patient Encounter\", $formID, \"newpatient\", $patient_id, \"1\", date(\"Y-m-d H:i:s\"), $username);\n $d->set_encounter_id($encounter);\n $this->image_result_indication($d->id, $encounter);\n } else {\n $d->set_encounter_id($encounter_id);\n $this->image_result_indication($d->id, $encounter_id);\n }\n $d->set_encounter_check($encounter_check);\n $d->persist();", " $messages .= xlt('Document tagged to Encounter successfully') . \"<br />\";\n }", " $this->_state = false;\n $this->assign(\"messages\", $messages);", " return $this->view_action($patient_id, $document_id);\n }", " public function image_procedure_action(string $patient_id = null, $document_id)\n {", " $img_procedure_id = $_POST['image_procedure_id'];\n $proc_code = $_POST['procedure_code'];", " if (is_numeric($document_id)) {\n $img_order = sqlQuery(\"select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? \", array($img_procedure_id,$proc_code));\n $img_report = sqlQuery(\"select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? \", array($img_procedure_id,$img_order['procedure_order_seq']));\n $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;\n if ($img_report_id == 0) {\n $report_date = date('Y-m-d H:i:s');\n $img_report_id = sqlInsert(\"INSERT INTO procedure_report(procedure_order_id,procedure_order_seq,date_collected,date_report,report_status) values(?,?,?,?,'final')\", array($img_procedure_id,$img_order['procedure_order_seq'],$img_order['date_collected'],$report_date));\n }", " $img_result = sqlQuery(\"select * from procedure_result where procedure_report_id = ? and document_id = ?\", array($img_report_id,$document_id));\n if (empty($img_result)) {\n sqlStatement(\"INSERT INTO procedure_result(procedure_report_id,date,document_id,result_status) values(?,?,?,'final')\", array($img_report_id,date('Y-m-d H:i:s'),$document_id));\n }", " $this->image_result_indication($document_id, 0, $img_procedure_id);\n }\n return $this->view_action($patient_id, $document_id);\n }", " public function clear_procedure_tag_action(string $patient_id = null, $document_id)\n {\n if (is_numeric($document_id)) {\n sqlStatement(\"delete from procedure_result where document_id = ?\", $document_id);\n }\n return $this->view_action($patient_id, $document_id);\n }", " public function get_mapped_procedure($document_id)\n {\n $map = array();\n if (is_numeric($document_id)) {\n $map = sqlQuery(\"select poc.procedure_order_id,poc.procedure_code from procedure_result pres\n\t\t\t\t\t\t inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id\n\t\t\t\t\t\t inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)\n\t\t\t\t\t\t inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id\n\t\t\t\t\t\t where pres.document_id = ?\", array($document_id));\n }\n return $map;\n }", " public function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)\n {\n $doc_notes = sqlQuery(\"select note from notes where foreign_id = ?\", array($doc_id));\n $narration = isset($doc_notes['note']) ? 'With Narration' : 'Without Narration';", " // TODO: This should be moved into a service so we can handle things such as uuid generation....\n if ($encounter != 0) {\n $ep = sqlQuery(\"select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?\", array($encounter));\n } elseif ($image_procedure_id != 0) {\n $ep = sqlQuery(\"select u.username as assigned_to from procedure_order inner join users u on u.id = provider_id where procedure_order_id = ?\", array($image_procedure_id));\n } else {\n $ep = array('assigned_to' => $_SESSION['authUser']);\n }", " $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];\n $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');\n setGpRelation(1, $doc_id, 6, $noteid);\n }", "//clear encounter tag public function\n public function clear_encounter_tag_action(string $patient_id = null, $document_id)\n {\n if (is_numeric($document_id)) {\n sqlStatement(\"update documents set encounter_id='0' where foreign_id=? and id = ?\", array($patient_id,$document_id));\n }\n return $this->view_action($patient_id, $document_id);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [303], "buggy_code_start_loc": [277], "filenames": ["controllers/C_Document.class.php"], "fixing_code_end_loc": [311], "fixing_code_start_loc": [276], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository openemr/openemr prior to 7.0.0.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "C397DED6-5350-43A0-B65D-FB92E8587CED", "versionEndExcluding": "7.0.0.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository openemr/openemr prior to 7.0.0.2."}], "evaluatorComment": null, "id": "CVE-2022-4506", "lastModified": "2022-12-16T15:09:39.797", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-15T01:15:11.227", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/2e7678d812df167ea3c0756382408b670e8aa51f"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/f423d193-4ab0-4f03-ad90-25e4f02e7942"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/2e7678d812df167ea3c0756382408b670e8aa51f"}, "type": "CWE-434"}
25
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * C_Document.class.php\n *\n * @package OpenEMR\n * @link https://www.open-emr.org\n * @author Brady Miller <brady.g.miller@gmail.com>\n * @copyright Copyright (c) 2019 Brady Miller <brady.g.miller@gmail.com>\n * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3\n */", "require_once(__DIR__ . \"/../library/forms.inc\");\nrequire_once(__DIR__ . \"/../library/patient.inc\");", "use OpenEMR\\Common\\Acl\\AclMain;\nuse OpenEMR\\Common\\Crypto\\CryptoGen;\nuse OpenEMR\\Common\\Csrf\\CsrfUtils;\nuse OpenEMR\\Common\\Twig\\TwigContainer;\nuse OpenEMR\\Services\\FacilityService;\nuse OpenEMR\\Services\\PatientService;\nuse OpenEMR\\Events\\PatientDocuments\\PatientDocumentTreeViewFilterEvent;", "class C_Document extends Controller\n{\n public $documents;\n public $document_categories;\n public $tree;\n public $_config;\n public $manual_set_owner = false; // allows manual setting of a document owner/service\n public $facilityService;\n public $patientService;\n public $_last_node;\n private $Document;\n private $cryptoGen;", " public function __construct($template_mod = \"general\")\n {\n parent::__construct();\n $this->facilityService = new FacilityService();\n $this->patientService = new PatientService();\n $this->documents = array();\n $this->template_mod = $template_mod;\n $this->assign(\"FORM_ACTION\", $GLOBALS['webroot'] . \"/controller.php?\" . attr($_SERVER['QUERY_STRING'] ?? ''));\n $this->assign(\"CURRENT_ACTION\", $GLOBALS['webroot'] . \"/controller.php?\" . \"document&\");", " if (php_sapi_name() !== 'cli') {\n // skip when this is being called via command line for the ccda importing\n $this->assign(\"CSRF_TOKEN_FORM\", CsrfUtils::collectCsrfToken());\n }", " $this->assign(\"IMAGES_STATIC_RELATIVE\", $GLOBALS['images_static_relative']);", " //get global config options for this namespace\n $this->_config = $GLOBALS['oer_config']['documents'];", " $this->_args = array(\"patient_id\" => ($_GET['patient_id'] ?? null));", " $this->assign(\"STYLE\", $GLOBALS['style']);\n $t = new CategoryTree(1);\n //print_r($t->tree);\n $this->tree = $t;\n $this->Document = new Document();", " // Create a crypto object that will be used for for encryption/decryption\n $this->cryptoGen = new CryptoGen();\n }", " public function upload_action($patient_id, $category_id)\n {\n $category_name = $this->tree->get_node_name($category_id);\n $this->assign(\"category_id\", $category_id);\n $this->assign(\"category_name\", $category_name);\n $this->assign(\"hide_encryption\", $GLOBALS['hide_document_encryption']);\n $this->assign(\"patient_id\", $patient_id);", " // Added by Rod to support document template download from general_upload.html.\n // Cloned from similar stuff in manage_document_templates.php.\n $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/doctemplates';\n $templates_options = \"<option value=''>-- \" . xlt('Select Template') . \" --</option>\";\n if (file_exists($templatedir)) {\n $dh = opendir($templatedir);\n }\n if (!empty($dh)) {\n $templateslist = array();\n while (false !== ($sfname = readdir($dh))) {\n if (substr($sfname, 0, 1) == '.') {\n continue;\n }\n $templateslist[$sfname] = $sfname;\n }\n closedir($dh);\n ksort($templateslist);\n foreach ($templateslist as $sfname) {\n $templates_options .= \"<option value='\" . attr($sfname) .\n \"'>\" . text($sfname) . \"</option>\";\n }\n }\n $this->assign(\"TEMPLATES_LIST\", $templates_options);", " // duplicate template list for new template form editor sjp 05/20/2019\n // will call as module or individual template.\n $templatedir = $GLOBALS['OE_SITE_DIR'] . '/documents/onsite_portal_documents/templates';\n $templates_options = \"<option value=''>-- \" . xlt('Open Forms Module') . \" --</option>\";\n if (file_exists($templatedir)) {\n $dh = opendir($templatedir);\n }\n if ($dh) {\n $templateslist = array();\n while (false !== ($sfname = readdir($dh))) {\n if (substr($sfname, 0, 1) == '.') {\n continue;\n }\n if (substr(strtolower($sfname), strlen($sfname) - 4) == '.tpl') {\n $templateslist[$sfname] = $sfname;\n }\n }\n closedir($dh);\n ksort($templateslist);\n foreach ($templateslist as $sfname) {\n $optname = str_replace('_', ' ', basename($sfname, \".tpl\"));\n $templates_options .= \"<option value='\" . attr($sfname) . \"'>\" . text($optname) . \"</option>\";\n }\n }\n $this->assign(\"TEMPLATES_LIST_PATIENT\", $templates_options);", " $activity = $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_upload.html\");\n $this->assign(\"activity\", $activity);\n return $this->list_action($patient_id);\n }", " public function zip_dicom_folder($study_name = null)\n {\n $zip = new ZipArchive();\n $zip_name = $GLOBALS['temporary_files_dir'] . \"/\" . $study_name;\n if ($zip->open($zip_name, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) === true) {\n foreach ($_FILES['dicom_folder']['name'] as $i => $name) {\n $zfn = $GLOBALS['temporary_files_dir'] . \"/\" . $name;\n $fparts = pathinfo($name);\n if (empty($fparts['extension'])) {\n // viewer requires lowercase.\n $fparts['extension'] = \"dcm\";\n $name = $fparts['filename'] . \".dcm\";\n }\n if ($fparts['extension'] == \"DCM\") {\n // viewer requires lowercase.\n $fparts['extension'] = \"dcm\";\n $name = $fparts['filename'] . \".dcm\";\n }\n // required extension for viewer\n if ($fparts['extension'] != \"dcm\") {\n continue;\n }\n move_uploaded_file($_FILES['dicom_folder']['tmp_name'][$i], $zfn);\n $zip->addFile($zfn, $name);\n }\n $zip->close();\n } else {\n return false;\n }\n $file_array['name'][] = $study_name;\n $file_array['type'][] = 'zip';\n $file_array['tmp_name'][] = $zip_name;\n $file_array['error'][] = '';\n $file_array['size'][] = filesize($zip_name);\n return $file_array;\n }", " //Upload multiple files on single click\n public function upload_action_process()\n {", " // Collect a manually set owner if this has been set\n // Used when want to manually assign the owning user/service such as the Direct mechanism\n $non_HTTP_owner = false;\n if ($this->manual_set_owner) {\n $non_HTTP_owner = $this->manual_set_owner;\n }", " $couchDB = false;\n $harddisk = false;\n if ($GLOBALS['document_storage_method'] == 0) {\n $harddisk = true;\n }\n if ($GLOBALS['document_storage_method'] == 1) {\n $couchDB = true;\n }", " if ($_POST['process'] != \"true\") {\n return;\n }", " $doDecryption = false;\n $encrypted = $_POST['encrypted'] ?? false;\n $passphrase = $_POST['passphrase'] ?? '';\n if (\n !$GLOBALS['hide_document_encryption'] &&\n $encrypted && $passphrase\n ) {\n $doDecryption = true;\n }", " if (is_numeric($_POST['category_id'])) {\n $category_id = $_POST['category_id'];\n }", " $patient_id = 0;\n if (isset($_GET['patient_id']) && !$couchDB) {\n $patient_id = $_GET['patient_id'];\n } elseif (is_numeric($_POST['patient_id'])) {\n $patient_id = $_POST['patient_id'];\n }", " if (!empty($_FILES['dicom_folder']['name'][0])) {\n // let's zip um up then pass along new zip\n $study_name = $_POST['destination'] ? (trim($_POST['destination']) . \".zip\") : 'DicomStudy.zip';\n $study_name = preg_replace('/\\s+/', '_', $study_name);\n $_POST['destination'] = \"\";\n $zipped = $this->zip_dicom_folder($study_name);\n if ($zipped) {\n $_FILES['file'] = $zipped;\n }\n // and off we go! just fall through and let routine\n // do its normal file processing..\n }", " $sentUploadStatus = array();\n if (count($_FILES['file']['name']) > 0) {\n $upl_inc = 0;", " foreach ($_FILES['file']['name'] as $key => $value) {\n $fname = $value;\n $error = \"\";\n if ($_FILES['file']['error'][$key] > 0 || empty($fname) || $_FILES['file']['size'][$key] == 0) {\n $fname = $value;\n if (empty($fname)) {\n $fname = htmlentities(\"<empty>\");\n }\n $error = xl(\"Error number\") . \": \" . $_FILES['file']['error'][$key] . \" \" . xl(\"occurred while uploading file named\") . \": \" . $fname . \"\\n\";\n if ($_FILES['file']['size'][$key] == 0) {\n $error .= xl(\"The system does not permit uploading files of with size 0.\") . \"\\n\";\n }\n } elseif ($GLOBALS['secure_upload'] && !isWhiteFile($_FILES['file']['tmp_name'][$key])) {\n $error = xl(\"The system does not permit uploading files with MIME content type\") . \" - \" . mime_content_type($_FILES['file']['tmp_name'][$key]) . \".\\n\";\n } else {\n // Test for a zip of DICOM images\n if (stripos($_FILES['file']['type'][$key], 'zip') !== false) {\n $za = new ZipArchive();\n $handler = $za->open($_FILES['file']['tmp_name'][$key]);\n if ($handler) {\n $mimetype = \"application/dicom+zip\";\n for ($i = 0; $i < $za->numFiles; $i++) {\n $stat = $za->statIndex($i);\n $fp = $za->getStream($stat['name']);\n if ($fp) {\n $head = fread($fp, 256);\n fclose($fp);\n if (strpos($head, 'DICM') === false) { // Fixed at offset 128. even one non DICOM makes zip invalid.\n $mimetype = \"application/zip\";\n break;\n }\n unset($head);\n // if here -then a DICOM\n $parts = pathinfo($stat['name']);\n if ($parts['extension'] != \"dcm\" || empty($parts['extension'])) { // required extension for viewer\n $new_name = $parts['filename'] . \".dcm\";\n $za->renameIndex($i, $new_name);\n $za->renameName($parts['filename'], $new_name);\n }\n } else { // Rarely here\n $mimetype = \"application/zip\";\n break;\n }\n }\n $za->close();\n if ($mimetype == \"application/dicom+zip\") {", "", " sleep(1); // Timing insurance in case of re-compression. Only acted on index so...!\n $_FILES['file']['size'][$key] = filesize($_FILES['file']['tmp_name'][$key]); // file may have grown.\n }\n }\n }\n $tmpfile = fopen($_FILES['file']['tmp_name'][$key], \"r\");\n $filetext = fread($tmpfile, $_FILES['file']['size'][$key]);\n fclose($tmpfile);\n if ($doDecryption) {\n $filetext = $this->cryptoGen->decryptStandard($filetext, $passphrase);\n if ($filetext === false) {\n error_log(\"OpenEMR Error: Unable to decrypt a document since decryption failed.\");\n $filetext = \"\";\n }\n }\n if ($_POST['destination'] != '') {\n $fname = $_POST['destination'];\n }", " // test for single DICOM and assign extension if missing.", " if (strpos($filetext, 'DICM') !== false) {\n $mimetype = 'application/dicom';\n $parts = pathinfo($fname);\n if (!$parts['extension']) {\n $fname .= '.dcm';\n }", " }\n // set mimetype (if not already set above)\n if (empty($mimetype)) {\n $mimetype = mime_content_type($_FILES['file']['tmp_name'][$key]);\n }\n // if mimetype still empty, then do not upload the file\n if (empty($mimetype)) {\n $error = xl(\"Unable to discover mimetype, so did not upload \" . $_FILES['file']['tmp_name'][$key]) . \".\\n\";\n continue;", " }\n $d = new Document();\n $rc = $d->createDocument(\n $patient_id,\n $category_id,\n $fname,\n $mimetype,\n $filetext,\n empty($_GET['higher_level_path']) ? '' : $_GET['higher_level_path'],\n empty($_POST['path_depth']) ? 1 : $_POST['path_depth'],\n $non_HTTP_owner,\n $_FILES['file']['tmp_name'][$key]\n );\n if ($rc) {\n $error .= $rc . \"\\n\";\n } else {\n $this->assign(\"upload_success\", \"true\");\n }\n $sentUploadStatus[] = $d;\n $this->assign(\"file\", $sentUploadStatus);\n }", " // Option to run a custom plugin for each file upload.\n // This was initially created to delete the original source file in a custom setting.\n $upload_plugin = $GLOBALS['OE_SITE_DIR'] . \"/documentUpload.plugin.php\";\n if (file_exists($upload_plugin)) {\n include_once($upload_plugin);\n }\n $upload_plugin_pp = 'documentUploadPostProcess';\n if (function_exists($upload_plugin_pp)) {\n $tmp = call_user_func($upload_plugin_pp, $value, $d);\n if ($tmp) {\n $error = $tmp;\n }\n }\n // Following is just an example of code in such a plugin file.\n /*****************************************************\n public function documentUploadPostProcess($filename, &$d) {\n $userid = $_SESSION['authUserID'];\n $row = sqlQuery(\"SELECT username FROM users WHERE id = ?\", array($userid));\n $owner = strtolower($row['username']);\n $dn = '1_' . ucfirst($owner);\n $filepath = \"/shared_network_directory/$dn/$filename\";\n if (@unlink($filepath)) return '';\n return \"Failed to delete '$filepath'.\";\n }\n *****************************************************/\n }\n }", " $this->assign(\"error\", $error);\n //$this->_state = false;\n $_POST['process'] = \"\";\n //return $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_upload.html\");\n }", " public function note_action_process($patient_id)\n {\n // this public function is a dual public function that will set up a note associated with a document or send a document via email.", " if ($_POST['process'] != \"true\") {\n return;\n }", " $n = new Note();\n $n->set_owner($_SESSION['authUserID']);\n parent::populate_object($n);\n if ($_POST['identifier'] == \"no\") {\n // associate a note with a document\n $n->persist();\n } elseif ($_POST['identifier'] == \"yes\") {\n // send the document via email\n $d = new Document($_POST['foreign_id']);\n $url = $d->get_url();\n $storagemethod = $d->get_storagemethod();\n $couch_docid = $d->get_couch_docid();\n $couch_revid = $d->get_couch_revid();\n if ($couch_docid && $couch_revid) {\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc($couch_docid);\n $content = $resp->data;\n if ($content == '' && $GLOBALS['couchdb_log'] == 1) {\n $log_content = date('Y-m-d H:i:s') . \" ==> Retrieving document\\r\\n\";\n $log_content = date('Y-m-d H:i:s') . \" ==> URL: \" . $url . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Document Id: \" . $couch_docid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Revision Id: \" . $couch_revid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Failed to fetch document content from CouchDB.\\r\\n\";\n //$log_content .= date('Y-m-d H:i:s').\" ==> Will try to download file from HardDisk if exists.\\r\\n\\r\\n\";\n $this->document_upload_download_log($d->get_foreign_id(), $log_content);\n die(xlt(\"File retrieval from CouchDB failed\"));\n }\n // place it in a temporary file and will remove the file below after emailed\n $temp_couchdb_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/couch_' . date(\"YmdHis\") . $d->get_url_file();\n $fh = fopen($temp_couchdb_url, \"w\");\n fwrite($fh, base64_decode($content));\n fclose($fh);\n $temp_url = $temp_couchdb_url; // doing this ensure hard drive file never deleted in case something weird happens\n } else {\n $url = preg_replace(\"|^(.*)://|\", \"\", $url);\n // Collect filename and path\n $from_all = explode(\"/\", $url);\n $from_filename = array_pop($from_all);\n $from_pathname_array = array();\n for ($i = 0; $i < $d->get_path_depth(); $i++) {\n $from_pathname_array[] = array_pop($from_all);\n }\n $from_pathname_array = array_reverse($from_pathname_array);\n $from_pathname = implode(\"/\", $from_pathname_array);\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;\n }\n if (!file_exists($temp_url)) {\n echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $temp_url;\n }\n $url = $temp_url;\n $pdetails = getPatientData($patient_id);\n $pname = $pdetails['fname'] . \" \" . $pdetails['lname'];\n $this->document_send($_POST['provide_email'], $_POST['note'], $url, $pname);\n if ($couch_docid && $couch_revid) {\n // remove the temporary couchdb file\n unlink($temp_couchdb_url);\n }\n }\n $this->_state = false;\n $_POST['process'] = \"\";\n return $this->view_action($patient_id, $n->get_foreign_id());\n }", " public function default_action()\n {\n return $this->list_action();\n }", " public function view_action(string $patient_id = null, $doc_id)\n {\n global $ISSUE_TYPES;", " require_once(dirname(__FILE__) . \"/../library/lists.inc\");", " $d = new Document($doc_id);\n $notes = $d->get_notes();", " $this->assign(\"csrf_token_form\", CsrfUtils::collectCsrfToken());", " $this->assign(\"file\", $d);\n $this->assign(\"web_path\", $this->_link(\"retrieve\") . \"document_id=\" . urlencode($d->get_id()) . \"&\");\n $this->assign(\"NOTE_ACTION\", $this->_link(\"note\"));\n $this->assign(\"MOVE_ACTION\", $this->_link(\"move\") . \"document_id=\" . urlencode($d->get_id()) . \"&process=true\");\n $this->assign(\"hide_encryption\", $GLOBALS['hide_document_encryption']);\n $this->assign(\"assets_static_relative\", $GLOBALS['assets_static_relative']);\n $this->assign(\"webroot\", $GLOBALS['webroot']);", " // Added by Rod to support document delete:\n $delete_string = '';\n if (AclMain::aclCheckCore('patients', 'docs_rm')) {\n $delete_string = \"<a href='' class='btn btn-danger' onclick='return deleteme(\" . attr_js($d->get_id()) .\n \")'>\" . xlt('Delete') . \"</a>\";\n }\n $this->assign(\"delete_string\", $delete_string);\n $this->assign(\"REFRESH_ACTION\", $this->_link(\"list\"));", " $this->assign(\"VALIDATE_ACTION\", $this->_link(\"validate\") .\n \"document_id=\" . $d->get_id() . \"&process=true\");", " // Added by Rod to support document date update:\n $this->assign(\"DOCDATE\", $d->get_docdate());\n $this->assign(\"UPDATE_ACTION\", $this->_link(\"update\") .\n \"document_id=\" . $d->get_id() . \"&process=true\");", " // Added by Rod to support document issue update:\n $issues_options = \"<option value='0'>-- \" . xlt('Select Issue') . \" --</option>\";\n $ires = sqlStatement(\"SELECT id, type, title, begdate FROM lists WHERE \" .\n \"pid = ? \" . // AND enddate IS NULL \" .\n \"ORDER BY type, begdate\", array($patient_id));\n while ($irow = sqlFetchArray($ires)) {\n $desc = $irow['type'];\n if ($ISSUE_TYPES[$desc]) {\n $desc = $ISSUE_TYPES[$desc][2];\n }\n $desc .= \": \" . text($irow['begdate']) . \" \" . text(substr($irow['title'], 0, 40));\n $sel = ($irow['id'] == $d->get_list_id()) ? ' selected' : '';\n $issues_options .= \"<option value='\" . attr($irow['id']) . \"'$sel>$desc</option>\";\n }\n $this->assign(\"ISSUES_LIST\", $issues_options);", " // For tagging to encounter\n // Populate the dropdown with patient's encounter list\n $this->assign(\"TAG_ACTION\", $this->_link(\"tag\") . \"document_id=\" . urlencode($d->get_id()) . \"&process=true\");\n $encOptions = \"<option value='0'>-- \" . xlt('Select Encounter') . \" --</option>\";\n $result_docs = sqlStatement(\"SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe \" .\n \"LEFT JOIN openemr_postcalendar_categories ON fe.pc_catid=openemr_postcalendar_categories.pc_catid WHERE fe.pid = ? ORDER BY fe.date desc\", array($patient_id));\n if (sqlNumRows($result_docs) > 0) {\n while ($row_result_docs = sqlFetchArray($result_docs)) {\n $sel_enc = ($row_result_docs['encounter'] == $d->get_encounter_id()) ? ' selected' : '';\n $encOptions .= \"<option value='\" . attr($row_result_docs['encounter']) . \"' $sel_enc>\" . text(oeFormatShortDate(date('Y-m-d', strtotime($row_result_docs['date'])))) . \"-\" . text(xl_appt_category($row_result_docs['pc_catname'])) . \"</option>\";\n }\n }\n $this->assign(\"ENC_LIST\", $encOptions);", " //clear encounter tag\n if ($d->get_encounter_id() != 0) {\n $this->assign('clear_encounter_tag', $this->_link('clear_encounter_tag') . \"document_id=\" . urlencode($d->get_id()));\n } else {\n $this->assign('clear_encounter_tag', 'javascript:void(0)');\n }", " //Populate the dropdown with category list\n $visit_category_list = \"<option value='0'>-- \" . xlt('Select One') . \" --</option>\";\n $cres = sqlStatement(\"SELECT pc_catid, pc_catname FROM openemr_postcalendar_categories ORDER BY pc_catname\");\n while ($crow = sqlFetchArray($cres)) {\n $catid = $crow['pc_catid'];\n if ($catid < 9 && $catid != 5) {\n continue; // Applying same logic as in new encounter page.\n }\n $visit_category_list .= \"<option value='\" . attr($catid) . \"'>\" . text(xl_appt_category($crow['pc_catname'])) . \"</option>\\n\";\n }\n $this->assign(\"VISIT_CATEGORY_LIST\", $visit_category_list);", " $this->assign(\"notes\", $notes);", " $this->assign(\"PROCEDURE_TAG_ACTION\", $this->_link(\"image_procedure\") . \"document_id=\" . urlencode($d->get_id()));\n // Populate the dropdown with procedure order list\n $imgOptions = \"<option value='0'>-- \" . xlt('Select Procedure') . \" --</option>\";\n $imgOrders = sqlStatement(\"select procedure_name,po.procedure_order_id,procedure_code,poc.procedure_order_title from procedure_order po inner join procedure_order_code poc on poc.procedure_order_id = po.procedure_order_id where po.patient_id = ?\", array($patient_id));\n $mapping = $this->get_mapped_procedure($d->get_id());\n if (sqlNumRows($imgOrders) > 0) {\n while ($row = sqlFetchArray($imgOrders)) {\n $sel_proc = '';\n if ((isset($mapping['procedure_code']) && $mapping['procedure_code'] == $row['procedure_code']) && (isset($mapping['procedure_code']) && $mapping['procedure_order_id'] == $row['procedure_order_id'])) {\n $sel_proc = 'selected';\n }\n $imgOptions .= \"<option value='\" . attr($row['procedure_order_id']) . \"' data-code='\" . attr($row['procedure_code']) . \"' $sel_proc>\" . text($row['procedure_name'] . ' - ' . $row['procedure_code'] . ' : ' . ucfirst($row['procedure_order_title'])) . \"</option>\";\n }\n }", " $this->assign('TAG_PROCEDURE_LIST', $imgOptions);", " $this->assign('clear_procedure_tag', $this->_link('clear_procedure_tag') . \"document_id=\" . urlencode($d->get_id()));", " $this->_last_node = null;", " $menu = new HTML_TreeMenu();", " //pass an empty array because we don't want the documents for each category showing up in this list box\n $rnode = $this->array_recurse($this->tree->tree, $patient_id, array());\n $menu->addItem($rnode);\n $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array(\"promoText\" => xl('Move Document to Category:')));", " $this->assign(\"tree_html_listbox\", $treeMenu_listbox->toHTML());", " $activity = $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_view.html\");\n $this->assign(\"activity\", $activity);", " return $this->list_action($patient_id);\n }", " /**\n * Retrieve file from hard disk / CouchDB.\n * In case that file isn't download this public function will return thumbnail image (if exist).\n * @param (boolean) $show_original - enable to show the original image (not thumbnail) in inline status.\n * @param (string) $context - given a special document scenario (e.g.: patient avatar, custom image viewer document, etc), the context can be set so that a switch statement can execute a custom strategy.\n * */\n public function retrieve_action(string $patient_id = null, $document_id, $as_file = true, $original_file = true, $disable_exit = false, $show_original = false, $context = \"normal\")\n {\n $encrypted = $_POST['encrypted'] ?? false;\n $passphrase = $_POST['passphrase'] ?? '';\n $doEncryption = false;\n if (\n !$GLOBALS['hide_document_encryption'] &&\n $encrypted == \"true\" &&\n $passphrase\n ) {\n $doEncryption = true;\n }", " //controller public function ruins booleans, so need to manually re-convert to booleans\n if ($as_file == \"true\") {\n $as_file = true;\n } elseif ($as_file == \"false\") {\n $as_file = false;\n }\n if ($original_file == \"true\") {\n $original_file = true;\n } elseif ($original_file == \"false\") {\n $original_file = false;\n }\n if ($disable_exit == \"true\") {\n $disable_exit = true;\n } elseif ($disable_exit == \"false\") {\n $disable_exit = false;\n }\n if ($show_original == \"true\") {\n $show_original = true;\n } elseif ($show_original == \"false\") {\n $show_original = false;\n }", " switch ($context) {\n case \"patient_picture\":\n $document_id = $this->patientService->getPatientPictureDocumentId($patient_id);\n break;\n }", " $d = new Document($document_id);\n $url = $d->get_url();\n $th_url = $d->get_thumb_url();", " $storagemethod = $d->get_storagemethod();\n $couch_docid = $d->get_couch_docid();\n $couch_revid = $d->get_couch_revid();", " if ($couch_docid && $couch_revid && $original_file) {\n // standard case for collecting a document from couchdb\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc($couch_docid);\n //Take thumbnail file when is not null and file is presented online\n if (!$as_file && !is_null($th_url) && !$show_original) {\n $content = $resp->th_data;\n } else {\n $content = $resp->data;\n }\n if ($content == '' && $GLOBALS['couchdb_log'] == 1) {\n $log_content = date('Y-m-d H:i:s') . \" ==> Retrieving document\\r\\n\";\n $log_content = date('Y-m-d H:i:s') . \" ==> URL: \" . $url . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Document Id: \" . $couch_docid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Revision Id: \" . $couch_revid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Failed to fetch document content from CouchDB.\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Will try to download file from HardDisk if exists.\\r\\n\\r\\n\";\n $this->document_upload_download_log($d->get_foreign_id(), $log_content);\n die(xlt(\"File retrieval from CouchDB failed\"));\n }\n if ($d->get_encrypted() == 1) {\n $filetext = $this->cryptoGen->decryptStandard($content, null, 'database');\n } else {\n $filetext = base64_decode($content);\n }\n if ($disable_exit == true) {\n return $filetext;\n }\n header('Content-Description: File Transfer');\n header('Content-Transfer-Encoding: binary');\n header('Expires: 0');\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n if ($doEncryption) {\n $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);\n header('Content-Disposition: attachment; filename=\"' . \"/encrypted_aes_\" . $d->get_name() . '\"');\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Length: \" . strlen($ciphertext));\n echo $ciphertext;\n } else {\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: \" . $d->get_mimetype());\n header(\"Content-Length: \" . strlen($filetext));\n echo $filetext;\n }\n exit;//exits only if file download from CouchDB is successfull.\n }\n if ($couch_docid && $couch_revid) {\n //special case when retrieving a document from couchdb that has been converted to a jpg and not directly referenced in openemr documents table\n //try to convert it if it has not yet been converted\n //first, see if the converted jpg already exists\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc(\"converted_\" . $couch_docid);\n $content = $resp->data;\n if ($content == '') {\n //create the converted jpg\n $couchM = new CouchDB();\n $respM = $couchM->retrieve_doc($couch_docid);\n if ($d->get_encrypted() == 1) {\n $contentM = $this->cryptoGen->decryptStandard($respM->data, null, 'database');\n } else {\n $contentM = base64_decode($respM->data);\n }\n if ($contentM == '' && $GLOBALS['couchdb_log'] == 1) {\n $log_content = date('Y-m-d H:i:s') . \" ==> Retrieving document\\r\\n\";\n $log_content = date('Y-m-d H:i:s') . \" ==> URL: \" . $url . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Document Id: \" . $couch_docid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> CouchDB Revision Id: \" . $couch_revid . \"\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Failed to fetch document content from CouchDB.\\r\\n\";\n $log_content .= date('Y-m-d H:i:s') . \" ==> Will try to download file from HardDisk if exists.\\r\\n\\r\\n\";\n $this->document_upload_download_log($d->get_foreign_id(), $log_content);\n die(xlt(\"File retrieval from CouchDB failed\"));\n }\n // place the from-file into a temporary file\n $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n file_put_contents($from_file_tmp_name, $contentM);\n // prepare a temporary file for the to-file\n $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n $to_file_tmp_name = $to_file_tmp . \".jpg\";\n // convert file to jpg\n exec(\"convert -density 200 \" . escapeshellarg($from_file_tmp_name) . \" -append -resize 850 \" . escapeshellarg($to_file_tmp_name));\n // remove from tmp file\n unlink($from_file_tmp_name);\n // save the to-file if a to-file was created in above convert call\n if (is_file($to_file_tmp_name)) {\n $couchI = new CouchDB();\n if ($d->get_encrypted() == 1) {\n $document = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');\n } else {\n $document = base64_encode(file_get_contents($to_file_tmp_name));\n }\n $couchI->save_doc(['_id' => \"converted_\" . $couch_docid, 'data' => $document]);\n // remove to tmp files\n unlink($to_file_tmp);\n unlink($to_file_tmp_name);\n } else {\n error_log(\"ERROR: Document '\" . errorLogEscape($d->get_name()) . \"' cannot be converted to JPEG. Perhaps ImageMagick is not installed?\");\n }\n // now collect the newly created converted jpg\n $couchF = new CouchDB();\n $respF = $couchF->retrieve_doc(\"converted_\" . $couch_docid);\n if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard($respF->data, null, 'database');\n } else {\n $content = base64_decode($respF->data);\n }\n } else {\n // decrypt/decode when converted jpg already exists\n if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');\n } else {\n $content = base64_decode($resp->data);\n }\n }\n $filetext = $content;\n if ($disable_exit == true) {\n return $filetext;\n }\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: image/jpeg\");\n header(\"Content-Length: \" . strlen($filetext));\n echo $filetext;\n exit;\n }", " //Take thumbnail file when is not null and file is presented online\n if (!$as_file && !is_null($th_url) && !$show_original) {\n $url = $th_url;\n }", " //strip url of protocol handler\n $url = preg_replace(\"|^(.*)://|\", \"\", $url);", " //change full path to current webroot. this is for documents that may have\n //been moved from a different filesystem and the full path in the database\n //is not current. this is also for documents that may of been moved to\n //different patients. Note that the path_depth is used to see how far down\n //the path to go. For example, originally the path_depth was always 1, which\n //only allowed things like documents/1/<file>, but now can have more structured\n //directories. For example a path_depth of 2 can give documents/encounters/1/<file>\n // etc.\n // NOTE that $from_filename and basename($url) are the same thing\n $from_all = explode(\"/\", $url);\n $from_filename = array_pop($from_all);\n $from_pathname_array = array();\n for ($i = 0; $i < $d->get_path_depth(); $i++) {\n $from_pathname_array[] = array_pop($from_all);\n }\n $from_pathname_array = array_reverse($from_pathname_array);\n $from_pathname = implode(\"/\", $from_pathname_array);\n if ($couch_docid && $couch_revid) {\n //for couchDB no URL is available in the table, hence using the foreign_id which is patientID\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/' . $d->get_foreign_id() . '_' . $from_filename;\n } else {\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;\n }", " if (file_exists($temp_url)) {\n $url = $temp_url;\n }", " if (!file_exists($url)) {\n echo xl('The requested document is not present at the expected location on the filesystem or there are not sufficient permissions to access it.', '', '', ' ') . $url;\n } else {\n if ($original_file) {\n //normal case when serving the file referenced in database\n if ($d->get_encrypted() == 1) {\n $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');\n } else {\n if (!is_dir($url)) {\n $filetext = file_get_contents($url);\n }\n }\n if ($disable_exit == true) {\n return $filetext ?? '';\n }\n header('Content-Description: File Transfer');\n header('Content-Transfer-Encoding: binary');\n header('Expires: 0');\n header('Cache-Control: must-revalidate, post-check=0, pre-check=0');\n header('Pragma: public');\n if ($doEncryption) {\n $ciphertext = $this->cryptoGen->encryptStandard($filetext, $passphrase);\n header('Content-Disposition: attachment; filename=\"' . \"/encrypted_aes_\" . $d->get_name() . '\"');\n header(\"Content-Type: application/octet-stream\");\n header(\"Content-Length: \" . strlen($ciphertext));\n echo $ciphertext;\n } else {\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: \" . $d->get_mimetype());\n header(\"Content-Length: \" . strlen($filetext ?? ''));\n echo $filetext ?? '';\n }\n exit;\n } else {\n //special case when retrieving a document that has been converted to a jpg and not directly referenced in database\n //try to convert it if it has not yet been converted\n $originalUrl = $url;\n if (strrpos(basename_international($url), '.') === false) {\n $convertedFile = basename_international($url) . '_converted.jpg';\n } else {\n $convertedFile = substr(basename_international($url), 0, strrpos(basename_international($url), '.')) . '_converted.jpg';\n }\n $url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $convertedFile;\n if (!is_file($url)) {\n if ($d->get_encrypted() == 1) {\n // decrypt the from-file into a temporary file\n $from_file_unencrypted = $this->cryptoGen->decryptStandard(file_get_contents($originalUrl), null, 'database');\n $from_file_tmp_name = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n file_put_contents($from_file_tmp_name, $from_file_unencrypted);\n // prepare a temporary file for the unencrypted to-file\n $to_file_tmp = tempnam($GLOBALS['temporary_files_dir'], \"oer\");\n $to_file_tmp_name = $to_file_tmp . \".jpg\";\n // convert file to jpg\n exec(\"convert -density 200 \" . escapeshellarg($from_file_tmp_name) . \" -append -resize 850 \" . escapeshellarg($to_file_tmp_name));\n // remove unencrypted tmp file\n unlink($from_file_tmp_name);\n // make the encrypted to-file if a to-file was created in above convert call\n if (is_file($to_file_tmp_name)) {\n $to_file_encrypted = $this->cryptoGen->encryptStandard(file_get_contents($to_file_tmp_name), null, 'database');\n file_put_contents($url, $to_file_encrypted);\n // remove unencrypted tmp files\n unlink($to_file_tmp);\n unlink($to_file_tmp_name);\n }\n } else {\n // convert file to jpg\n exec(\"convert -density 200 \" . escapeshellarg($originalUrl) . \" -append -resize 850 \" . escapeshellarg($url));\n }\n }\n if (is_file($url)) {\n if ($d->get_encrypted() == 1) {\n $filetext = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');\n } else {\n $filetext = file_get_contents($url);\n }\n } else {\n $filetext = '';\n error_log(\"ERROR: Document '\" . errorLogEscape(basename_international($url)) . \"' cannot be converted to JPEG. Perhaps ImageMagick is not installed?\");\n }\n if ($disable_exit == true) {\n return $filetext;\n }\n header(\"Pragma: public\");\n header(\"Expires: 0\");\n header(\"Cache-Control: must-revalidate, post-check=0, pre-check=0\");\n header(\"Content-Disposition: \" . ($as_file ? \"attachment\" : \"inline\") . \"; filename=\\\"\" . $d->get_name() . \"\\\"\");\n header(\"Content-Type: image/jpeg\");\n header(\"Content-Length: \" . strlen($filetext));\n echo $filetext;\n exit;\n }\n }\n }", " public function move_action_process(string $patient_id = null, $document_id)\n {\n if ($_POST['process'] != \"true\") {\n return;\n }", " $messages = '';", " $new_category_id = $_POST['new_category_id'];\n $new_patient_id = $_POST['new_patient_id'];", " //move to new category\n if (is_numeric($new_category_id) && is_numeric($document_id)) {\n $sql = \"UPDATE categories_to_documents set category_id = ? where document_id = ?\";\n $messages .= xl('Document moved to new category', '', '', ' \\'') . $this->tree->_id_name[$new_category_id]['name'] . xl('successfully.', '', '\\' ') . \"\\n\";\n //echo $sql;\n $this->tree->_db->Execute($sql, [$new_category_id, $document_id]);\n }", " //move to new patient\n if (is_numeric($new_patient_id) && is_numeric($document_id)) {\n $d = new Document($document_id);\n $sql = \"SELECT pid from patient_data where pid = ?\";\n $result = $d->_db->Execute($sql, [$new_patient_id]);", " if (!$result || $result->EOF) {\n //patient id does not exist\n $messages .= xl('Document could not be moved to patient id', '', '', ' \\'') . $new_patient_id . xl('because that id does not exist.', '', '\\' ') . \"\\n\";\n } else {\n $changefailed = !$d->change_patient($new_patient_id);", " $this->_state = false;\n if (!$changefailed) {\n $messages .= xl('Document moved to patient id', '', '', ' \\'') . $new_patient_id . xl('successfully.', '', '\\' ') . \"\\n\";\n } else {\n $messages .= xl('Document moved to patient id', '', '', ' \\'') . $new_patient_id . xl('Failed.', '', '\\' ') . \"\\n\";\n }\n $this->assign(\"messages\", $messages);\n return $this->list_action($patient_id);\n }\n }", " $this->_state = false;\n $this->assign(\"messages\", $messages);\n return $this->view_action($patient_id, $document_id);\n }", " public function validate_action_process(string $patient_id = null, $document_id)\n {", " $d = new Document($document_id);\n if ($d->couch_docid && $d->couch_revid) {\n $file_path = $GLOBALS['OE_SITE_DIR'] . '/documents/temp/';\n $url = $file_path . $d->get_url();\n $couch = new CouchDB();\n $resp = $couch->retrieve_doc($d->couch_docid);\n if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard($resp->data, null, 'database');\n } else {\n $content = base64_decode($resp->data);\n }\n } else {\n $url = $d->get_url();", " //strip url of protocol handler\n $url = preg_replace(\"|^(.*)://|\", \"\", $url);", " //change full path to current webroot. this is for documents that may have\n //been moved from a different filesystem and the full path in the database\n //is not current. this is also for documents that may of been moved to\n //different patients. Note that the path_depth is used to see how far down\n //the path to go. For example, originally the path_depth was always 1, which\n //only allowed things like documents/1/<file>, but now can have more structured\n //directories. For example a path_depth of 2 can give documents/encounters/1/<file>\n // etc.\n // NOTE that $from_filename and basename($url) are the same thing\n $from_all = explode(\"/\", $url);\n $from_filename = array_pop($from_all);\n $from_pathname_array = array();\n for ($i = 0; $i < $d->get_path_depth(); $i++) {\n $from_pathname_array[] = array_pop($from_all);\n }\n $from_pathname_array = array_reverse($from_pathname_array);\n $from_pathname = implode(\"/\", $from_pathname_array);\n $temp_url = $GLOBALS['OE_SITE_DIR'] . '/documents/' . $from_pathname . '/' . $from_filename;\n if (file_exists($temp_url)) {\n $url = $temp_url;\n }", " if ($_POST['process'] != \"true\") {\n die(\"process is '\" . text($_POST['process']) . \"', expected 'true'\");\n return;\n }", " if ($d->get_encrypted() == 1) {\n $content = $this->cryptoGen->decryptStandard(file_get_contents($url), null, 'database');\n } else {\n $content = file_get_contents($url);\n }\n }", " if (!empty($d->get_hash()) && (strlen($d->get_hash()) < 50)) {\n // backward compatibility for documents that were hashed prior to OpenEMR 6.0.0\n $current_hash = sha1($content);\n } else {\n $current_hash = hash('sha3-512', $content);\n }\n $messages = xl('Current Hash') . \": \" . $current_hash . \" | \";\n $messages .= xl('Stored Hash') . \": \" . $d->get_hash();\n if ($d->get_hash() == '') {\n $d->hash = $current_hash;\n $d->persist();\n $d->populate();\n $messages .= xl('Hash did not exist for this file. A new hash was generated.');\n } elseif ($current_hash != $d->get_hash()) {\n $messages .= xl('Hash does not match. Data integrity has been compromised.');\n } else {\n $messages = xl('Document passed integrity check.') . ' | ' . $messages;\n }\n $this->_state = false;\n $this->assign(\"messages\", $messages);\n return $this->view_action($patient_id, $document_id);\n }", " // Added by Rod for metadata update.\n //\n public function update_action_process(string $patient_id = null, $document_id)\n {", " if ($_POST['process'] != \"true\") {\n die(\"process is '\" . $_POST['process'] . \"', expected 'true'\");\n return;\n }", " $docdate = $_POST['docdate'];\n $docname = $_POST['docname'];\n $issue_id = $_POST['issue_id'];", " if (is_numeric($document_id)) {\n $messages = '';\n $d = new Document($document_id);\n $file_name = $d->get_name();\n if (\n $docname != '' &&\n $docname != $file_name\n ) {\n // Rename\n $d->set_name($docname);\n $d->persist();\n $d->populate();\n $messages .= xl('Document successfully renamed.') . \"<br />\";\n }", " if (preg_match('/^\\d\\d\\d\\d-\\d+-\\d+$/', $docdate)) {\n $docdate = \"$docdate\";\n } else {\n $docdate = \"NULL\";\n }\n if (!is_numeric($issue_id)) {\n $issue_id = 0;\n }\n $couch_docid = $d->get_couch_docid();\n $couch_revid = $d->get_couch_revid();\n if ($couch_docid && $couch_revid) {\n $sql = \"UPDATE documents SET docdate = ?, url = ?, list_id = ? WHERE id = ?\";\n $this->tree->_db->Execute($sql, [$docdate, $_POST['docname'], $issue_id, $document_id]);\n } else {\n $sql = \"UPDATE documents SET docdate = ?, list_id = ? WHERE id = ?\";\n $this->tree->_db->Execute($sql, [$docdate, $issue_id, $document_id]);\n }\n $messages .= xl('Document date and issue updated successfully') . \"<br />\";\n }", " $this->_state = false;\n $this->assign(\"messages\", $messages);\n return $this->view_action($patient_id, $document_id);\n }", " public function list_action($patient_id = \"\")\n {\n $this->_last_node = null;\n $categories_list = $this->tree->_get_categories_array($patient_id);\n //print_r($categories_list);", " $menu = new HTML_TreeMenu();\n $rnode = $this->array_recurse($this->tree->tree, $patient_id, $categories_list);\n $menu->addItem($rnode);\n $treeMenu = new HTML_TreeMenu_DHTML($menu, array('images' => 'public/images', 'defaultClass' => 'treeMenuDefault'));\n $treeMenu_listbox = new HTML_TreeMenu_Listbox($menu, array('linkTarget' => '_self'));\n $this->assign(\"tree_html\", $treeMenu->toHTML());", " $is_new = isset($_GET['patient_name']) ? 1 : false;\n $place_hld = isset($_GET['patient_name']) ? filter_input(INPUT_GET, 'patient_name') : xl(\"Patient search or select.\");\n $cur_pid = isset($_GET['patient_id']) ? filter_input(INPUT_GET, 'patient_id') : '';\n $used_msg = xl('Current patient unavailable here. Use Patient Documents');\n if ($cur_pid == '00') {\n if (!AclMain::aclCheckCore('patients', 'docs', '', ['write', 'addonly'])) {\n echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl(\"Documents\")]);\n exit;\n }\n $cur_pid = '0';\n $is_new = 1;\n }\n if (!AclMain::aclCheckCore('patients', 'docs')) {\n echo (new TwigContainer(null, $GLOBALS['kernel']))->getTwig()->render('core/unauthorized.html.twig', ['pageTitle' => xl(\"Documents\")]);\n exit;\n }\n $this->assign('is_new', $is_new);\n $this->assign('place_hld', $place_hld);\n $this->assign('cur_pid', $cur_pid);\n $this->assign('used_msg', $used_msg);\n $this->assign('demo_pid', ($_SESSION['pid'] ?? null));", " return $this->fetch($GLOBALS['template_dir'] . \"documents/\" . $this->template_mod . \"_list.html\");\n }", " public function &array_recurse($array, $patient_id, $categories = array())\n {\n if (!is_array($array)) {\n $array = array();\n }\n $node = &$this->_last_node;\n $current_node = &$node;\n $expandedIcon = 'folder-expanded.gif';\n foreach ($array as $id => $ar) {\n $icon = 'folder.gif';\n if (is_array($ar) || !empty($id)) {\n if ($node == null) {\n //echo \"r:\" . $this->tree->get_node_name($id) . \"<br />\";\n $rnode = new HTML_TreeNode(array(\"id\" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => false));\n $this->_last_node = &$rnode;\n $node = &$rnode;\n $current_node = &$rnode;\n } else {\n //echo \"p:\" . $this->tree->get_node_name($id) . \"<br />\";\n $this->_last_node = &$node->addItem(new HTML_TreeNode(array(\"id\" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));\n $current_node = &$this->_last_node;\n }", " $this->array_recurse($ar, $patient_id, $categories);\n } else {\n if ($id === 0 && !empty($ar)) {\n $info = $this->tree->get_node_info($id);\n //echo \"b:\" . $this->tree->get_node_name($id) . \"<br />\";\n $current_node = &$node->addItem(new HTML_TreeNode(array(\"id\" => $id, 'text' => $info['value'], 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));\n } else {\n //there is a third case that is implicit here when title === 0 and $ar is empty, in that case we do not want to do anything\n //this conditional tree could be more efficient but working with recursive trees makes my head hurt, TODO\n if ($id !== 0 && is_object($node)) {\n //echo \"n:\" . $this->tree->get_node_name($id) . \"<br />\";\n $current_node = &$node->addItem(new HTML_TreeNode(array(\"id\" => $id, 'text' => $this->tree->get_node_name($id), 'link' => $this->_link(\"upload\") . \"parent_id=\" . $id . \"&\", 'icon' => $icon, 'expandedIcon' => $expandedIcon)));\n }\n }\n }", " // If there are documents in this document category, then add their\n // attributes to the current node.\n $icon = \"file3.png\";\n if (!empty($categories[$id]) && is_array($categories[$id])) {\n foreach ($categories[$id] as $doc) {\n $link = $this->_link(\"view\") . \"doc_id=\" . urlencode($doc['document_id']) . \"&\";\n // If user has no access then there will be no link.\n if (!AclMain::aclCheckAcoSpec($doc['aco_spec'])) {\n $link = '';\n }\n // CCD view\n $nodeInfo = $this->tree->get_node_info($id);\n $treeViewFilterEvent = new PatientDocumentTreeViewFilterEvent();\n $treeViewFilterEvent->setCategoryTreeNode($this->tree);\n $treeViewFilterEvent->setDocumentId($doc['document_id']);\n $treeViewFilterEvent->setDocumentName($doc['document_name']);\n $treeViewFilterEvent->setCategoryId($id);\n $treeViewFilterEvent->setCategoryInfo($nodeInfo);\n $treeViewFilterEvent->setPid($patient_id);", " $htmlNode = new HTML_TreeNode(array(\n 'text' => oeFormatShortDate($doc['docdate']) . ' ' . $doc['document_name'] . '-' . $doc['document_id'],\n 'link' => $link,\n 'icon' => $icon,\n 'expandedIcon' => $expandedIcon\n ));", " $treeViewFilterEvent->setHtmlTreeNode($htmlNode);\n $filteredEvent = $GLOBALS['kernel']->getEventDispatcher()->dispatch($treeViewFilterEvent, PatientDocumentTreeViewFilterEvent::EVENT_NAME);\n if ($filteredEvent->getHtmlTreeNode() != null) {\n $current_node->addItem($filteredEvent->getHtmlTreeNode());\n } else {\n // add the original node if we got back nothing from the server\n $current_node->addItem($htmlNode);\n }\n }\n }\n }\n return $node;\n }", " //public function for logging the errors in writing file to CouchDB/Hard Disk\n public function document_upload_download_log($patientid, $content)\n {\n $log_path = $GLOBALS['OE_SITE_DIR'] . \"/documents/couchdb/\";\n $log_file = 'log.txt';\n if (!is_dir($log_path)) {\n mkdir($log_path, 0777, true);\n }", " $LOG = file_get_contents($log_path . $log_file);", " if ($this->cryptoGen->cryptCheckStandard($LOG)) {\n $LOG = $this->cryptoGen->decryptStandard($LOG, null, 'database');\n }", " $LOG .= $content;", " if (!empty($LOG)) {\n if ($GLOBALS['drive_encryption']) {\n $LOG = $this->cryptoGen->encryptStandard($LOG, null, 'database');\n }\n file_put_contents($log_path . $log_file, $LOG);\n }\n }", " public function document_send($email, $body, $attfile, $pname)\n {\n if (empty($email)) {\n $this->assign(\"process_result\", \"Email could not be sent, the address supplied: '$email' was empty or invalid.\");\n return;\n }", " $desc = \"Please check the attached patient document.\\n Content:\" . $body;\n $mail = new MyMailer();\n $from_name = $GLOBALS[\"practice_return_email_path\"];\n $from = $GLOBALS[\"practice_return_email_path\"];\n $mail->AddReplyTo($from, $from_name);\n $mail->SetFrom($from, $from);\n $to = $email ;\n $to_name = $email;\n $mail->AddAddress($to, $to_name);\n $subject = \"Patient documents\";\n $mail->Subject = $subject;\n $mail->Body = $desc;\n $mail->AddAttachment($attfile);\n if ($mail->Send()) {\n $retstatus = \"email_sent\";\n } else {\n $email_status = $mail->ErrorInfo;\n //echo \"EMAIL ERROR: \".$email_status;\n $retstatus = \"email_fail\";\n }\n }", "//place to hold optional code\n//$first_node = array_keys($t->tree);\n //$first_node = $first_node[0];\n //$node1 = new HTML_TreeNode(array('text' => $t->get_node_name($first_node), 'link' => \"test.php\", 'icon' => $icon, 'expandedIcon' => $expandedIcon, 'expanded' => true), array('onclick' => \"alert('foo'); return false\", 'onexpand' => \"alert('Expanded')\"));", " //$this->_last_node = &$node1;", "// public function to tag a document to an encounter.\n public function tag_action_process(string $patient_id = null, $document_id)\n {\n if ($_POST['process'] != \"true\") {\n die(\"process is '\" . text($_POST['process']) . \"', expected 'true'\");\n return;\n }", " // Create Encounter and Tag it.\n $event_date = date('Y-m-d H:i:s');\n $encounter_id = $_POST['encounter_id'];\n $encounter_check = $_POST['encounter_check'];\n $visit_category_id = $_POST['visit_category_id'];", " if (is_numeric($document_id)) {\n $messages = '';\n $d = new Document($document_id);\n $file_name = $d->get_url_file();\n if (!is_numeric($encounter_id)) {\n $encounter_id = 0;\n }", " $encounter_check = ( $encounter_check == 'on') ? 1 : 0;\n if ($encounter_check) {\n $provider_id = $_SESSION['authUserID'] ;", " // Get the logged in user's facility\n $facilityRow = sqlQuery(\"SELECT username, facility, facility_id FROM users WHERE id = ?\", array(\"$provider_id\"));\n $username = $facilityRow['username'];\n $facility = $facilityRow['facility'];\n $facility_id = $facilityRow['facility_id'];\n // Get the primary Business Entity facility to set as billing facility, if null take user's facility as billing facility\n $billingFacility = $this->facilityService->getPrimaryBusinessEntity();\n $billingFacilityID = ( $billingFacility['id'] ) ? $billingFacility['id'] : $facility_id;", " $conn = $GLOBALS['adodb']['db'];\n $encounter = $conn->GenID(\"sequences\");\n $query = \"INSERT INTO form_encounter SET\n\t\t\t\t\t\tdate = ?,\n\t\t\t\t\t\treason = ?,\n\t\t\t\t\t\tfacility = ?,\n\t\t\t\t\t\tsensitivity = 'normal',\n\t\t\t\t\t\tpc_catid = ?,\n\t\t\t\t\t\tfacility_id = ?,\n\t\t\t\t\t\tbilling_facility = ?,\n\t\t\t\t\t\tprovider_id = ?,\n\t\t\t\t\t\tpid = ?,\n\t\t\t\t\t\tencounter = ?\";\n $bindArray = array($event_date,$file_name,$facility,$_POST['visit_category_id'],(int)$facility_id,(int)$billingFacilityID,(int)$provider_id,$patient_id,$encounter);\n $formID = sqlInsert($query, $bindArray);\n addForm($encounter, \"New Patient Encounter\", $formID, \"newpatient\", $patient_id, \"1\", date(\"Y-m-d H:i:s\"), $username);\n $d->set_encounter_id($encounter);\n $this->image_result_indication($d->id, $encounter);\n } else {\n $d->set_encounter_id($encounter_id);\n $this->image_result_indication($d->id, $encounter_id);\n }\n $d->set_encounter_check($encounter_check);\n $d->persist();", " $messages .= xlt('Document tagged to Encounter successfully') . \"<br />\";\n }", " $this->_state = false;\n $this->assign(\"messages\", $messages);", " return $this->view_action($patient_id, $document_id);\n }", " public function image_procedure_action(string $patient_id = null, $document_id)\n {", " $img_procedure_id = $_POST['image_procedure_id'];\n $proc_code = $_POST['procedure_code'];", " if (is_numeric($document_id)) {\n $img_order = sqlQuery(\"select * from procedure_order_code where procedure_order_id = ? and procedure_code = ? \", array($img_procedure_id,$proc_code));\n $img_report = sqlQuery(\"select * from procedure_report where procedure_order_id = ? and procedure_order_seq = ? \", array($img_procedure_id,$img_order['procedure_order_seq']));\n $img_report_id = !empty($img_report['procedure_report_id']) ? $img_report['procedure_report_id'] : 0;\n if ($img_report_id == 0) {\n $report_date = date('Y-m-d H:i:s');\n $img_report_id = sqlInsert(\"INSERT INTO procedure_report(procedure_order_id,procedure_order_seq,date_collected,date_report,report_status) values(?,?,?,?,'final')\", array($img_procedure_id,$img_order['procedure_order_seq'],$img_order['date_collected'],$report_date));\n }", " $img_result = sqlQuery(\"select * from procedure_result where procedure_report_id = ? and document_id = ?\", array($img_report_id,$document_id));\n if (empty($img_result)) {\n sqlStatement(\"INSERT INTO procedure_result(procedure_report_id,date,document_id,result_status) values(?,?,?,'final')\", array($img_report_id,date('Y-m-d H:i:s'),$document_id));\n }", " $this->image_result_indication($document_id, 0, $img_procedure_id);\n }\n return $this->view_action($patient_id, $document_id);\n }", " public function clear_procedure_tag_action(string $patient_id = null, $document_id)\n {\n if (is_numeric($document_id)) {\n sqlStatement(\"delete from procedure_result where document_id = ?\", $document_id);\n }\n return $this->view_action($patient_id, $document_id);\n }", " public function get_mapped_procedure($document_id)\n {\n $map = array();\n if (is_numeric($document_id)) {\n $map = sqlQuery(\"select poc.procedure_order_id,poc.procedure_code from procedure_result pres\n\t\t\t\t\t\t inner join procedure_report pr on pr.procedure_report_id = pres.procedure_report_id\n\t\t\t\t\t\t inner join procedure_order_code poc on (poc.procedure_order_id = pr.procedure_order_id and poc.procedure_order_seq = pr.procedure_order_seq)\n\t\t\t\t\t\t inner join procedure_order po on po.procedure_order_id = poc.procedure_order_id\n\t\t\t\t\t\t where pres.document_id = ?\", array($document_id));\n }\n return $map;\n }", " public function image_result_indication($doc_id, $encounter, $image_procedure_id = 0)\n {\n $doc_notes = sqlQuery(\"select note from notes where foreign_id = ?\", array($doc_id));\n $narration = isset($doc_notes['note']) ? 'With Narration' : 'Without Narration';", " // TODO: This should be moved into a service so we can handle things such as uuid generation....\n if ($encounter != 0) {\n $ep = sqlQuery(\"select u.username as assigned_to from form_encounter inner join users u on u.id = provider_id where encounter = ?\", array($encounter));\n } elseif ($image_procedure_id != 0) {\n $ep = sqlQuery(\"select u.username as assigned_to from procedure_order inner join users u on u.id = provider_id where procedure_order_id = ?\", array($image_procedure_id));\n } else {\n $ep = array('assigned_to' => $_SESSION['authUser']);\n }", " $encounter_provider = isset($ep['assigned_to']) ? $ep['assigned_to'] : $_SESSION['authUser'];\n $noteid = addPnote($_SESSION['pid'], 'New Image Report received ' . $narration, 0, 1, 'Image Results', $encounter_provider, '', 'New', '');\n setGpRelation(1, $doc_id, 6, $noteid);\n }", "//clear encounter tag public function\n public function clear_encounter_tag_action(string $patient_id = null, $document_id)\n {\n if (is_numeric($document_id)) {\n sqlStatement(\"update documents set encounter_id='0' where foreign_id=? and id = ?\", array($patient_id,$document_id));\n }\n return $this->view_action($patient_id, $document_id);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [303], "buggy_code_start_loc": [277], "filenames": ["controllers/C_Document.class.php"], "fixing_code_end_loc": [311], "fixing_code_start_loc": [276], "message": "Unrestricted Upload of File with Dangerous Type in GitHub repository openemr/openemr prior to 7.0.0.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:open-emr:openemr:*:*:*:*:*:*:*:*", "matchCriteriaId": "C397DED6-5350-43A0-B65D-FB92E8587CED", "versionEndExcluding": "7.0.0.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Unrestricted Upload of File with Dangerous Type in GitHub repository openemr/openemr prior to 7.0.0.2."}], "evaluatorComment": null, "id": "CVE-2022-4506", "lastModified": "2022-12-16T15:09:39.797", "metrics": {"cvssMetricV2": null, "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 7.6, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 4.7, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 8.8, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 2.8, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2022-12-15T01:15:11.227", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/openemr/openemr/commit/2e7678d812df167ea3c0756382408b670e8aa51f"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/f423d193-4ab0-4f03-ad90-25e4f02e7942"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-434"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/openemr/openemr/commit/2e7678d812df167ea3c0756382408b670e8aa51f"}, "type": "CWE-434"}
25
Determine whether the {function_name} code is vulnerable or not.
[ "# Additional MIME types that you'd like nginx to handle go in here\ntypes {\n text/csv csv;\n application/wasm wasm;\n}", "upstream discourse {\n server unix:/var/www/discourse/tmp/sockets/nginx.http.sock;\n server unix:/var/www/discourse/tmp/sockets/nginx.https.sock;\n}", "# inactive means we keep stuff around for 1440m minutes regardless of last access (1 week)\n# levels means it is a 2 deep hierarchy cause we can have lots of files\n# max_size limits the size of the cache\nproxy_cache_path /var/nginx/cache inactive=1440m levels=1:2 keys_zone=one:10m max_size=600m;", "# see: https://meta.discourse.org/t/x/74060\nproxy_buffer_size 8k;", "# If you are going to use Puma, use these:\n#\n# upstream discourse {\n# server unix:/var/www/discourse/tmp/sockets/puma.sock;\n# }", "\n# attempt to preserve the proto, must be in http context\nmap $http_x_forwarded_proto $thescheme {\n default $scheme;\n https https;\n}", "log_format log_discourse '[$time_local] \"$http_host\" $remote_addr \"$request\" \"$http_user_agent\" \"$sent_http_x_discourse_route\" $status $bytes_sent \"$http_referer\" $upstream_response_time $request_time \"$upstream_http_x_discourse_username\" \"$upstream_http_x_discourse_trackview\" \"$upstream_http_x_queue_time\" \"$upstream_http_x_redis_calls\" \"$upstream_http_x_redis_time\" \"$upstream_http_x_sql_calls\" \"$upstream_http_x_sql_time\"';", "# Allow bypass cache from localhost\ngeo $bypass_cache {\n default 0;\n 127.0.0.1 1;\n ::1 1;\n}", "server {", " access_log /var/log/nginx/access.log log_discourse;", " listen 80;\n gzip on;\n gzip_vary on;\n gzip_min_length 1000;\n gzip_comp_level 5;\n gzip_types application/json text/css text/javascript application/x-javascript application/javascript image/svg+xml application/wasm;\n gzip_proxied any;", " # Uncomment and configure this section for HTTPS support\n # NOTE: Put your ssl cert in your main nginx config directory (/etc/nginx)\n #\n # rewrite ^/(.*) https://enter.your.web.hostname.here/$1 permanent;\n #\n # listen 443 ssl;\n # ssl_certificate your-hostname-cert.pem;\n # ssl_certificate_key your-hostname-cert.key;\n # ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n # ssl_ciphers HIGH:!aNULL:!MD5;\n #", " server_name enter.your.web.hostname.here;\n server_tokens off;", " sendfile on;", " keepalive_timeout 65;", " # maximum file upload size (keep up to date when changing the corresponding site setting)\n client_max_body_size 10m;", " # path to discourse's public directory\n set $public /var/www/discourse/public;", " # without weak etags we get zero benefit from etags on dynamically compressed content\n # further more etags are based on the file in nginx not sha of data\n # use dates, it solves the problem fine even cross server\n etag off;", " # prevent direct download of backups\n location ^~ /backups/ {\n internal;\n }", " # bypass rails stack with a cheap 204 for favicon.ico requests\n location /favicon.ico {\n return 204;\n access_log off;\n log_not_found off;\n }", " location / {\n root $public;\n add_header ETag \"\";", " # auth_basic on;\n # auth_basic_user_file /etc/nginx/htpasswd;", " location ~ ^/uploads/short-url/ {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n break;\n }", " location ~ ^/secure-media-uploads/ {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n break;\n }", " location ~* (fonts|assets|plugins|uploads)/.*\\.(eot|ttf|woff|woff2|ico|otf)$ {\n expires 1y;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " location = /srv/status {\n access_log off;\n log_not_found off;\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n break;\n }", " # some minimal caching here so we don't keep asking\n # longer term we should increase probably to 1y\n location ~ ^/javascripts/ {\n expires 1d;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " location ~ ^/assets/(?<asset_path>.+)$ {\n expires 1y;\n # asset pipeline enables this\n brotli_static on;\n gzip_static on;\n add_header Cache-Control public,immutable;\n # HOOK in asset location (used for extensibility)\n # TODO I don't think this break is needed, it just breaks out of rewrite\n break;\n }", " location ~ ^/plugins/ {\n expires 1y;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " # cache emojis\n location ~ /images/emoji/ {\n expires 1y;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " location ~ ^/uploads/ {", " # NOTE: it is really annoying that we can't just define headers\n # at the top level and inherit.\n #\n # proxy_set_header DOES NOT inherit, by design, we must repeat it,\n # otherwise headers are not set correctly\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_set_header X-Sendfile-Type X-Accel-Redirect;\n proxy_set_header X-Accel-Mapping $public/=/downloads/;\n expires 1y;\n add_header Cache-Control public,immutable;", " ## optional upload anti-hotlinking rules\n #valid_referers none blocked mysite.com *.mysite.com;\n #if ($invalid_referer) { return 403; }", " # custom CSS\n location ~ /stylesheet-cache/ {\n add_header Access-Control-Allow-Origin *;\n try_files $uri =404;\n }\n # this allows us to bypass rails\n location ~* \\.(gif|png|jpg|jpeg|bmp|tif|tiff|ico|webp)$ {\n add_header Access-Control-Allow-Origin *;\n try_files $uri =404;\n }\n # SVG needs an extra header attached\n location ~* \\.(svg)$ {\n }\n # thumbnails & optimized images\n location ~ /_?optimized/ {\n add_header Access-Control-Allow-Origin *;\n try_files $uri =404;\n }", " proxy_pass http://discourse;\n break;\n }", " location ~ ^/admin/backups/ {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_set_header X-Sendfile-Type X-Accel-Redirect;\n proxy_set_header X-Accel-Mapping $public/=/downloads/;\n proxy_pass http://discourse;\n break;\n }", " # This big block is needed so we can selectively enable\n # acceleration for backups, avatars, sprites and so on.\n # see note about repetition above\n location ~ ^/(svg-sprite/|letter_avatar/|letter_avatar_proxy/|user_avatar|highlight-js|stylesheets|theme-javascripts|favicon/proxied|service-worker) {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;", " # if Set-Cookie is in the response nothing gets cached\n # this is double bad cause we are not passing last modified in\n proxy_ignore_headers \"Set-Cookie\";\n proxy_hide_header \"Set-Cookie\";\n proxy_hide_header \"X-Discourse-Username\";\n proxy_hide_header \"X-Runtime\";", " # note x-accel-redirect can not be used with proxy_cache\n proxy_cache one;\n proxy_cache_key \"$scheme,$host,$request_uri\";\n proxy_cache_valid 200 301 302 7d;", " proxy_cache_valid any 1m;", " proxy_cache_bypass $bypass_cache;\n proxy_pass http://discourse;\n break;\n }", " # we need buffering off for message bus\n location /message-bus/ {\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_http_version 1.1;\n proxy_buffering off;\n proxy_pass http://discourse;\n break;\n }", " # this means every file in public is tried first\n try_files $uri @discourse;\n }", " location /downloads/ {\n internal;\n alias $public/;\n }", " location @discourse {\n proxy_set_header Host $http_host;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [251], "buggy_code_start_loc": [250], "filenames": ["config/nginx.sample.conf"], "fixing_code_end_loc": [249], "fixing_code_start_loc": [249], "message": "Discourse is the an open source discussion platform. In affected versions a maliciously crafted request for static assets could cause error responses to be cached by Discourse's default NGINX proxy configuration. A corrected NGINX configuration is included in the latest stable, beta and tests-passed versions of Discourse. Users are advised to upgrade. There are no known workarounds for this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:discourse:discourse:*:*:*:*:*:*:*:*", "matchCriteriaId": "84A39503-20A3-468D-9B35-2956C3CA9765", "versionEndExcluding": "2.8.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta7:*:*:*:*:*:*", "matchCriteriaId": "750D2AD9-35E7-4AC7-9C22-AA90DAA34F3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Discourse is the an open source discussion platform. In affected versions a maliciously crafted request for static assets could cause error responses to be cached by Discourse's default NGINX proxy configuration. A corrected NGINX configuration is included in the latest stable, beta and tests-passed versions of Discourse. Users are advised to upgrade. There are no known workarounds for this vulnerability."}, {"lang": "es", "value": "Discourse es una plataforma de debate de c\u00f3digo abierto. En las versiones afectadas, una petici\u00f3n maliciosamente dise\u00f1ada de activos est\u00e1ticos podr\u00eda causar que las respuestas de error fueran almacenadas en la cach\u00e9 por la configuraci\u00f3n predeterminada del proxy NGINX de Discourse. Una configuraci\u00f3n NGINX corregida es incluida en las \u00faltimas versiones estables, beta y de prueba de Discourse. Es recomendado a usuarios actualizar. No se presentan mitigaciones conocidas para esta vulnerabilidad"}], "evaluatorComment": null, "id": "CVE-2022-31182", "lastModified": "2022-08-08T15:22:44.240", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-08-01T20:15:08.353", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/discourse/discourse/commit/7af25544c3940c4d046c51f4cfac9c72a06d4f50"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/discourse/discourse/security/advisories/GHSA-4ff8-3j78-w6pp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/discourse/discourse/commit/7af25544c3940c4d046c51f4cfac9c72a06d4f50"}, "type": "CWE-404"}
26
Determine whether the {function_name} code is vulnerable or not.
[ "# Additional MIME types that you'd like nginx to handle go in here\ntypes {\n text/csv csv;\n application/wasm wasm;\n}", "upstream discourse {\n server unix:/var/www/discourse/tmp/sockets/nginx.http.sock;\n server unix:/var/www/discourse/tmp/sockets/nginx.https.sock;\n}", "# inactive means we keep stuff around for 1440m minutes regardless of last access (1 week)\n# levels means it is a 2 deep hierarchy cause we can have lots of files\n# max_size limits the size of the cache\nproxy_cache_path /var/nginx/cache inactive=1440m levels=1:2 keys_zone=one:10m max_size=600m;", "# see: https://meta.discourse.org/t/x/74060\nproxy_buffer_size 8k;", "# If you are going to use Puma, use these:\n#\n# upstream discourse {\n# server unix:/var/www/discourse/tmp/sockets/puma.sock;\n# }", "\n# attempt to preserve the proto, must be in http context\nmap $http_x_forwarded_proto $thescheme {\n default $scheme;\n https https;\n}", "log_format log_discourse '[$time_local] \"$http_host\" $remote_addr \"$request\" \"$http_user_agent\" \"$sent_http_x_discourse_route\" $status $bytes_sent \"$http_referer\" $upstream_response_time $request_time \"$upstream_http_x_discourse_username\" \"$upstream_http_x_discourse_trackview\" \"$upstream_http_x_queue_time\" \"$upstream_http_x_redis_calls\" \"$upstream_http_x_redis_time\" \"$upstream_http_x_sql_calls\" \"$upstream_http_x_sql_time\"';", "# Allow bypass cache from localhost\ngeo $bypass_cache {\n default 0;\n 127.0.0.1 1;\n ::1 1;\n}", "server {", " access_log /var/log/nginx/access.log log_discourse;", " listen 80;\n gzip on;\n gzip_vary on;\n gzip_min_length 1000;\n gzip_comp_level 5;\n gzip_types application/json text/css text/javascript application/x-javascript application/javascript image/svg+xml application/wasm;\n gzip_proxied any;", " # Uncomment and configure this section for HTTPS support\n # NOTE: Put your ssl cert in your main nginx config directory (/etc/nginx)\n #\n # rewrite ^/(.*) https://enter.your.web.hostname.here/$1 permanent;\n #\n # listen 443 ssl;\n # ssl_certificate your-hostname-cert.pem;\n # ssl_certificate_key your-hostname-cert.key;\n # ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n # ssl_ciphers HIGH:!aNULL:!MD5;\n #", " server_name enter.your.web.hostname.here;\n server_tokens off;", " sendfile on;", " keepalive_timeout 65;", " # maximum file upload size (keep up to date when changing the corresponding site setting)\n client_max_body_size 10m;", " # path to discourse's public directory\n set $public /var/www/discourse/public;", " # without weak etags we get zero benefit from etags on dynamically compressed content\n # further more etags are based on the file in nginx not sha of data\n # use dates, it solves the problem fine even cross server\n etag off;", " # prevent direct download of backups\n location ^~ /backups/ {\n internal;\n }", " # bypass rails stack with a cheap 204 for favicon.ico requests\n location /favicon.ico {\n return 204;\n access_log off;\n log_not_found off;\n }", " location / {\n root $public;\n add_header ETag \"\";", " # auth_basic on;\n # auth_basic_user_file /etc/nginx/htpasswd;", " location ~ ^/uploads/short-url/ {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n break;\n }", " location ~ ^/secure-media-uploads/ {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n break;\n }", " location ~* (fonts|assets|plugins|uploads)/.*\\.(eot|ttf|woff|woff2|ico|otf)$ {\n expires 1y;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " location = /srv/status {\n access_log off;\n log_not_found off;\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n break;\n }", " # some minimal caching here so we don't keep asking\n # longer term we should increase probably to 1y\n location ~ ^/javascripts/ {\n expires 1d;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " location ~ ^/assets/(?<asset_path>.+)$ {\n expires 1y;\n # asset pipeline enables this\n brotli_static on;\n gzip_static on;\n add_header Cache-Control public,immutable;\n # HOOK in asset location (used for extensibility)\n # TODO I don't think this break is needed, it just breaks out of rewrite\n break;\n }", " location ~ ^/plugins/ {\n expires 1y;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " # cache emojis\n location ~ /images/emoji/ {\n expires 1y;\n add_header Cache-Control public,immutable;\n add_header Access-Control-Allow-Origin *;\n }", " location ~ ^/uploads/ {", " # NOTE: it is really annoying that we can't just define headers\n # at the top level and inherit.\n #\n # proxy_set_header DOES NOT inherit, by design, we must repeat it,\n # otherwise headers are not set correctly\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_set_header X-Sendfile-Type X-Accel-Redirect;\n proxy_set_header X-Accel-Mapping $public/=/downloads/;\n expires 1y;\n add_header Cache-Control public,immutable;", " ## optional upload anti-hotlinking rules\n #valid_referers none blocked mysite.com *.mysite.com;\n #if ($invalid_referer) { return 403; }", " # custom CSS\n location ~ /stylesheet-cache/ {\n add_header Access-Control-Allow-Origin *;\n try_files $uri =404;\n }\n # this allows us to bypass rails\n location ~* \\.(gif|png|jpg|jpeg|bmp|tif|tiff|ico|webp)$ {\n add_header Access-Control-Allow-Origin *;\n try_files $uri =404;\n }\n # SVG needs an extra header attached\n location ~* \\.(svg)$ {\n }\n # thumbnails & optimized images\n location ~ /_?optimized/ {\n add_header Access-Control-Allow-Origin *;\n try_files $uri =404;\n }", " proxy_pass http://discourse;\n break;\n }", " location ~ ^/admin/backups/ {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_set_header X-Sendfile-Type X-Accel-Redirect;\n proxy_set_header X-Accel-Mapping $public/=/downloads/;\n proxy_pass http://discourse;\n break;\n }", " # This big block is needed so we can selectively enable\n # acceleration for backups, avatars, sprites and so on.\n # see note about repetition above\n location ~ ^/(svg-sprite/|letter_avatar/|letter_avatar_proxy/|user_avatar|highlight-js|stylesheets|theme-javascripts|favicon/proxied|service-worker) {\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;", " # if Set-Cookie is in the response nothing gets cached\n # this is double bad cause we are not passing last modified in\n proxy_ignore_headers \"Set-Cookie\";\n proxy_hide_header \"Set-Cookie\";\n proxy_hide_header \"X-Discourse-Username\";\n proxy_hide_header \"X-Runtime\";", " # note x-accel-redirect can not be used with proxy_cache\n proxy_cache one;\n proxy_cache_key \"$scheme,$host,$request_uri\";\n proxy_cache_valid 200 301 302 7d;", "", " proxy_cache_bypass $bypass_cache;\n proxy_pass http://discourse;\n break;\n }", " # we need buffering off for message bus\n location /message-bus/ {\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header Host $http_host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_http_version 1.1;\n proxy_buffering off;\n proxy_pass http://discourse;\n break;\n }", " # this means every file in public is tried first\n try_files $uri @discourse;\n }", " location /downloads/ {\n internal;\n alias $public/;\n }", " location @discourse {\n proxy_set_header Host $http_host;\n proxy_set_header X-Request-Start \"t=${msec}\";\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $thescheme;\n proxy_pass http://discourse;\n }", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [251], "buggy_code_start_loc": [250], "filenames": ["config/nginx.sample.conf"], "fixing_code_end_loc": [249], "fixing_code_start_loc": [249], "message": "Discourse is the an open source discussion platform. In affected versions a maliciously crafted request for static assets could cause error responses to be cached by Discourse's default NGINX proxy configuration. A corrected NGINX configuration is included in the latest stable, beta and tests-passed versions of Discourse. Users are advised to upgrade. There are no known workarounds for this vulnerability.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:discourse:discourse:*:*:*:*:*:*:*:*", "matchCriteriaId": "84A39503-20A3-468D-9B35-2956C3CA9765", "versionEndExcluding": "2.8.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:discourse:discourse:2.9.0:beta7:*:*:*:*:*:*", "matchCriteriaId": "750D2AD9-35E7-4AC7-9C22-AA90DAA34F3F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Discourse is the an open source discussion platform. In affected versions a maliciously crafted request for static assets could cause error responses to be cached by Discourse's default NGINX proxy configuration. A corrected NGINX configuration is included in the latest stable, beta and tests-passed versions of Discourse. Users are advised to upgrade. There are no known workarounds for this vulnerability."}, {"lang": "es", "value": "Discourse es una plataforma de debate de c\u00f3digo abierto. En las versiones afectadas, una petici\u00f3n maliciosamente dise\u00f1ada de activos est\u00e1ticos podr\u00eda causar que las respuestas de error fueran almacenadas en la cach\u00e9 por la configuraci\u00f3n predeterminada del proxy NGINX de Discourse. Una configuraci\u00f3n NGINX corregida es incluida en las \u00faltimas versiones estables, beta y de prueba de Discourse. Es recomendado a usuarios actualizar. No se presentan mitigaciones conocidas para esta vulnerabilidad"}], "evaluatorComment": null, "id": "CVE-2022-31182", "lastModified": "2022-08-08T15:22:44.240", "metrics": {"cvssMetricV2": null, "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "LOW", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2022-08-01T20:15:08.353", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/discourse/discourse/commit/7af25544c3940c4d046c51f4cfac9c72a06d4f50"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/discourse/discourse/security/advisories/GHSA-4ff8-3j78-w6pp"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-404"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/discourse/discourse/commit/7af25544c3940c4d046c51f4cfac9c72a06d4f50"}, "type": "CWE-404"}
26
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * The MIT License\n * \n * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,\n * Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,\n * Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,\n * id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques\n * Michelin, Romain Seguy\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage hudson.model;", "import com.infradna.tool.bridge_method_injector.WithBridgeMethods;\nimport hudson.EnvVars;\nimport hudson.Functions;\nimport antlr.ANTLRException;\nimport hudson.AbortException;\nimport hudson.CopyOnWrite;\nimport hudson.FeedAdapter;\nimport hudson.FilePath;\nimport hudson.Launcher;\nimport hudson.Util;\nimport hudson.cli.declarative.CLIMethod;\nimport hudson.cli.declarative.CLIResolver;\nimport hudson.model.Cause.LegacyCodeCause;\nimport hudson.model.Cause.RemoteCause;\nimport hudson.model.Cause.UserIdCause;\nimport hudson.model.Descriptor.FormException;\nimport hudson.model.Fingerprint.RangeSet;\nimport hudson.model.Queue.Executable;\nimport hudson.model.Queue.Task;\nimport hudson.model.queue.QueueTaskFuture;\nimport hudson.model.queue.SubTask;\nimport hudson.model.Queue.WaitingItem;\nimport hudson.model.RunMap.Constructor;\nimport hudson.model.labels.LabelAtom;\nimport hudson.model.labels.LabelExpression;\nimport hudson.model.listeners.SCMPollListener;\nimport hudson.model.queue.CauseOfBlockage;\nimport hudson.model.queue.SubTaskContributor;\nimport hudson.scm.ChangeLogSet;\nimport hudson.scm.ChangeLogSet.Entry;\nimport hudson.scm.NullSCM;\nimport hudson.scm.PollingResult;\nimport hudson.scm.SCM;\nimport hudson.scm.SCMRevisionState;\nimport hudson.scm.SCMS;\nimport hudson.search.SearchIndexBuilder;\nimport hudson.security.ACL;\nimport hudson.security.Permission;\nimport hudson.slaves.WorkspaceList;\nimport hudson.tasks.BuildStep;\nimport hudson.tasks.BuildStepDescriptor;\nimport hudson.tasks.BuildTrigger;\nimport hudson.tasks.BuildWrapperDescriptor;\nimport hudson.tasks.Publisher;\nimport hudson.triggers.SCMTrigger;\nimport hudson.triggers.Trigger;\nimport hudson.triggers.TriggerDescriptor;\nimport hudson.util.AlternativeUiTextProvider;\nimport hudson.util.AlternativeUiTextProvider.Message;\nimport hudson.util.DescribableList;\nimport hudson.util.EditDistance;\nimport hudson.util.FormValidation;\nimport hudson.widgets.BuildHistoryWidget;\nimport hudson.widgets.HistoryWidget;\nimport jenkins.model.Jenkins;\nimport jenkins.model.JenkinsLocationConfiguration;\nimport jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;\nimport jenkins.scm.DefaultSCMCheckoutStrategyImpl;\nimport jenkins.scm.SCMCheckoutStrategy;\nimport jenkins.scm.SCMCheckoutStrategyDescriptor;\nimport jenkins.util.TimeDuration;\nimport net.sf.json.JSONObject;\nimport org.acegisecurity.context.SecurityContext;\nimport org.acegisecurity.context.SecurityContextHolder;\nimport org.kohsuke.accmod.Restricted;\nimport org.kohsuke.accmod.restrictions.NoExternalUse;\nimport org.kohsuke.args4j.Argument;\nimport org.kohsuke.args4j.CmdLineException;\nimport org.kohsuke.stapler.ForwardToView;\nimport org.kohsuke.stapler.HttpRedirect;\nimport org.kohsuke.stapler.HttpResponse;\nimport org.kohsuke.stapler.HttpResponses;\nimport org.kohsuke.stapler.QueryParameter;\nimport org.kohsuke.stapler.StaplerRequest;\nimport org.kohsuke.stapler.StaplerResponse;\nimport org.kohsuke.stapler.export.Exported;\nimport org.kohsuke.stapler.interceptor.RequirePOST;", "import javax.servlet.ServletException;\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport java.util.concurrent.Future;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;", "import static hudson.scm.PollingResult.*;\nimport static javax.servlet.http.HttpServletResponse.*;", "/**\n * Base implementation of {@link Job}s that build software.\n *\n * For now this is primarily the common part of {@link Project} and MavenModule.\n *\n * @author Kohsuke Kawaguchi\n * @see AbstractBuild\n */\n@SuppressWarnings(\"rawtypes\")\npublic abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {", " /**\n * {@link SCM} associated with the project.\n * To allow derived classes to link {@link SCM} config to elsewhere,\n * access to this variable should always go through {@link #getScm()}.\n */\n private volatile SCM scm = new NullSCM();", " /**\n * Controls how the checkout is done.\n */\n private volatile SCMCheckoutStrategy scmCheckoutStrategy;", " /**\n * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.\n */\n private volatile transient SCMRevisionState pollingBaseline = null;", " /**\n * All the builds keyed by their build number.\n *\n * External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via\n * {@link Run#getPreviousBuild()}\n */\n @Restricted(NoExternalUse.class)\n @SuppressWarnings(\"deprecation\") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called\n protected transient RunMap<R> builds = new RunMap<R>();", " /**\n * The quiet period. Null to delegate to the system default.\n */\n private volatile Integer quietPeriod = null;\n \n /**\n * The retry count. Null to delegate to the system default.\n */\n private volatile Integer scmCheckoutRetryCount = null;", " /**\n * If this project is configured to be only built on a certain label,\n * this value will be set to that label.\n *\n * For historical reasons, this is called 'assignedNode'. Also for\n * a historical reason, null to indicate the affinity\n * with the master node.\n *\n * @see #canRoam\n */\n private String assignedNode;", " /**\n * True if this project can be built on any node.\n *\n * <p>\n * This somewhat ugly flag combination is so that we can migrate\n * existing Hudson installations nicely.\n */\n private volatile boolean canRoam;", " /**\n * True to suspend new builds.\n */\n protected volatile boolean disabled;", " /**\n * True to keep builds of this project in queue when downstream projects are\n * building. False by default to keep from breaking existing behavior.\n */\n protected volatile boolean blockBuildWhenDownstreamBuilding = false;", " /**\n * True to keep builds of this project in queue when upstream projects are\n * building. False by default to keep from breaking existing behavior.\n */\n protected volatile boolean blockBuildWhenUpstreamBuilding = false;", " /**\n * Identifies {@link JDK} to be used.\n * Null if no explicit configuration is required.\n *\n * <p>\n * Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}\n * are saved independently.\n *\n * @see Jenkins#getJDK(String)\n */\n private volatile String jdk;", " private volatile BuildAuthorizationToken authToken = null;", " /**\n * List of all {@link Trigger}s for this project.\n */\n protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();", " /**\n * {@link Action}s contributed from subsidiary objects associated with\n * {@link AbstractProject}, such as from triggers, builders, publishers, etc.\n *\n * We don't want to persist them separately, and these actions\n * come and go as configuration change, so it's kept separate.\n */\n @CopyOnWrite\n protected transient volatile List<Action> transientActions = new Vector<Action>();", " private boolean concurrentBuild;", " /**\n * See {@link #setCustomWorkspace(String)}.\n *\n * @since 1.410\n */\n private String customWorkspace;\n \n protected AbstractProject(ItemGroup parent, String name) {\n super(parent,name);", " if(!Jenkins.getInstance().getNodes().isEmpty()) {\n // if a new job is configured with Hudson that already has slave nodes\n // make it roamable by default\n canRoam = true;\n }\n }", " @Override\n public synchronized void save() throws IOException {\n super.save();\n updateTransientActions();\n }", " @Override\n public void onCreatedFromScratch() {\n super.onCreatedFromScratch();\n builds = createBuildRunMap();\n // solicit initial contributions, especially from TransientProjectActionFactory\n updateTransientActions();\n }", " @Override\n public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {\n super.onLoad(parent, name);", " RunMap<R> builds = createBuildRunMap();", " RunMap<R> currentBuilds = this.builds;", " if (currentBuilds==null) {\n // are we overwriting what currently exist?\n // this is primarily when Jenkins is getting reloaded\n Item current = parent.getItem(name);\n if (current!=null && current.getClass()==getClass()) {\n currentBuilds = ((AbstractProject)current).builds;\n }\n }\n if (currentBuilds !=null) {\n // if we are reloading, keep all those that are still building intact\n for (R r : currentBuilds.getLoadedBuilds().values()) {\n if (r.isBuilding())\n builds.put(r);\n }\n }\n this.builds = builds;\n for (Trigger t : triggers())\n t.start(this, Items.updatingByXml.get());\n if(scm==null)\n scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.", " if(transientActions==null)\n transientActions = new Vector<Action>(); // happens when loaded from disk\n updateTransientActions();\n }", " private RunMap<R> createBuildRunMap() {\n return new RunMap<R>(getBuildDir(), new Constructor<R>() {\n public R create(File dir) throws IOException {\n return loadBuild(dir);\n }\n });\n }", " private synchronized List<Trigger<?>> triggers() {\n if (triggers == null) {\n triggers = new Vector<Trigger<?>>();\n }\n return triggers;\n }", " @Override\n public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {\n EnvVars env = super.getEnvironment(node, listener);", " JDK jdk = getJDK();\n if (jdk != null) {\n if (node != null) { // just in case were not in a build\n jdk = jdk.forNode(node, listener);\n }\n jdk.buildEnvVars(env);\n }", " return env;\n }", " @Override\n protected void performDelete() throws IOException, InterruptedException {\n // prevent a new build while a delete operation is in progress\n makeDisabled(true);\n FilePath ws = getWorkspace();\n if(ws!=null) {\n Node on = getLastBuiltOn();\n getScm().processWorkspaceBeforeDeletion(this, ws, on);\n if(on!=null)\n on.getFileSystemProvisioner().discardWorkspace(this,ws);\n }\n super.performDelete();\n }", " /**\n * Does this project perform concurrent builds?\n * @since 1.319\n */\n @Exported\n public boolean isConcurrentBuild() {\n return concurrentBuild;\n }", " public void setConcurrentBuild(boolean b) throws IOException {\n concurrentBuild = b;\n save();\n }", " /**\n * If this project is configured to be always built on this node,\n * return that {@link Node}. Otherwise null.\n */\n public Label getAssignedLabel() {\n if(canRoam)\n return null;", " if(assignedNode==null)\n return Jenkins.getInstance().getSelfLabel();\n return Jenkins.getInstance().getLabel(assignedNode);\n }", " /**\n * Set of labels relevant to this job.\n *\n * This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.\n * It does not affect the scheduling. This information is informational and the best-effort basis.\n *\n * @since 1.456\n * @return\n * Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element\n * to correspond to the null return value from {@link #getAssignedLabel()}.\n */\n public Set<Label> getRelevantLabels() {\n return Collections.singleton(getAssignedLabel());\n }", " /**\n * Gets the textual representation of the assigned label as it was entered by the user.\n */\n public String getAssignedLabelString() {\n if (canRoam || assignedNode==null) return null;\n try {\n LabelExpression.parseExpression(assignedNode);\n return assignedNode;\n } catch (ANTLRException e) {\n // must be old label or host name that includes whitespace or other unsafe chars\n return LabelAtom.escape(assignedNode);\n }\n }", " /**\n * Sets the assigned label.\n */\n public void setAssignedLabel(Label l) throws IOException {\n if(l==null) {\n canRoam = true;\n assignedNode = null;\n } else {\n canRoam = false;\n if(l== Jenkins.getInstance().getSelfLabel()) assignedNode = null;\n else assignedNode = l.getExpression();\n }\n save();\n }", " /**\n * Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.\n */\n public void setAssignedNode(Node l) throws IOException {\n setAssignedLabel(l.getSelfLabel());\n }", " /**\n * Get the term used in the UI to represent this kind of {@link AbstractProject}.\n * Must start with a capital letter.\n */\n @Override\n public String getPronoun() {\n return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());\n }", " /**\n * Gets the human readable display name to be rendered in the \"Build Now\" link.\n *\n * @since 1.401\n */\n public String getBuildNowText() {\n return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());\n }", " /**\n * Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.\n *\n * <p>\n * Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs\n * that acts as a single unit. This method can be used to find the top most dominating job that\n * covers such a tree.\n *\n * @return never null.\n * @see AbstractBuild#getRootBuild()\n */\n public AbstractProject<?,?> getRootProject() {\n if (this instanceof TopLevelItem) {\n return this;\n } else {\n ItemGroup p = this.getParent();\n if (p instanceof AbstractProject)\n return ((AbstractProject) p).getRootProject();\n return this;\n }\n }", " /**\n * Gets the directory where the module is checked out.\n *\n * @return\n * null if the workspace is on a slave that's not connected.\n * @deprecated as of 1.319\n * To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.\n * For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called\n * from {@link Executor}, and otherwise the workspace of the last build.\n *\n * <p>\n * If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.\n * If you are calling this method to serve a file from the workspace, doing a form validation, etc., then\n * use {@link #getSomeWorkspace()}\n */\n public final FilePath getWorkspace() {\n AbstractBuild b = getBuildForDeprecatedMethods();\n return b != null ? b.getWorkspace() : null;", " }\n \n /**\n * Various deprecated methods in this class all need the 'current' build. This method returns\n * the build suitable for that purpose.\n * \n * @return An AbstractBuild for deprecated methods to use.\n */\n private AbstractBuild getBuildForDeprecatedMethods() {\n Executor e = Executor.currentExecutor();\n if(e!=null) {\n Executable exe = e.getCurrentExecutable();\n if (exe instanceof AbstractBuild) {\n AbstractBuild b = (AbstractBuild) exe;\n if(b.getProject()==this)\n return b;\n }\n }\n R lb = getLastBuild();\n if(lb!=null) return lb;\n return null;\n }", " /**\n * Gets a workspace for some build of this project.\n *\n * <p>\n * This is useful for obtaining a workspace for the purpose of form field validation, where exactly\n * which build the workspace belonged is less important. The implementation makes a cursory effort\n * to find some workspace.\n *\n * @return\n * null if there's no available workspace.\n * @since 1.319\n */\n public final FilePath getSomeWorkspace() {\n R b = getSomeBuildWithWorkspace();\n if (b!=null) return b.getWorkspace();\n for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {\n FilePath f = browser.getWorkspace(this);\n if (f != null) return f;\n }\n return null;\n }", " /**\n * Gets some build that has a live workspace.\n *\n * @return null if no such build exists.\n */\n public final R getSomeBuildWithWorkspace() {\n int cnt=0;\n for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {\n FilePath ws = b.getWorkspace();\n if (ws!=null) return b;\n }\n return null;\n }", " /**\n * Returns the root directory of the checked-out module.\n * <p>\n * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>\n * and so on exists.\n *\n * @deprecated as of 1.319\n * See {@link #getWorkspace()} for a migration strategy.\n */\n public FilePath getModuleRoot() {\n AbstractBuild b = getBuildForDeprecatedMethods();\n return b != null ? b.getModuleRoot() : null;\n }", " /**\n * Returns the root directories of all checked-out modules.\n * <p>\n * Some SCMs support checking out multiple modules into the same workspace.\n * In these cases, the returned array will have a length greater than one.\n * @return The roots of all modules checked out from the SCM.\n *\n * @deprecated as of 1.319\n * See {@link #getWorkspace()} for a migration strategy.\n */\n public FilePath[] getModuleRoots() {\n AbstractBuild b = getBuildForDeprecatedMethods();\n return b != null ? b.getModuleRoots() : null;\n }", " public int getQuietPeriod() {\n return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();\n }", " public SCMCheckoutStrategy getScmCheckoutStrategy() {\n return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;\n }", " public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {\n this.scmCheckoutStrategy = scmCheckoutStrategy;\n save();\n }", "\n public int getScmCheckoutRetryCount() {\n return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();\n }", " // ugly name because of EL\n public boolean getHasCustomQuietPeriod() {\n return quietPeriod!=null;\n }", " /**\n * Sets the custom quiet period of this project, or revert to the global default if null is given. \n */\n public void setQuietPeriod(Integer seconds) throws IOException {\n this.quietPeriod = seconds;\n save();\n }\n \n public boolean hasCustomScmCheckoutRetryCount(){\n return scmCheckoutRetryCount != null;\n }", " @Override\n public boolean isBuildable() {\n return !isDisabled() && !isHoldOffBuildUntilSave();\n }", " /**\n * Used in <tt>sidepanel.jelly</tt> to decide whether to display\n * the config/delete/build links.\n */\n public boolean isConfigurable() {\n return true;\n }", " public boolean blockBuildWhenDownstreamBuilding() {\n return blockBuildWhenDownstreamBuilding;\n }", " public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {\n blockBuildWhenDownstreamBuilding = b;\n save();\n }", " public boolean blockBuildWhenUpstreamBuilding() {\n return blockBuildWhenUpstreamBuilding;\n }", " public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {\n blockBuildWhenUpstreamBuilding = b;\n save();\n }", " public boolean isDisabled() {\n return disabled;\n }\n \n /**\n * Validates the retry count Regex\n */\n public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{\n // retry count is optional so this is ok\n if(value == null || value.trim().equals(\"\"))\n return FormValidation.ok();\n if (!value.matches(\"[0-9]*\")) {\n return FormValidation.error(\"Invalid retry count\");\n } \n return FormValidation.ok();\n }", " /**\n * Marks the build as disabled.\n */\n public void makeDisabled(boolean b) throws IOException {\n if(disabled==b) return; // noop\n this.disabled = b;\n if(b)\n Jenkins.getInstance().getQueue().cancel(this);\n save();\n }", " /**\n * Specifies whether this project may be disabled by the user.\n * By default, it can be only if this is a {@link TopLevelItem};\n * would be false for matrix configurations, etc.\n * @return true if the GUI should allow {@link #doDisable} and the like\n * @since 1.475\n */\n public boolean supportsMakeDisabled() {\n return this instanceof TopLevelItem;\n }", " public void disable() throws IOException {\n makeDisabled(true);\n }", " public void enable() throws IOException {\n makeDisabled(false);\n }", " @Override\n public BallColor getIconColor() {\n if(isDisabled())\n return BallColor.DISABLED;\n else\n return super.getIconColor();\n }", " /**\n * effectively deprecated. Since using updateTransientActions correctly\n * under concurrent environment requires a lock that can too easily cause deadlocks.\n *\n * <p>\n * Override {@link #createTransientActions()} instead.\n */\n protected void updateTransientActions() {\n transientActions = createTransientActions();\n }", " protected List<Action> createTransientActions() {\n Vector<Action> ta = new Vector<Action>();", " for (JobProperty<? super P> p : Util.fixNull(properties))\n ta.addAll(p.getJobActions((P)this));", " for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())\n ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null\n return ta;\n }", " /**\n * Returns the live list of all {@link Publisher}s configured for this project.\n *\n * <p>\n * This method couldn't be called <tt>getPublishers()</tt> because existing methods\n * in sub-classes return different inconsistent types.\n */\n public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();", " @Override\n public void addProperty(JobProperty<? super P> jobProp) throws IOException {\n super.addProperty(jobProp);\n updateTransientActions();\n }", " public List<ProminentProjectAction> getProminentActions() {\n List<Action> a = getActions();\n List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();\n for (Action action : a) {\n if(action instanceof ProminentProjectAction)\n pa.add((ProminentProjectAction) action);\n }\n return pa;\n }", " @Override\n public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {\n super.doConfigSubmit(req,rsp);", " updateTransientActions();", " Set<AbstractProject> upstream = Collections.emptySet();\n if(req.getParameter(\"pseudoUpstreamTrigger\")!=null) {\n upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter(\"upstreamProjects\"),AbstractProject.class));\n }", " // dependency setting might have been changed by the user, so rebuild.\n Jenkins.getInstance().rebuildDependencyGraph();\n convertUpstreamBuildTrigger(upstream);", "\n // notify the queue as the project might be now tied to different node\n Jenkins.getInstance().getQueue().scheduleMaintenance();", " // this is to reflect the upstream build adjustments done above\n Jenkins.getInstance().rebuildDependencyGraph();\n }", " /**\n * Reflect the submission of the pseudo 'upstream build trigger'.\n */\n /* package */ void convertUpstreamBuildTrigger(Set<AbstractProject> upstream) throws IOException {", " SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);\n try {\n for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {\n // Don't consider child projects such as MatrixConfiguration:\n if (!p.isConfigurable()) continue;\n boolean isUpstream = upstream.contains(p);\n synchronized(p) {\n // does 'p' include us in its BuildTrigger?\n DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();\n BuildTrigger trigger = pl.get(BuildTrigger.class);\n List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);\n if(isUpstream) {\n if(!newChildProjects.contains(this))\n newChildProjects.add(this);\n } else {\n newChildProjects.remove(this);\n }", " if(newChildProjects.isEmpty()) {\n pl.remove(BuildTrigger.class);\n } else {\n // here, we just need to replace the old one with the new one,\n // but there was a regression (we don't know when it started) that put multiple BuildTriggers\n // into the list. For us not to lose the data, we need to merge them all.\n List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);\n BuildTrigger existing;\n switch (existingList.size()) {\n case 0:\n existing = null;\n break;\n case 1:\n existing = existingList.get(0);\n break;\n default:\n pl.removeAll(BuildTrigger.class);\n Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();\n for (BuildTrigger bt : existingList)\n combinedChildren.addAll(bt.getChildProjects(p));\n existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());\n pl.add(existing);\n break;\n }", " if(existing!=null && existing.hasSame(p,newChildProjects))\n continue; // no need to touch\n pl.replace(new BuildTrigger(newChildProjects,\n existing==null? Result.SUCCESS:existing.getThreshold()));\n }\n }\n }\n } finally {\n SecurityContextHolder.setContext(saveCtx);\n }\n }", " /**\n\t * @deprecated\n\t * Use {@link #scheduleBuild(Cause)}. Since 1.283\n\t */\n public boolean scheduleBuild() {\n \treturn scheduleBuild(new LegacyCodeCause());\n }\n \n\t/**\n\t * @deprecated\n\t * Use {@link #scheduleBuild(int, Cause)}. Since 1.283\n\t */\n public boolean scheduleBuild(int quietPeriod) {\n \treturn scheduleBuild(quietPeriod, new LegacyCodeCause());\n }\n \n /**\n * Schedules a build of this project.\n *\n * @return\n * true if the project is actually added to the queue.\n * false if the queue contained it and therefore the add()\n * was noop\n */\n public boolean scheduleBuild(Cause c) {\n return scheduleBuild(getQuietPeriod(), c);\n }", " public boolean scheduleBuild(int quietPeriod, Cause c) {\n return scheduleBuild(quietPeriod, c, new Action[0]);\n }", " /**\n * Schedules a build.\n *\n * Important: the actions should be persistable without outside references (e.g. don't store\n * references to this project). To provide parameters for a parameterized project, add a ParametersAction. If\n * no ParametersAction is provided for such a project, one will be created with the default parameter values.\n *\n * @param quietPeriod the quiet period to observer\n * @param c the cause for this build which should be recorded\n * @param actions a list of Actions that will be added to the build\n * @return whether the build was actually scheduled\n */\n public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {\n return scheduleBuild2(quietPeriod,c,actions)!=null;\n }", " /**\n * Schedules a build of this project, and returns a {@link Future} object\n * to wait for the completion of the build.\n *\n * @param actions\n * For the convenience of the caller, this array can contain null, and those will be silently ignored.\n */\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {\n return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));\n }", " /**\n * Schedules a build of this project, and returns a {@link Future} object\n * to wait for the completion of the build.\n *\n * @param actions\n * For the convenience of the caller, this collection can contain null, and those will be silently ignored.\n * @since 1.383\n */\n @SuppressWarnings(\"unchecked\")\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {\n if (!isBuildable())\n return null;", " List<Action> queueActions = new ArrayList<Action>(actions);\n if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {\n queueActions.add(new ParametersAction(getDefaultParametersValues()));\n }", " if (c != null) {\n queueActions.add(new CauseAction(c));\n }", " WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);\n if(i!=null)\n return (QueueTaskFuture)i.getFuture();\n return null;\n }", " private List<ParameterValue> getDefaultParametersValues() {\n ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);\n ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();\n \n /*\n * This check is made ONLY if someone will call this method even if isParametrized() is false.\n */\n if(paramDefProp == null)\n return defValues;\n \n /* Scan for all parameter with an associated default values */\n for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())\n {\n ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();\n \n if(defaultValue != null)\n defValues.add(defaultValue); \n }\n \n return defValues;\n }", " /**\n * Schedules a build, and returns a {@link Future} object\n * to wait for the completion of the build.\n *\n * <p>\n * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked\n * as deprecated.\n */\n @SuppressWarnings(\"deprecation\")\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {\n return scheduleBuild2(quietPeriod, new LegacyCodeCause());\n }\n \n /**\n * Schedules a build of this project, and returns a {@link Future} object\n * to wait for the completion of the build.\n */\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {\n return scheduleBuild2(quietPeriod, c, new Action[0]);\n }", " /**\n * Schedules a polling of this project.\n */\n public boolean schedulePolling() {\n if(isDisabled()) return false;\n SCMTrigger scmt = getTrigger(SCMTrigger.class);\n if(scmt==null) return false;\n scmt.run();\n return true;\n }", " /**\n * Returns true if the build is in the queue.\n */\n @Override\n public boolean isInQueue() {\n return Jenkins.getInstance().getQueue().contains(this);\n }", " @Override\n public Queue.Item getQueueItem() {\n return Jenkins.getInstance().getQueue().getItem(this);\n }", " /**\n * Gets the JDK that this project is configured with, or null.\n */\n public JDK getJDK() {\n return Jenkins.getInstance().getJDK(jdk);\n }", " /**\n * Overwrites the JDK setting.\n */\n public void setJDK(JDK jdk) throws IOException {\n this.jdk = jdk.getName();\n save();\n }", " public BuildAuthorizationToken getAuthToken() {\n return authToken;\n }", " @Override\n public RunMap<R> _getRuns() {\n assert builds.baseDirInitialized() : \"neither onCreatedFromScratch nor onLoad called on \" + this + \" yet\";\n return builds;\n }", " @Override\n public void removeRun(R run) {\n this.builds.remove(run);\n }", " /**\n * {@inheritDoc}\n *\n * More efficient implementation.\n */\n @Override\n public R getBuild(String id) {\n return builds.getById(id);\n }", " /**\n * {@inheritDoc}\n *\n * More efficient implementation.\n */\n @Override\n public R getBuildByNumber(int n) {\n return builds.getByNumber(n);\n }", " /**\n * {@inheritDoc}\n *\n * More efficient implementation.\n */\n @Override\n public R getFirstBuild() {\n return builds.oldestBuild();\n }", " @Override\n public R getLastBuild() {\n return builds.newestBuild();\n }", " @Override\n public R getNearestBuild(int n) {\n return builds.search(n, Direction.ASC);\n }", " @Override\n public R getNearestOldBuild(int n) {\n return builds.search(n, Direction.DESC);\n }", " /**\n * Determines Class&lt;R>.\n */\n protected abstract Class<R> getBuildClass();", " // keep track of the previous time we started a build\n private transient long lastBuildStartTime;\n \n /**\n * Creates a new build of this project for immediate execution.\n */\n protected synchronized R newBuild() throws IOException {\n \t// make sure we don't start two builds in the same second\n \t// so the build directories will be different too\n \tlong timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;\n \tif (timeSinceLast < 1000) {\n \t\ttry {\n\t\t\t\tThread.sleep(1000 - timeSinceLast);\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n \t}\n \tlastBuildStartTime = System.currentTimeMillis();\n try {\n R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);\n builds.put(lastBuild);\n return lastBuild;\n } catch (InstantiationException e) {\n throw new Error(e);\n } catch (IllegalAccessException e) {\n throw new Error(e);\n } catch (InvocationTargetException e) {\n throw handleInvocationTargetException(e);\n } catch (NoSuchMethodException e) {\n throw new Error(e);\n }\n }", " private IOException handleInvocationTargetException(InvocationTargetException e) {\n Throwable t = e.getTargetException();\n if(t instanceof Error) throw (Error)t;\n if(t instanceof RuntimeException) throw (RuntimeException)t;\n if(t instanceof IOException) return (IOException)t;\n throw new Error(t);\n }", " /**\n * Loads an existing build record from disk.\n */\n protected R loadBuild(File dir) throws IOException {\n try {\n return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);\n } catch (InstantiationException e) {\n throw new Error(e);\n } catch (IllegalAccessException e) {\n throw new Error(e);\n } catch (InvocationTargetException e) {\n throw handleInvocationTargetException(e);\n } catch (NoSuchMethodException e) {\n throw new Error(e);\n }\n }", " /**\n * {@inheritDoc}\n *\n * <p>\n * Note that this method returns a read-only view of {@link Action}s.\n * {@link BuildStep}s and others who want to add a project action\n * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.\n *\n * @see TransientProjectActionFactory\n */\n @Override\n public List<Action> getActions() {\n // add all the transient actions, too\n List<Action> actions = new Vector<Action>(super.getActions());\n actions.addAll(transientActions);\n // return the read only list to cause a failure on plugins who try to add an action here\n return Collections.unmodifiableList(actions);\n }", " /**\n * Gets the {@link Node} where this project was last built on.\n *\n * @return\n * null if no information is available (for example,\n * if no build was done yet.)\n */\n public Node getLastBuiltOn() {\n // where was it built on?\n AbstractBuild b = getLastBuild();\n if(b==null)\n return null;\n else\n return b.getBuiltOn();\n }", " public Object getSameNodeConstraint() {\n return this; // in this way, any member that wants to run with the main guy can nominate the project itself \n }", " public final Task getOwnerTask() {\n return this;\n }", " /**\n * {@inheritDoc}\n *\n * <p>\n * A project must be blocked if its own previous build is in progress,\n * or if the blockBuildWhenUpstreamBuilding option is true and an upstream\n * project is building, but derived classes can also check other conditions.\n */\n public boolean isBuildBlocked() {\n return getCauseOfBlockage()!=null;\n }", " public String getWhyBlocked() {\n CauseOfBlockage cb = getCauseOfBlockage();\n return cb!=null ? cb.getShortDescription() : null;\n }", " /**\n * Blocked because the previous build is already in progress.\n */\n public static class BecauseOfBuildInProgress extends CauseOfBlockage {\n private final AbstractBuild<?,?> build;", " public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {\n this.build = build;\n }", " @Override\n public String getShortDescription() {\n Executor e = build.getExecutor();\n String eta = \"\";\n if (e != null)\n eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());\n int lbn = build.getNumber();\n return Messages.AbstractProject_BuildInProgress(lbn, eta);\n }\n }\n \n /**\n * Because the downstream build is in progress, and we are configured to wait for that.\n */\n public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {\n public final AbstractProject<?,?> up;", " public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {\n this.up = up;\n }", " @Override\n public String getShortDescription() {\n return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());\n }\n }", " /**\n * Because the upstream build is in progress, and we are configured to wait for that.\n */\n public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {\n public final AbstractProject<?,?> up;", " public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {\n this.up = up;\n }", " @Override\n public String getShortDescription() {\n return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());\n }\n }", " public CauseOfBlockage getCauseOfBlockage() {\n // Block builds until they are done with post-production\n if (isLogUpdated() && !isConcurrentBuild())\n return new BecauseOfBuildInProgress(getLastBuild());\n if (blockBuildWhenDownstreamBuilding()) {\n AbstractProject<?,?> bup = getBuildingDownstream();\n if (bup!=null)\n return new BecauseOfDownstreamBuildInProgress(bup);\n }\n if (blockBuildWhenUpstreamBuilding()) {\n AbstractProject<?,?> bup = getBuildingUpstream();\n if (bup!=null)\n return new BecauseOfUpstreamBuildInProgress(bup);\n }\n return null;\n }", " /**\n * Returns the project if any of the downstream project is either\n * building, waiting, pending or buildable.\n * <p>\n * This means eventually there will be an automatic triggering of\n * the given project (provided that all builds went smoothly.)\n */\n public AbstractProject getBuildingDownstream() {\n Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();", " for (AbstractProject tup : getTransitiveDownstreamProjects()) {\n\t\t\tif (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))\n return tup;\n }\n return null;\n }", " /**\n * Returns the project if any of the upstream project is either\n * building or is in the queue.\n * <p>\n * This means eventually there will be an automatic triggering of\n * the given project (provided that all builds went smoothly.)\n */\n public AbstractProject getBuildingUpstream() {\n Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();", " for (AbstractProject tup : getTransitiveUpstreamProjects()) {\n\t\t\tif (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))\n return tup;\n }\n return null;\n }", " public List<SubTask> getSubTasks() {\n List<SubTask> r = new ArrayList<SubTask>();\n r.add(this);\n for (SubTaskContributor euc : SubTaskContributor.all())\n r.addAll(euc.forProject(this));\n for (JobProperty<? super P> p : properties)\n r.addAll(p.getSubTasks());\n return r;\n }", " public R createExecutable() throws IOException {\n if(isDisabled()) return null;\n return newBuild();\n }", " public void checkAbortPermission() {\n checkPermission(AbstractProject.ABORT);\n }", " public boolean hasAbortPermission() {\n return hasPermission(AbstractProject.ABORT);\n }", " /**\n * Gets the {@link Resource} that represents the workspace of this project.\n * Useful for locking and mutual exclusion control.\n *\n * @deprecated as of 1.319\n * Projects no longer have a fixed workspace, ands builds will find an available workspace via\n * {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)\n * So a {@link Resource} representation for a workspace at the project level no longer makes sense.\n *\n * <p>\n * If you need to lock a workspace while you do some computation, see the source code of\n * {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.\n */\n public Resource getWorkspaceResource() {\n return new Resource(getFullDisplayName()+\" workspace\");\n }", " /**\n * List of necessary resources to perform the build of this project.\n */\n public ResourceList getResourceList() {\n final Set<ResourceActivity> resourceActivities = getResourceActivities();\n final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());\n for (ResourceActivity activity : resourceActivities) {\n if (activity != this && activity != null) {\n // defensive infinite recursion and null check\n resourceLists.add(activity.getResourceList());\n }\n }\n return ResourceList.union(resourceLists);\n }", " /**\n * Set of child resource activities of the build of this project (override in child projects).\n * @return The set of child resource activities of the build of this project.\n */\n protected Set<ResourceActivity> getResourceActivities() {\n return Collections.emptySet();\n }", " public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {\n SCM scm = getScm();\n if(scm==null)\n return true; // no SCM", " FilePath workspace = build.getWorkspace();\n workspace.mkdirs();\n \n boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);\n if (r) {\n // Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations\n // won't reach this line anyway, as they throw AbortExceptions on checkout failure.\n calcPollingBaseline(build, launcher, listener);\n }\n return r;\n }", " /**\n * Pushes the baseline up to the newly checked out revision.\n */\n private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {\n SCMRevisionState baseline = build.getAction(SCMRevisionState.class);\n if (baseline==null) {\n try {\n baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);\n } catch (AbstractMethodError e) {\n baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling\n }\n if (baseline!=null)\n build.addAction(baseline);\n }\n pollingBaseline = baseline;\n }", " /**\n * Checks if there's any update in SCM, and returns true if any is found.\n *\n * @deprecated as of 1.346\n * Use {@link #poll(TaskListener)} instead.\n */\n public boolean pollSCMChanges( TaskListener listener ) {\n return poll(listener).hasChanges();\n }", " /**\n * Checks if there's any update in SCM, and returns true if any is found.\n *\n * <p>\n * The implementation is responsible for ensuring mutual exclusion between polling and builds\n * if necessary.\n *\n * @since 1.345\n */\n public PollingResult poll( TaskListener listener ) {\n SCM scm = getScm();\n if (scm==null) {\n listener.getLogger().println(Messages.AbstractProject_NoSCM());\n return NO_CHANGES;\n }\n if (!isBuildable()) {\n listener.getLogger().println(Messages.AbstractProject_Disabled());\n return NO_CHANGES;\n }", " R lb = getLastBuild();\n if (lb==null) {\n listener.getLogger().println(Messages.AbstractProject_NoBuilds());\n return isInQueue() ? NO_CHANGES : BUILD_NOW;\n }", " if (pollingBaseline==null) {\n R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this\n for (R r=lb; r!=null; r=r.getPreviousBuild()) {\n SCMRevisionState s = r.getAction(SCMRevisionState.class);\n if (s!=null) {\n pollingBaseline = s;\n break;\n }\n if (r==success) break; // searched far enough\n }\n // NOTE-NO-BASELINE:\n // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline\n // as action, so we need to compute it. This happens later.\n }", " try {\n SCMPollListener.fireBeforePolling(this, listener);\n PollingResult r = _poll(listener, scm, lb);\n SCMPollListener.firePollingSuccess(this,listener, r);\n return r;\n } catch (AbortException e) {\n listener.getLogger().println(e.getMessage());\n listener.fatalError(Messages.AbstractProject_Aborted());\n LOGGER.log(Level.FINE, \"Polling \"+this+\" aborted\",e);\n SCMPollListener.firePollingFailed(this, listener,e);\n return NO_CHANGES;\n } catch (IOException e) {\n e.printStackTrace(listener.fatalError(e.getMessage()));\n SCMPollListener.firePollingFailed(this, listener,e);\n return NO_CHANGES;\n } catch (InterruptedException e) {\n e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));\n SCMPollListener.firePollingFailed(this, listener,e);\n return NO_CHANGES;\n } catch (RuntimeException e) {\n SCMPollListener.firePollingFailed(this, listener,e);\n throw e;\n } catch (Error e) {\n SCMPollListener.firePollingFailed(this, listener,e);\n throw e;\n }\n }", " /**\n * {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .\n */\n private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {\n if (scm.requiresWorkspaceForPolling()) {\n // lock the workspace of the last build\n FilePath ws=lb.getWorkspace();", " WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );\n if ( workspaceOfflineReason != null ) {\n // workspace offline\n for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {\n ws = browser.getWorkspace(this);\n if (ws != null) {\n return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());\n }\n }", " // build now, or nothing will ever be built\n Label label = getAssignedLabel();\n if (label != null && label.isSelfLabel()) {\n // if the build is fixed on a node, then attempting a build will do us\n // no good. We should just wait for the slave to come back.\n listener.getLogger().print(Messages.AbstractProject_NoWorkspace());\n listener.getLogger().println( \" (\" + workspaceOfflineReason.name() + \")\");\n return NO_CHANGES;\n }\n listener.getLogger().println( ws==null\n ? Messages.AbstractProject_WorkspaceOffline()\n : Messages.AbstractProject_NoWorkspace());\n if (isInQueue()) {\n listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());\n return NO_CHANGES;\n } else {\n listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());\n listener.getLogger().println( \" (\" + workspaceOfflineReason.name() + \")\");\n return BUILD_NOW;\n }\n } else {\n WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();\n return pollWithWorkspace(listener, scm, lb, ws, l);", " }\n } else {\n // polling without workspace\n LOGGER.fine(\"Polling SCM changes of \" + getName());", " if (pollingBaseline==null) // see NOTE-NO-BASELINE above\n calcPollingBaseline(lb,null,listener);\n PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);\n pollingBaseline = r.remote;\n return r;\n }\n }", " private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {\n // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.\n // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.\n //\n // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,\n // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)\n // by having multiple workspaces\n WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);\n Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));\n try {\n LOGGER.fine(\"Polling SCM changes of \" + getName());\n if (pollingBaseline==null) // see NOTE-NO-BASELINE above\n calcPollingBaseline(lb,launcher,listener);\n PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);\n pollingBaseline = r.remote;\n return r;\n } finally {\n lease.release();\n }\n }", " enum WorkspaceOfflineReason {\n nonexisting_workspace,\n builton_node_gone,\n builton_node_no_executors\n }", " private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {\n FilePath ws = build.getWorkspace();\n if (ws==null || !ws.exists()) {\n return WorkspaceOfflineReason.nonexisting_workspace;\n }\n \n Node builtOn = build.getBuiltOn();\n if (builtOn == null) { // node built-on doesn't exist anymore\n return WorkspaceOfflineReason.builton_node_gone;\n }\n \n if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.\n return WorkspaceOfflineReason.builton_node_no_executors;\n }", " return null;\n }", " /**\n * Returns true if this user has made a commit to this project.\n *\n * @since 1.191\n */\n public boolean hasParticipant(User user) {\n for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())\n if(build.hasParticipant(user))\n return true;\n return false;\n }", " @Exported\n public SCM getScm() {\n return scm;\n }", " public void setScm(SCM scm) throws IOException {\n this.scm = scm;\n save();\n }", " /**\n * Adds a new {@link Trigger} to this {@link Project} if not active yet.\n */\n public void addTrigger(Trigger<?> trigger) throws IOException {\n addToList(trigger,triggers());\n }", " public void removeTrigger(TriggerDescriptor trigger) throws IOException {\n removeFromList(trigger,triggers());\n }", " protected final synchronized <T extends Describable<T>>\n void addToList( T item, List<T> collection ) throws IOException {\n for( int i=0; i<collection.size(); i++ ) {\n if(collection.get(i).getDescriptor()==item.getDescriptor()) {\n // replace\n collection.set(i,item);\n save();\n return;\n }\n }\n // add\n collection.add(item);\n save();\n updateTransientActions();\n }", " protected final synchronized <T extends Describable<T>>\n void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {\n for( int i=0; i< collection.size(); i++ ) {\n if(collection.get(i).getDescriptor()==item) {\n // found it\n collection.remove(i);\n save();\n updateTransientActions();\n return;\n }\n }\n }", " @SuppressWarnings(\"unchecked\")\n public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {\n return (Map)Descriptor.toMap(triggers());\n }", " /**\n * Gets the specific trigger, or null if the propert is not configured for this job.\n */\n public <T extends Trigger> T getTrigger(Class<T> clazz) {\n for (Trigger p : triggers()) {\n if(clazz.isInstance(p))\n return clazz.cast(p);\n }\n return null;\n }", "//\n//\n// fingerprint related\n//\n//\n /**\n * True if the builds of this project produces {@link Fingerprint} records.\n */\n public abstract boolean isFingerprintConfigured();", " /**\n * Gets the other {@link AbstractProject}s that should be built\n * when a build of this project is completed.\n */\n @Exported\n public final List<AbstractProject> getDownstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getDownstream(this);\n }", " @Exported\n public final List<AbstractProject> getUpstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getUpstream(this);\n }", " /**\n * Returns only those upstream projects that defines {@link BuildTrigger} to this project.\n * This is a subset of {@link #getUpstreamProjects()}\n *\n * @return A List of upstream projects that has a {@link BuildTrigger} to this project.\n */\n public final List<AbstractProject> getBuildTriggerUpstreamProjects() {\n ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();\n for (AbstractProject<?,?> ap : getUpstreamProjects()) {\n BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);\n if (buildTrigger != null)\n if (buildTrigger.getChildProjects(ap).contains(this))\n result.add(ap);\n } \n return result;\n } \n \n /**\n * Gets all the upstream projects including transitive upstream projects.\n *\n * @since 1.138\n */\n public final Set<AbstractProject> getTransitiveUpstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);\n }", " /**\n * Gets all the downstream projects including transitive downstream projects.\n *\n * @since 1.138\n */\n public final Set<AbstractProject> getTransitiveDownstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);\n }", " /**\n * Gets the dependency relationship map between this project (as the source)\n * and that project (as the sink.)\n *\n * @return\n * can be empty but not null. build number of this project to the build\n * numbers of that project.\n */\n public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {\n TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);", " checkAndRecord(that, r, this.getBuilds());\n // checkAndRecord(that, r, that.getBuilds());", " return r;\n }", " /**\n * Helper method for getDownstreamRelationship.\n *\n * For each given build, find the build number range of the given project and put that into the map.\n */\n private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {\n for (R build : builds) {\n RangeSet rs = build.getDownstreamRelationship(that);\n if(rs==null || rs.isEmpty())\n continue;", " int n = build.getNumber();", " RangeSet value = r.get(n);\n if(value==null)\n r.put(n,rs);\n else\n value.add(rs);\n }\n }", " /**\n * Builds the dependency graph.\n * @see DependencyGraph\n */\n protected abstract void buildDependencyGraph(DependencyGraph graph);", " @Override\n protected SearchIndexBuilder makeSearchIndex() {\n SearchIndexBuilder sib = super.makeSearchIndex();\n if(isBuildable() && hasPermission(Jenkins.ADMINISTER))\n sib.add(\"build\",\"build\");\n return sib;\n }", " @Override\n protected HistoryWidget createHistoryWidget() {\n return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);\n }\n \n public boolean isParameterized() {\n return getProperty(ParametersDefinitionProperty.class) != null;\n }", "//\n//\n// actions\n//\n//\n /**\n * Schedules a new build command.\n */\n public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {\n if (delay==null) delay=new TimeDuration(getQuietPeriod());", " // if a build is parameterized, let that take over\n ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);\n if (pp != null && !req.getMethod().equals(\"POST\")) {\n // show the parameter entry form.\n req.getView(pp, \"index.jelly\").forward(req, rsp);\n return;\n }", " BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);", " if (pp != null) {\n pp._doBuild(req,rsp,delay);\n return;\n }", " if (!isBuildable())\n throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+\" is not buildable\"));", " Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));\n rsp.sendRedirect(\".\");\n }", " /**\n * Computes the build cause, using RemoteCause or UserCause as appropriate.\n */\n /*package*/ CauseAction getBuildCause(StaplerRequest req) {\n Cause cause;\n if (authToken != null && authToken.getToken() != null && req.getParameter(\"token\") != null) {\n // Optional additional cause text when starting via token\n String causeText = req.getParameter(\"cause\");\n cause = new RemoteCause(req.getRemoteAddr(), causeText);\n } else {\n cause = new UserIdCause();\n }\n return new CauseAction(cause);\n }", " /**\n * Computes the delay by taking the default value and the override in the request parameter into the account.\n *\n * @deprecated as of 1.488\n * Inject {@link TimeDuration}.\n */\n public int getDelay(StaplerRequest req) throws ServletException {\n String delay = req.getParameter(\"delay\");\n if (delay==null) return getQuietPeriod();", " try {\n // TODO: more unit handling\n if(delay.endsWith(\"sec\")) delay=delay.substring(0,delay.length()-3);\n if(delay.endsWith(\"secs\")) delay=delay.substring(0,delay.length()-4);\n return Integer.parseInt(delay);\n } catch (NumberFormatException e) {\n throw new ServletException(\"Invalid delay parameter value: \"+delay);\n }\n }", " /**\n * Supports build trigger with parameters via an HTTP GET or POST.\n * Currently only String parameters are supported.\n */\n public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {\n BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);", " ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);\n if (pp != null) {\n pp.buildWithParameters(req,rsp,delay);\n } else {\n \tthrow new IllegalStateException(\"This build is not parameterized!\");\n }\n \t\n }", " /**\n * Schedules a new SCM polling command.\n */\n public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);\n schedulePolling();\n rsp.sendRedirect(\".\");\n }", " /**\n * Cancels a scheduled build.\n */\n @RequirePOST\n public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n checkPermission(ABORT);", " Jenkins.getInstance().getQueue().cancel(this);\n rsp.forwardToPreviousPage(req);\n }", " /**\n * Deletes this project.\n */\n @Override\n @RequirePOST\n public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {\n delete();\n if (req == null || rsp == null)\n return;\n View view = req.findAncestorObject(View.class);\n if (view == null)\n rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());\n else \n rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());\n }\n \n @Override\n protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {\n super.submit(req,rsp);\n JSONObject json = req.getSubmittedForm();", " makeDisabled(req.getParameter(\"disable\")!=null);", " jdk = req.getParameter(\"jdk\");\n if(req.getParameter(\"hasCustomQuietPeriod\")!=null) {\n quietPeriod = Integer.parseInt(req.getParameter(\"quiet_period\"));\n } else {\n quietPeriod = null;\n }\n if(req.getParameter(\"hasCustomScmCheckoutRetryCount\")!=null) {\n scmCheckoutRetryCount = Integer.parseInt(req.getParameter(\"scmCheckoutRetryCount\"));\n } else {\n scmCheckoutRetryCount = null;\n }\n blockBuildWhenDownstreamBuilding = req.getParameter(\"blockBuildWhenDownstreamBuilding\")!=null;\n blockBuildWhenUpstreamBuilding = req.getParameter(\"blockBuildWhenUpstreamBuilding\")!=null;", " if(req.hasParameter(\"customWorkspace\")) {\n customWorkspace = Util.fixEmptyAndTrim(req.getParameter(\"customWorkspace.directory\"));\n } else {\n customWorkspace = null;\n }", " if (json.has(\"scmCheckoutStrategy\"))\n scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,\n json.getJSONObject(\"scmCheckoutStrategy\"));\n else\n scmCheckoutStrategy = null;", " \n if(req.getParameter(\"hasSlaveAffinity\")!=null) {\n assignedNode = Util.fixEmptyAndTrim(req.getParameter(\"_.assignedLabelString\"));\n } else {\n assignedNode = null;\n }\n canRoam = assignedNode==null;", " concurrentBuild = req.getSubmittedForm().has(\"concurrentBuild\");", " authToken = BuildAuthorizationToken.create(req);", " setScm(SCMS.parseSCM(req,this));", " for (Trigger t : triggers())\n t.stop();\n triggers = buildDescribable(req, Trigger.for_(this));\n for (Trigger t : triggers)\n t.start(this,true);", " for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, \"publisher\", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {\n BuildTrigger t = (BuildTrigger) _t;", " for (AbstractProject downstream : t.getChildProjects(this)) {", " downstream.checkPermission(BUILD);\n }\n }\n }", " /**\n * @deprecated\n * As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.\n */\n protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {\n return buildDescribable(req,descriptors);\n }", " protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)\n throws FormException, ServletException {", " JSONObject data = req.getSubmittedForm();\n List<T> r = new Vector<T>();\n for (Descriptor<T> d : descriptors) {\n String safeName = d.getJsonSafeClassName();\n if (req.getParameter(safeName) != null) {\n T instance = d.newInstance(req, data.getJSONObject(safeName));\n r.add(instance);\n }\n }\n return r;\n }", " /**\n * Serves the workspace files.\n */\n public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {\n checkPermission(AbstractProject.WORKSPACE);\n FilePath ws = getSomeWorkspace();\n if ((ws == null) || (!ws.exists())) {\n // if there's no workspace, report a nice error message\n // Would be good if when asked for *plain*, do something else!\n // (E.g. return 404, or send empty doc.)\n // Not critical; client can just check if content type is not text/plain,\n // which also serves to detect old versions of Hudson.\n req.getView(this,\"noWorkspace.jelly\").forward(req,rsp);\n return null;\n } else {\n return new DirectoryBrowserSupport(this, ws, getDisplayName()+\" workspace\", \"folder.png\", true);\n }\n }", " /**\n * Wipes out the workspace.\n */\n public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {\n checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);\n R b = getSomeBuildWithWorkspace();\n FilePath ws = b!=null ? b.getWorkspace() : null;\n if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {\n ws.deleteRecursive();\n for (WorkspaceListener wl : WorkspaceListener.all()) {\n wl.afterDelete(this);\n }\n return new HttpRedirect(\".\");\n } else {\n // If we get here, that means the SCM blocked the workspace deletion.\n return new ForwardToView(this,\"wipeOutWorkspaceBlocked.jelly\");\n }\n }", " @CLIMethod(name=\"disable-job\")\n @RequirePOST\n public HttpResponse doDisable() throws IOException, ServletException {\n checkPermission(CONFIGURE);\n makeDisabled(true);\n return new HttpRedirect(\".\");\n }", " @CLIMethod(name=\"enable-job\")\n @RequirePOST\n public HttpResponse doEnable() throws IOException, ServletException {\n checkPermission(CONFIGURE);\n makeDisabled(false);\n return new HttpRedirect(\".\");\n }", " /**\n * RSS feed for changes in this project.\n */\n public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n class FeedItem {\n ChangeLogSet.Entry e;\n int idx;", " public FeedItem(Entry e, int idx) {\n this.e = e;\n this.idx = idx;\n }", " AbstractBuild<?,?> getBuild() {\n return e.getParent().build;\n }\n }", " List<FeedItem> entries = new ArrayList<FeedItem>();", " for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {\n int idx=0;\n for( ChangeLogSet.Entry e : r.getChangeSet())\n entries.add(new FeedItem(e,idx++));\n }", " RSS.forwardToRss(\n getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+\" changes\",\n getUrl()+\"changes\",\n entries, new FeedAdapter<FeedItem>() {\n public String getEntryTitle(FeedItem item) {\n return \"#\"+item.getBuild().number+' '+item.e.getMsg()+\" (\"+item.e.getAuthor()+\")\";\n }", " public String getEntryUrl(FeedItem item) {\n return item.getBuild().getUrl()+\"changes#detail\"+item.idx;\n }", " public String getEntryID(FeedItem item) {\n return getEntryUrl(item);\n }", " public String getEntryDescription(FeedItem item) {\n StringBuilder buf = new StringBuilder();\n for(String path : item.e.getAffectedPaths())\n buf.append(path).append('\\n');\n return buf.toString();\n }", " public Calendar getEntryTimestamp(FeedItem item) {\n return item.getBuild().getTimestamp();\n }", " public String getEntryAuthor(FeedItem entry) {\n return JenkinsLocationConfiguration.get().getAdminAddress();\n }\n },\n req, rsp );\n }", " /**\n * {@link AbstractProject} subtypes should implement this base class as a descriptor.\n *\n * @since 1.294\n */\n public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {\n /**\n * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s\n * from showing up on their configuration screen. This is often useful when you are building\n * a workflow/company specific project type, where you want to limit the number of choices\n * given to the users.\n *\n * <p>\n * Some {@link Descriptor}s define their own schemes for controlling applicability\n * (such as {@link BuildStepDescriptor#isApplicable(Class)}),\n * This method works like AND in conjunction with them;\n * Both this method and that method need to return true in order for a given {@link Descriptor}\n * to show up for the given {@link Project}.\n *\n * <p>\n * The default implementation returns true for everything.\n *\n * @see BuildStepDescriptor#isApplicable(Class) \n * @see BuildWrapperDescriptor#isApplicable(AbstractProject) \n * @see TriggerDescriptor#isApplicable(Item)\n */\n @Override\n public boolean isApplicable(Descriptor descriptor) {\n return true;\n }", " public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {\n if (Util.fixEmpty(value)==null)\n return FormValidation.ok(); // nothing typed yet\n try {\n Label.parseExpression(value);\n } catch (ANTLRException e) {\n return FormValidation.error(e,\n Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));\n }\n Label l = Jenkins.getInstance().getLabel(value);\n if (l.isEmpty()) {\n for (LabelAtom a : l.listAtoms()) {\n if (a.isEmpty()) {\n LabelAtom nearest = LabelAtom.findNearest(a.getName());\n return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));\n }\n }\n return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());\n }\n return FormValidation.ok();\n }", " public FormValidation doCheckCustomWorkspace(@QueryParameter(value=\"customWorkspace.directory\") String customWorkspace){\n \tif(Util.fixEmptyAndTrim(customWorkspace)==null)\n \t\treturn FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());\n \telse\n \t\treturn FormValidation.ok();\n }\n \n public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {\n AutoCompletionCandidates candidates = new AutoCompletionCandidates();\n List<Job> jobs = Jenkins.getInstance().getItems(Job.class);\n for (Job job: jobs) {\n if (job.getFullName().startsWith(value)) {\n if (job.hasPermission(Item.READ)) {\n candidates.add(job.getFullName());\n }\n }\n }\n return candidates;\n }", " public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {\n AutoCompletionCandidates c = new AutoCompletionCandidates();\n Set<Label> labels = Jenkins.getInstance().getLabels();\n List<String> queries = new AutoCompleteSeeder(value).getSeeds();", " for (String term : queries) {\n for (Label l : labels) {\n if (l.getName().startsWith(term)) {\n c.add(l.getName());\n }\n }\n }\n return c;\n }", " public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {\n return SCMCheckoutStrategyDescriptor._for(p);\n }", " /**\n * Utility class for taking the current input value and computing a list\n * of potential terms to match against the list of defined labels.\n */\n static class AutoCompleteSeeder {\n private String source;", " AutoCompleteSeeder(String source) {\n this.source = source;\n }", " List<String> getSeeds() {\n ArrayList<String> terms = new ArrayList<String>();\n boolean trailingQuote = source.endsWith(\"\\\"\");\n boolean leadingQuote = source.startsWith(\"\\\"\");\n boolean trailingSpace = source.endsWith(\" \");", " if (trailingQuote || (trailingSpace && !leadingQuote)) {\n terms.add(\"\");\n } else {\n if (leadingQuote) {\n int quote = source.lastIndexOf('\"');\n if (quote == 0) {\n terms.add(source.substring(1));\n } else {\n terms.add(\"\");\n }\n } else {\n int space = source.lastIndexOf(' ');\n if (space > -1) {\n terms.add(source.substring(space+1));\n } else {\n terms.add(source);\n }\n }\n }", " return terms;\n }\n }\n }", " /**\n * Finds a {@link AbstractProject} that has the name closest to the given name.\n */\n public static AbstractProject findNearest(String name) {\n return findNearest(name,Hudson.getInstance());\n }", " /**\n * Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.\n *\n * @since 1.419\n */\n public static AbstractProject findNearest(String name, ItemGroup context) {\n List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);\n String[] names = new String[projects.size()];\n for( int i=0; i<projects.size(); i++ )\n names[i] = projects.get(i).getRelativeNameFrom(context);", " String nearest = EditDistance.findNearest(name, names);\n return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);\n }", " private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {\n public int compare(Integer o1, Integer o2) {\n return o2-o1;\n }\n };", " private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());", " /**\n * Permission to abort a build\n */\n public static final Permission ABORT = CANCEL;", " /**\n * Replaceable \"Build Now\" text.\n */\n public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();", " /**\n * Used for CLI binding.\n */\n @CLIResolver\n public static AbstractProject resolveForCLI(\n @Argument(required=true,metaVar=\"NAME\",usage=\"Job name\") String name) throws CmdLineException {\n AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);\n if (item==null)\n throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));\n return item;\n }", " public String getCustomWorkspace() {\n return customWorkspace;\n }", " /**\n * User-specified workspace directory, or null if it's up to Jenkins.\n *\n * <p>\n * Normally a project uses the workspace location assigned by its parent container,\n * but sometimes people have builds that have hard-coded paths.\n *\n * <p>\n * This is not {@link File} because it may have to hold a path representation on another OS.\n *\n * <p>\n * If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace\n * is prepared. \n *\n * @since 1.410\n */\n public void setCustomWorkspace(String customWorkspace) throws IOException {\n this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);\n save();\n }\n \n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1943, 133], "buggy_code_start_loc": [1942, 25], "filenames": ["core/src/main/java/hudson/model/AbstractProject.java", "test/src/test/java/hudson/tasks/BuildTriggerTest.java"], "fixing_code_end_loc": [1950, 178], "fixing_code_start_loc": [1942, 26], "message": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:lts:*:*:*", "matchCriteriaId": "F5EDE52E-F7BE-457D-8E56-F24800F02241", "versionEndExcluding": null, "versionEndIncluding": "1.532.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:*:*:*:*", "matchCriteriaId": "07E4FEB5-A7D9-49FE-839A-0D650CC19C42", "versionEndExcluding": null, "versionEndIncluding": "1.550", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330."}, {"lang": "es", "value": "BuildTrigger en Jenkins en versiones anteriores a 1.551 y LTS en versiones anteriores a 1.532.2 permite a usuarios remotos autenticados eludir las restricciones de acceso y ejecutar trabajos arbitrarios configurando un trabajo para desencadenar otro trabajo. NOTA: esta vulnerabilidad existe debido a una soluci\u00f3n incompleta para CVE-2013-7330."}], "evaluatorComment": null, "id": "CVE-2014-2058", "lastModified": "2016-06-13T23:32:02.143", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-10-17T15:55:05.510", "references": [{"source": "security@debian.org", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2014/02/21/2"}, {"source": "security@debian.org", "tags": ["Patch"], "url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, {"source": "security@debian.org", "tags": ["Vendor Advisory"], "url": "https://wiki.jenkins-ci.org/display/SECURITY/Jenkins+Security+Advisory+2014-02-14"}], "sourceIdentifier": "security@debian.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-264"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, "type": "CWE-264"}
27
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * The MIT License\n * \n * Copyright (c) 2004-2011, Sun Microsystems, Inc., Kohsuke Kawaguchi,\n * Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot,\n * Luca Domenico Milanesio, R. Tyler Ballance, Stephen Connolly, Tom Huybrechts,\n * id:cactusman, Yahoo! Inc., Andrew Bayer, Manufacture Francaise des Pneumatiques\n * Michelin, Romain Seguy\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage hudson.model;", "import com.infradna.tool.bridge_method_injector.WithBridgeMethods;\nimport hudson.EnvVars;\nimport hudson.Functions;\nimport antlr.ANTLRException;\nimport hudson.AbortException;\nimport hudson.CopyOnWrite;\nimport hudson.FeedAdapter;\nimport hudson.FilePath;\nimport hudson.Launcher;\nimport hudson.Util;\nimport hudson.cli.declarative.CLIMethod;\nimport hudson.cli.declarative.CLIResolver;\nimport hudson.model.Cause.LegacyCodeCause;\nimport hudson.model.Cause.RemoteCause;\nimport hudson.model.Cause.UserIdCause;\nimport hudson.model.Descriptor.FormException;\nimport hudson.model.Fingerprint.RangeSet;\nimport hudson.model.Queue.Executable;\nimport hudson.model.Queue.Task;\nimport hudson.model.queue.QueueTaskFuture;\nimport hudson.model.queue.SubTask;\nimport hudson.model.Queue.WaitingItem;\nimport hudson.model.RunMap.Constructor;\nimport hudson.model.labels.LabelAtom;\nimport hudson.model.labels.LabelExpression;\nimport hudson.model.listeners.SCMPollListener;\nimport hudson.model.queue.CauseOfBlockage;\nimport hudson.model.queue.SubTaskContributor;\nimport hudson.scm.ChangeLogSet;\nimport hudson.scm.ChangeLogSet.Entry;\nimport hudson.scm.NullSCM;\nimport hudson.scm.PollingResult;\nimport hudson.scm.SCM;\nimport hudson.scm.SCMRevisionState;\nimport hudson.scm.SCMS;\nimport hudson.search.SearchIndexBuilder;\nimport hudson.security.ACL;\nimport hudson.security.Permission;\nimport hudson.slaves.WorkspaceList;\nimport hudson.tasks.BuildStep;\nimport hudson.tasks.BuildStepDescriptor;\nimport hudson.tasks.BuildTrigger;\nimport hudson.tasks.BuildWrapperDescriptor;\nimport hudson.tasks.Publisher;\nimport hudson.triggers.SCMTrigger;\nimport hudson.triggers.Trigger;\nimport hudson.triggers.TriggerDescriptor;\nimport hudson.util.AlternativeUiTextProvider;\nimport hudson.util.AlternativeUiTextProvider.Message;\nimport hudson.util.DescribableList;\nimport hudson.util.EditDistance;\nimport hudson.util.FormValidation;\nimport hudson.widgets.BuildHistoryWidget;\nimport hudson.widgets.HistoryWidget;\nimport jenkins.model.Jenkins;\nimport jenkins.model.JenkinsLocationConfiguration;\nimport jenkins.model.lazy.AbstractLazyLoadRunMap.Direction;\nimport jenkins.scm.DefaultSCMCheckoutStrategyImpl;\nimport jenkins.scm.SCMCheckoutStrategy;\nimport jenkins.scm.SCMCheckoutStrategyDescriptor;\nimport jenkins.util.TimeDuration;\nimport net.sf.json.JSONObject;\nimport org.acegisecurity.context.SecurityContext;\nimport org.acegisecurity.context.SecurityContextHolder;\nimport org.kohsuke.accmod.Restricted;\nimport org.kohsuke.accmod.restrictions.NoExternalUse;\nimport org.kohsuke.args4j.Argument;\nimport org.kohsuke.args4j.CmdLineException;\nimport org.kohsuke.stapler.ForwardToView;\nimport org.kohsuke.stapler.HttpRedirect;\nimport org.kohsuke.stapler.HttpResponse;\nimport org.kohsuke.stapler.HttpResponses;\nimport org.kohsuke.stapler.QueryParameter;\nimport org.kohsuke.stapler.StaplerRequest;\nimport org.kohsuke.stapler.StaplerResponse;\nimport org.kohsuke.stapler.export.Exported;\nimport org.kohsuke.stapler.interceptor.RequirePOST;", "import javax.servlet.ServletException;\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.TreeMap;\nimport java.util.Vector;\nimport java.util.concurrent.Future;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;", "import static hudson.scm.PollingResult.*;\nimport static javax.servlet.http.HttpServletResponse.*;", "/**\n * Base implementation of {@link Job}s that build software.\n *\n * For now this is primarily the common part of {@link Project} and MavenModule.\n *\n * @author Kohsuke Kawaguchi\n * @see AbstractBuild\n */\n@SuppressWarnings(\"rawtypes\")\npublic abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem {", " /**\n * {@link SCM} associated with the project.\n * To allow derived classes to link {@link SCM} config to elsewhere,\n * access to this variable should always go through {@link #getScm()}.\n */\n private volatile SCM scm = new NullSCM();", " /**\n * Controls how the checkout is done.\n */\n private volatile SCMCheckoutStrategy scmCheckoutStrategy;", " /**\n * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.\n */\n private volatile transient SCMRevisionState pollingBaseline = null;", " /**\n * All the builds keyed by their build number.\n *\n * External code should use {@link #getBuildByNumber(int)} or {@link #getLastBuild()} and traverse via\n * {@link Run#getPreviousBuild()}\n */\n @Restricted(NoExternalUse.class)\n @SuppressWarnings(\"deprecation\") // [JENKINS-15156] builds accessed before onLoad or onCreatedFromScratch called\n protected transient RunMap<R> builds = new RunMap<R>();", " /**\n * The quiet period. Null to delegate to the system default.\n */\n private volatile Integer quietPeriod = null;\n \n /**\n * The retry count. Null to delegate to the system default.\n */\n private volatile Integer scmCheckoutRetryCount = null;", " /**\n * If this project is configured to be only built on a certain label,\n * this value will be set to that label.\n *\n * For historical reasons, this is called 'assignedNode'. Also for\n * a historical reason, null to indicate the affinity\n * with the master node.\n *\n * @see #canRoam\n */\n private String assignedNode;", " /**\n * True if this project can be built on any node.\n *\n * <p>\n * This somewhat ugly flag combination is so that we can migrate\n * existing Hudson installations nicely.\n */\n private volatile boolean canRoam;", " /**\n * True to suspend new builds.\n */\n protected volatile boolean disabled;", " /**\n * True to keep builds of this project in queue when downstream projects are\n * building. False by default to keep from breaking existing behavior.\n */\n protected volatile boolean blockBuildWhenDownstreamBuilding = false;", " /**\n * True to keep builds of this project in queue when upstream projects are\n * building. False by default to keep from breaking existing behavior.\n */\n protected volatile boolean blockBuildWhenUpstreamBuilding = false;", " /**\n * Identifies {@link JDK} to be used.\n * Null if no explicit configuration is required.\n *\n * <p>\n * Can't store {@link JDK} directly because {@link Jenkins} and {@link Project}\n * are saved independently.\n *\n * @see Jenkins#getJDK(String)\n */\n private volatile String jdk;", " private volatile BuildAuthorizationToken authToken = null;", " /**\n * List of all {@link Trigger}s for this project.\n */\n protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();", " /**\n * {@link Action}s contributed from subsidiary objects associated with\n * {@link AbstractProject}, such as from triggers, builders, publishers, etc.\n *\n * We don't want to persist them separately, and these actions\n * come and go as configuration change, so it's kept separate.\n */\n @CopyOnWrite\n protected transient volatile List<Action> transientActions = new Vector<Action>();", " private boolean concurrentBuild;", " /**\n * See {@link #setCustomWorkspace(String)}.\n *\n * @since 1.410\n */\n private String customWorkspace;\n \n protected AbstractProject(ItemGroup parent, String name) {\n super(parent,name);", " if(!Jenkins.getInstance().getNodes().isEmpty()) {\n // if a new job is configured with Hudson that already has slave nodes\n // make it roamable by default\n canRoam = true;\n }\n }", " @Override\n public synchronized void save() throws IOException {\n super.save();\n updateTransientActions();\n }", " @Override\n public void onCreatedFromScratch() {\n super.onCreatedFromScratch();\n builds = createBuildRunMap();\n // solicit initial contributions, especially from TransientProjectActionFactory\n updateTransientActions();\n }", " @Override\n public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {\n super.onLoad(parent, name);", " RunMap<R> builds = createBuildRunMap();", " RunMap<R> currentBuilds = this.builds;", " if (currentBuilds==null) {\n // are we overwriting what currently exist?\n // this is primarily when Jenkins is getting reloaded\n Item current = parent.getItem(name);\n if (current!=null && current.getClass()==getClass()) {\n currentBuilds = ((AbstractProject)current).builds;\n }\n }\n if (currentBuilds !=null) {\n // if we are reloading, keep all those that are still building intact\n for (R r : currentBuilds.getLoadedBuilds().values()) {\n if (r.isBuilding())\n builds.put(r);\n }\n }\n this.builds = builds;\n for (Trigger t : triggers())\n t.start(this, Items.updatingByXml.get());\n if(scm==null)\n scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.", " if(transientActions==null)\n transientActions = new Vector<Action>(); // happens when loaded from disk\n updateTransientActions();\n }", " private RunMap<R> createBuildRunMap() {\n return new RunMap<R>(getBuildDir(), new Constructor<R>() {\n public R create(File dir) throws IOException {\n return loadBuild(dir);\n }\n });\n }", " private synchronized List<Trigger<?>> triggers() {\n if (triggers == null) {\n triggers = new Vector<Trigger<?>>();\n }\n return triggers;\n }", " @Override\n public EnvVars getEnvironment(Node node, TaskListener listener) throws IOException, InterruptedException {\n EnvVars env = super.getEnvironment(node, listener);", " JDK jdk = getJDK();\n if (jdk != null) {\n if (node != null) { // just in case were not in a build\n jdk = jdk.forNode(node, listener);\n }\n jdk.buildEnvVars(env);\n }", " return env;\n }", " @Override\n protected void performDelete() throws IOException, InterruptedException {\n // prevent a new build while a delete operation is in progress\n makeDisabled(true);\n FilePath ws = getWorkspace();\n if(ws!=null) {\n Node on = getLastBuiltOn();\n getScm().processWorkspaceBeforeDeletion(this, ws, on);\n if(on!=null)\n on.getFileSystemProvisioner().discardWorkspace(this,ws);\n }\n super.performDelete();\n }", " /**\n * Does this project perform concurrent builds?\n * @since 1.319\n */\n @Exported\n public boolean isConcurrentBuild() {\n return concurrentBuild;\n }", " public void setConcurrentBuild(boolean b) throws IOException {\n concurrentBuild = b;\n save();\n }", " /**\n * If this project is configured to be always built on this node,\n * return that {@link Node}. Otherwise null.\n */\n public Label getAssignedLabel() {\n if(canRoam)\n return null;", " if(assignedNode==null)\n return Jenkins.getInstance().getSelfLabel();\n return Jenkins.getInstance().getLabel(assignedNode);\n }", " /**\n * Set of labels relevant to this job.\n *\n * This method is used to determine what slaves are relevant to jobs, for example by {@link View}s.\n * It does not affect the scheduling. This information is informational and the best-effort basis.\n *\n * @since 1.456\n * @return\n * Minimally it should contain {@link #getAssignedLabel()}. The set can contain null element\n * to correspond to the null return value from {@link #getAssignedLabel()}.\n */\n public Set<Label> getRelevantLabels() {\n return Collections.singleton(getAssignedLabel());\n }", " /**\n * Gets the textual representation of the assigned label as it was entered by the user.\n */\n public String getAssignedLabelString() {\n if (canRoam || assignedNode==null) return null;\n try {\n LabelExpression.parseExpression(assignedNode);\n return assignedNode;\n } catch (ANTLRException e) {\n // must be old label or host name that includes whitespace or other unsafe chars\n return LabelAtom.escape(assignedNode);\n }\n }", " /**\n * Sets the assigned label.\n */\n public void setAssignedLabel(Label l) throws IOException {\n if(l==null) {\n canRoam = true;\n assignedNode = null;\n } else {\n canRoam = false;\n if(l== Jenkins.getInstance().getSelfLabel()) assignedNode = null;\n else assignedNode = l.getExpression();\n }\n save();\n }", " /**\n * Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.\n */\n public void setAssignedNode(Node l) throws IOException {\n setAssignedLabel(l.getSelfLabel());\n }", " /**\n * Get the term used in the UI to represent this kind of {@link AbstractProject}.\n * Must start with a capital letter.\n */\n @Override\n public String getPronoun() {\n return AlternativeUiTextProvider.get(PRONOUN, this,Messages.AbstractProject_Pronoun());\n }", " /**\n * Gets the human readable display name to be rendered in the \"Build Now\" link.\n *\n * @since 1.401\n */\n public String getBuildNowText() {\n return AlternativeUiTextProvider.get(BUILD_NOW_TEXT,this,Messages.AbstractProject_BuildNow());\n }", " /**\n * Gets the nearest ancestor {@link TopLevelItem} that's also an {@link AbstractProject}.\n *\n * <p>\n * Some projects (such as matrix projects, Maven projects, or promotion processes) form a tree of jobs\n * that acts as a single unit. This method can be used to find the top most dominating job that\n * covers such a tree.\n *\n * @return never null.\n * @see AbstractBuild#getRootBuild()\n */\n public AbstractProject<?,?> getRootProject() {\n if (this instanceof TopLevelItem) {\n return this;\n } else {\n ItemGroup p = this.getParent();\n if (p instanceof AbstractProject)\n return ((AbstractProject) p).getRootProject();\n return this;\n }\n }", " /**\n * Gets the directory where the module is checked out.\n *\n * @return\n * null if the workspace is on a slave that's not connected.\n * @deprecated as of 1.319\n * To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.\n * For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called\n * from {@link Executor}, and otherwise the workspace of the last build.\n *\n * <p>\n * If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.\n * If you are calling this method to serve a file from the workspace, doing a form validation, etc., then\n * use {@link #getSomeWorkspace()}\n */\n public final FilePath getWorkspace() {\n AbstractBuild b = getBuildForDeprecatedMethods();\n return b != null ? b.getWorkspace() : null;", " }\n \n /**\n * Various deprecated methods in this class all need the 'current' build. This method returns\n * the build suitable for that purpose.\n * \n * @return An AbstractBuild for deprecated methods to use.\n */\n private AbstractBuild getBuildForDeprecatedMethods() {\n Executor e = Executor.currentExecutor();\n if(e!=null) {\n Executable exe = e.getCurrentExecutable();\n if (exe instanceof AbstractBuild) {\n AbstractBuild b = (AbstractBuild) exe;\n if(b.getProject()==this)\n return b;\n }\n }\n R lb = getLastBuild();\n if(lb!=null) return lb;\n return null;\n }", " /**\n * Gets a workspace for some build of this project.\n *\n * <p>\n * This is useful for obtaining a workspace for the purpose of form field validation, where exactly\n * which build the workspace belonged is less important. The implementation makes a cursory effort\n * to find some workspace.\n *\n * @return\n * null if there's no available workspace.\n * @since 1.319\n */\n public final FilePath getSomeWorkspace() {\n R b = getSomeBuildWithWorkspace();\n if (b!=null) return b.getWorkspace();\n for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {\n FilePath f = browser.getWorkspace(this);\n if (f != null) return f;\n }\n return null;\n }", " /**\n * Gets some build that has a live workspace.\n *\n * @return null if no such build exists.\n */\n public final R getSomeBuildWithWorkspace() {\n int cnt=0;\n for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {\n FilePath ws = b.getWorkspace();\n if (ws!=null) return b;\n }\n return null;\n }", " /**\n * Returns the root directory of the checked-out module.\n * <p>\n * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>\n * and so on exists.\n *\n * @deprecated as of 1.319\n * See {@link #getWorkspace()} for a migration strategy.\n */\n public FilePath getModuleRoot() {\n AbstractBuild b = getBuildForDeprecatedMethods();\n return b != null ? b.getModuleRoot() : null;\n }", " /**\n * Returns the root directories of all checked-out modules.\n * <p>\n * Some SCMs support checking out multiple modules into the same workspace.\n * In these cases, the returned array will have a length greater than one.\n * @return The roots of all modules checked out from the SCM.\n *\n * @deprecated as of 1.319\n * See {@link #getWorkspace()} for a migration strategy.\n */\n public FilePath[] getModuleRoots() {\n AbstractBuild b = getBuildForDeprecatedMethods();\n return b != null ? b.getModuleRoots() : null;\n }", " public int getQuietPeriod() {\n return quietPeriod!=null ? quietPeriod : Jenkins.getInstance().getQuietPeriod();\n }", " public SCMCheckoutStrategy getScmCheckoutStrategy() {\n return scmCheckoutStrategy == null ? new DefaultSCMCheckoutStrategyImpl() : scmCheckoutStrategy;\n }", " public void setScmCheckoutStrategy(SCMCheckoutStrategy scmCheckoutStrategy) throws IOException {\n this.scmCheckoutStrategy = scmCheckoutStrategy;\n save();\n }", "\n public int getScmCheckoutRetryCount() {\n return scmCheckoutRetryCount !=null ? scmCheckoutRetryCount : Jenkins.getInstance().getScmCheckoutRetryCount();\n }", " // ugly name because of EL\n public boolean getHasCustomQuietPeriod() {\n return quietPeriod!=null;\n }", " /**\n * Sets the custom quiet period of this project, or revert to the global default if null is given. \n */\n public void setQuietPeriod(Integer seconds) throws IOException {\n this.quietPeriod = seconds;\n save();\n }\n \n public boolean hasCustomScmCheckoutRetryCount(){\n return scmCheckoutRetryCount != null;\n }", " @Override\n public boolean isBuildable() {\n return !isDisabled() && !isHoldOffBuildUntilSave();\n }", " /**\n * Used in <tt>sidepanel.jelly</tt> to decide whether to display\n * the config/delete/build links.\n */\n public boolean isConfigurable() {\n return true;\n }", " public boolean blockBuildWhenDownstreamBuilding() {\n return blockBuildWhenDownstreamBuilding;\n }", " public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {\n blockBuildWhenDownstreamBuilding = b;\n save();\n }", " public boolean blockBuildWhenUpstreamBuilding() {\n return blockBuildWhenUpstreamBuilding;\n }", " public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {\n blockBuildWhenUpstreamBuilding = b;\n save();\n }", " public boolean isDisabled() {\n return disabled;\n }\n \n /**\n * Validates the retry count Regex\n */\n public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{\n // retry count is optional so this is ok\n if(value == null || value.trim().equals(\"\"))\n return FormValidation.ok();\n if (!value.matches(\"[0-9]*\")) {\n return FormValidation.error(\"Invalid retry count\");\n } \n return FormValidation.ok();\n }", " /**\n * Marks the build as disabled.\n */\n public void makeDisabled(boolean b) throws IOException {\n if(disabled==b) return; // noop\n this.disabled = b;\n if(b)\n Jenkins.getInstance().getQueue().cancel(this);\n save();\n }", " /**\n * Specifies whether this project may be disabled by the user.\n * By default, it can be only if this is a {@link TopLevelItem};\n * would be false for matrix configurations, etc.\n * @return true if the GUI should allow {@link #doDisable} and the like\n * @since 1.475\n */\n public boolean supportsMakeDisabled() {\n return this instanceof TopLevelItem;\n }", " public void disable() throws IOException {\n makeDisabled(true);\n }", " public void enable() throws IOException {\n makeDisabled(false);\n }", " @Override\n public BallColor getIconColor() {\n if(isDisabled())\n return BallColor.DISABLED;\n else\n return super.getIconColor();\n }", " /**\n * effectively deprecated. Since using updateTransientActions correctly\n * under concurrent environment requires a lock that can too easily cause deadlocks.\n *\n * <p>\n * Override {@link #createTransientActions()} instead.\n */\n protected void updateTransientActions() {\n transientActions = createTransientActions();\n }", " protected List<Action> createTransientActions() {\n Vector<Action> ta = new Vector<Action>();", " for (JobProperty<? super P> p : Util.fixNull(properties))\n ta.addAll(p.getJobActions((P)this));", " for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())\n ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null\n return ta;\n }", " /**\n * Returns the live list of all {@link Publisher}s configured for this project.\n *\n * <p>\n * This method couldn't be called <tt>getPublishers()</tt> because existing methods\n * in sub-classes return different inconsistent types.\n */\n public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();", " @Override\n public void addProperty(JobProperty<? super P> jobProp) throws IOException {\n super.addProperty(jobProp);\n updateTransientActions();\n }", " public List<ProminentProjectAction> getProminentActions() {\n List<Action> a = getActions();\n List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();\n for (Action action : a) {\n if(action instanceof ProminentProjectAction)\n pa.add((ProminentProjectAction) action);\n }\n return pa;\n }", " @Override\n public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {\n super.doConfigSubmit(req,rsp);", " updateTransientActions();", " Set<AbstractProject> upstream = Collections.emptySet();\n if(req.getParameter(\"pseudoUpstreamTrigger\")!=null) {\n upstream = new HashSet<AbstractProject>(Items.fromNameList(getParent(),req.getParameter(\"upstreamProjects\"),AbstractProject.class));\n }", " // dependency setting might have been changed by the user, so rebuild.\n Jenkins.getInstance().rebuildDependencyGraph();\n convertUpstreamBuildTrigger(upstream);", "\n // notify the queue as the project might be now tied to different node\n Jenkins.getInstance().getQueue().scheduleMaintenance();", " // this is to reflect the upstream build adjustments done above\n Jenkins.getInstance().rebuildDependencyGraph();\n }", " /**\n * Reflect the submission of the pseudo 'upstream build trigger'.\n */\n /* package */ void convertUpstreamBuildTrigger(Set<AbstractProject> upstream) throws IOException {", " SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM);\n try {\n for (AbstractProject<?,?> p : Jenkins.getInstance().getAllItems(AbstractProject.class)) {\n // Don't consider child projects such as MatrixConfiguration:\n if (!p.isConfigurable()) continue;\n boolean isUpstream = upstream.contains(p);\n synchronized(p) {\n // does 'p' include us in its BuildTrigger?\n DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();\n BuildTrigger trigger = pl.get(BuildTrigger.class);\n List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(p);\n if(isUpstream) {\n if(!newChildProjects.contains(this))\n newChildProjects.add(this);\n } else {\n newChildProjects.remove(this);\n }", " if(newChildProjects.isEmpty()) {\n pl.remove(BuildTrigger.class);\n } else {\n // here, we just need to replace the old one with the new one,\n // but there was a regression (we don't know when it started) that put multiple BuildTriggers\n // into the list. For us not to lose the data, we need to merge them all.\n List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);\n BuildTrigger existing;\n switch (existingList.size()) {\n case 0:\n existing = null;\n break;\n case 1:\n existing = existingList.get(0);\n break;\n default:\n pl.removeAll(BuildTrigger.class);\n Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();\n for (BuildTrigger bt : existingList)\n combinedChildren.addAll(bt.getChildProjects(p));\n existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());\n pl.add(existing);\n break;\n }", " if(existing!=null && existing.hasSame(p,newChildProjects))\n continue; // no need to touch\n pl.replace(new BuildTrigger(newChildProjects,\n existing==null? Result.SUCCESS:existing.getThreshold()));\n }\n }\n }\n } finally {\n SecurityContextHolder.setContext(saveCtx);\n }\n }", " /**\n\t * @deprecated\n\t * Use {@link #scheduleBuild(Cause)}. Since 1.283\n\t */\n public boolean scheduleBuild() {\n \treturn scheduleBuild(new LegacyCodeCause());\n }\n \n\t/**\n\t * @deprecated\n\t * Use {@link #scheduleBuild(int, Cause)}. Since 1.283\n\t */\n public boolean scheduleBuild(int quietPeriod) {\n \treturn scheduleBuild(quietPeriod, new LegacyCodeCause());\n }\n \n /**\n * Schedules a build of this project.\n *\n * @return\n * true if the project is actually added to the queue.\n * false if the queue contained it and therefore the add()\n * was noop\n */\n public boolean scheduleBuild(Cause c) {\n return scheduleBuild(getQuietPeriod(), c);\n }", " public boolean scheduleBuild(int quietPeriod, Cause c) {\n return scheduleBuild(quietPeriod, c, new Action[0]);\n }", " /**\n * Schedules a build.\n *\n * Important: the actions should be persistable without outside references (e.g. don't store\n * references to this project). To provide parameters for a parameterized project, add a ParametersAction. If\n * no ParametersAction is provided for such a project, one will be created with the default parameter values.\n *\n * @param quietPeriod the quiet period to observer\n * @param c the cause for this build which should be recorded\n * @param actions a list of Actions that will be added to the build\n * @return whether the build was actually scheduled\n */\n public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {\n return scheduleBuild2(quietPeriod,c,actions)!=null;\n }", " /**\n * Schedules a build of this project, and returns a {@link Future} object\n * to wait for the completion of the build.\n *\n * @param actions\n * For the convenience of the caller, this array can contain null, and those will be silently ignored.\n */\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {\n return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));\n }", " /**\n * Schedules a build of this project, and returns a {@link Future} object\n * to wait for the completion of the build.\n *\n * @param actions\n * For the convenience of the caller, this collection can contain null, and those will be silently ignored.\n * @since 1.383\n */\n @SuppressWarnings(\"unchecked\")\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {\n if (!isBuildable())\n return null;", " List<Action> queueActions = new ArrayList<Action>(actions);\n if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {\n queueActions.add(new ParametersAction(getDefaultParametersValues()));\n }", " if (c != null) {\n queueActions.add(new CauseAction(c));\n }", " WaitingItem i = Jenkins.getInstance().getQueue().schedule(this, quietPeriod, queueActions);\n if(i!=null)\n return (QueueTaskFuture)i.getFuture();\n return null;\n }", " private List<ParameterValue> getDefaultParametersValues() {\n ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);\n ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();\n \n /*\n * This check is made ONLY if someone will call this method even if isParametrized() is false.\n */\n if(paramDefProp == null)\n return defValues;\n \n /* Scan for all parameter with an associated default values */\n for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())\n {\n ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();\n \n if(defaultValue != null)\n defValues.add(defaultValue); \n }\n \n return defValues;\n }", " /**\n * Schedules a build, and returns a {@link Future} object\n * to wait for the completion of the build.\n *\n * <p>\n * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked\n * as deprecated.\n */\n @SuppressWarnings(\"deprecation\")\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod) {\n return scheduleBuild2(quietPeriod, new LegacyCodeCause());\n }\n \n /**\n * Schedules a build of this project, and returns a {@link Future} object\n * to wait for the completion of the build.\n */\n @WithBridgeMethods(Future.class)\n public QueueTaskFuture<R> scheduleBuild2(int quietPeriod, Cause c) {\n return scheduleBuild2(quietPeriod, c, new Action[0]);\n }", " /**\n * Schedules a polling of this project.\n */\n public boolean schedulePolling() {\n if(isDisabled()) return false;\n SCMTrigger scmt = getTrigger(SCMTrigger.class);\n if(scmt==null) return false;\n scmt.run();\n return true;\n }", " /**\n * Returns true if the build is in the queue.\n */\n @Override\n public boolean isInQueue() {\n return Jenkins.getInstance().getQueue().contains(this);\n }", " @Override\n public Queue.Item getQueueItem() {\n return Jenkins.getInstance().getQueue().getItem(this);\n }", " /**\n * Gets the JDK that this project is configured with, or null.\n */\n public JDK getJDK() {\n return Jenkins.getInstance().getJDK(jdk);\n }", " /**\n * Overwrites the JDK setting.\n */\n public void setJDK(JDK jdk) throws IOException {\n this.jdk = jdk.getName();\n save();\n }", " public BuildAuthorizationToken getAuthToken() {\n return authToken;\n }", " @Override\n public RunMap<R> _getRuns() {\n assert builds.baseDirInitialized() : \"neither onCreatedFromScratch nor onLoad called on \" + this + \" yet\";\n return builds;\n }", " @Override\n public void removeRun(R run) {\n this.builds.remove(run);\n }", " /**\n * {@inheritDoc}\n *\n * More efficient implementation.\n */\n @Override\n public R getBuild(String id) {\n return builds.getById(id);\n }", " /**\n * {@inheritDoc}\n *\n * More efficient implementation.\n */\n @Override\n public R getBuildByNumber(int n) {\n return builds.getByNumber(n);\n }", " /**\n * {@inheritDoc}\n *\n * More efficient implementation.\n */\n @Override\n public R getFirstBuild() {\n return builds.oldestBuild();\n }", " @Override\n public R getLastBuild() {\n return builds.newestBuild();\n }", " @Override\n public R getNearestBuild(int n) {\n return builds.search(n, Direction.ASC);\n }", " @Override\n public R getNearestOldBuild(int n) {\n return builds.search(n, Direction.DESC);\n }", " /**\n * Determines Class&lt;R>.\n */\n protected abstract Class<R> getBuildClass();", " // keep track of the previous time we started a build\n private transient long lastBuildStartTime;\n \n /**\n * Creates a new build of this project for immediate execution.\n */\n protected synchronized R newBuild() throws IOException {\n \t// make sure we don't start two builds in the same second\n \t// so the build directories will be different too\n \tlong timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;\n \tif (timeSinceLast < 1000) {\n \t\ttry {\n\t\t\t\tThread.sleep(1000 - timeSinceLast);\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n \t}\n \tlastBuildStartTime = System.currentTimeMillis();\n try {\n R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);\n builds.put(lastBuild);\n return lastBuild;\n } catch (InstantiationException e) {\n throw new Error(e);\n } catch (IllegalAccessException e) {\n throw new Error(e);\n } catch (InvocationTargetException e) {\n throw handleInvocationTargetException(e);\n } catch (NoSuchMethodException e) {\n throw new Error(e);\n }\n }", " private IOException handleInvocationTargetException(InvocationTargetException e) {\n Throwable t = e.getTargetException();\n if(t instanceof Error) throw (Error)t;\n if(t instanceof RuntimeException) throw (RuntimeException)t;\n if(t instanceof IOException) return (IOException)t;\n throw new Error(t);\n }", " /**\n * Loads an existing build record from disk.\n */\n protected R loadBuild(File dir) throws IOException {\n try {\n return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);\n } catch (InstantiationException e) {\n throw new Error(e);\n } catch (IllegalAccessException e) {\n throw new Error(e);\n } catch (InvocationTargetException e) {\n throw handleInvocationTargetException(e);\n } catch (NoSuchMethodException e) {\n throw new Error(e);\n }\n }", " /**\n * {@inheritDoc}\n *\n * <p>\n * Note that this method returns a read-only view of {@link Action}s.\n * {@link BuildStep}s and others who want to add a project action\n * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.\n *\n * @see TransientProjectActionFactory\n */\n @Override\n public List<Action> getActions() {\n // add all the transient actions, too\n List<Action> actions = new Vector<Action>(super.getActions());\n actions.addAll(transientActions);\n // return the read only list to cause a failure on plugins who try to add an action here\n return Collections.unmodifiableList(actions);\n }", " /**\n * Gets the {@link Node} where this project was last built on.\n *\n * @return\n * null if no information is available (for example,\n * if no build was done yet.)\n */\n public Node getLastBuiltOn() {\n // where was it built on?\n AbstractBuild b = getLastBuild();\n if(b==null)\n return null;\n else\n return b.getBuiltOn();\n }", " public Object getSameNodeConstraint() {\n return this; // in this way, any member that wants to run with the main guy can nominate the project itself \n }", " public final Task getOwnerTask() {\n return this;\n }", " /**\n * {@inheritDoc}\n *\n * <p>\n * A project must be blocked if its own previous build is in progress,\n * or if the blockBuildWhenUpstreamBuilding option is true and an upstream\n * project is building, but derived classes can also check other conditions.\n */\n public boolean isBuildBlocked() {\n return getCauseOfBlockage()!=null;\n }", " public String getWhyBlocked() {\n CauseOfBlockage cb = getCauseOfBlockage();\n return cb!=null ? cb.getShortDescription() : null;\n }", " /**\n * Blocked because the previous build is already in progress.\n */\n public static class BecauseOfBuildInProgress extends CauseOfBlockage {\n private final AbstractBuild<?,?> build;", " public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {\n this.build = build;\n }", " @Override\n public String getShortDescription() {\n Executor e = build.getExecutor();\n String eta = \"\";\n if (e != null)\n eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());\n int lbn = build.getNumber();\n return Messages.AbstractProject_BuildInProgress(lbn, eta);\n }\n }\n \n /**\n * Because the downstream build is in progress, and we are configured to wait for that.\n */\n public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {\n public final AbstractProject<?,?> up;", " public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {\n this.up = up;\n }", " @Override\n public String getShortDescription() {\n return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());\n }\n }", " /**\n * Because the upstream build is in progress, and we are configured to wait for that.\n */\n public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {\n public final AbstractProject<?,?> up;", " public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {\n this.up = up;\n }", " @Override\n public String getShortDescription() {\n return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());\n }\n }", " public CauseOfBlockage getCauseOfBlockage() {\n // Block builds until they are done with post-production\n if (isLogUpdated() && !isConcurrentBuild())\n return new BecauseOfBuildInProgress(getLastBuild());\n if (blockBuildWhenDownstreamBuilding()) {\n AbstractProject<?,?> bup = getBuildingDownstream();\n if (bup!=null)\n return new BecauseOfDownstreamBuildInProgress(bup);\n }\n if (blockBuildWhenUpstreamBuilding()) {\n AbstractProject<?,?> bup = getBuildingUpstream();\n if (bup!=null)\n return new BecauseOfUpstreamBuildInProgress(bup);\n }\n return null;\n }", " /**\n * Returns the project if any of the downstream project is either\n * building, waiting, pending or buildable.\n * <p>\n * This means eventually there will be an automatic triggering of\n * the given project (provided that all builds went smoothly.)\n */\n public AbstractProject getBuildingDownstream() {\n Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();", " for (AbstractProject tup : getTransitiveDownstreamProjects()) {\n\t\t\tif (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))\n return tup;\n }\n return null;\n }", " /**\n * Returns the project if any of the upstream project is either\n * building or is in the queue.\n * <p>\n * This means eventually there will be an automatic triggering of\n * the given project (provided that all builds went smoothly.)\n */\n public AbstractProject getBuildingUpstream() {\n Set<Task> unblockedTasks = Jenkins.getInstance().getQueue().getUnblockedTasks();", " for (AbstractProject tup : getTransitiveUpstreamProjects()) {\n\t\t\tif (tup!=this && (tup.isBuilding() || unblockedTasks.contains(tup)))\n return tup;\n }\n return null;\n }", " public List<SubTask> getSubTasks() {\n List<SubTask> r = new ArrayList<SubTask>();\n r.add(this);\n for (SubTaskContributor euc : SubTaskContributor.all())\n r.addAll(euc.forProject(this));\n for (JobProperty<? super P> p : properties)\n r.addAll(p.getSubTasks());\n return r;\n }", " public R createExecutable() throws IOException {\n if(isDisabled()) return null;\n return newBuild();\n }", " public void checkAbortPermission() {\n checkPermission(AbstractProject.ABORT);\n }", " public boolean hasAbortPermission() {\n return hasPermission(AbstractProject.ABORT);\n }", " /**\n * Gets the {@link Resource} that represents the workspace of this project.\n * Useful for locking and mutual exclusion control.\n *\n * @deprecated as of 1.319\n * Projects no longer have a fixed workspace, ands builds will find an available workspace via\n * {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)\n * So a {@link Resource} representation for a workspace at the project level no longer makes sense.\n *\n * <p>\n * If you need to lock a workspace while you do some computation, see the source code of\n * {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.\n */\n public Resource getWorkspaceResource() {\n return new Resource(getFullDisplayName()+\" workspace\");\n }", " /**\n * List of necessary resources to perform the build of this project.\n */\n public ResourceList getResourceList() {\n final Set<ResourceActivity> resourceActivities = getResourceActivities();\n final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());\n for (ResourceActivity activity : resourceActivities) {\n if (activity != this && activity != null) {\n // defensive infinite recursion and null check\n resourceLists.add(activity.getResourceList());\n }\n }\n return ResourceList.union(resourceLists);\n }", " /**\n * Set of child resource activities of the build of this project (override in child projects).\n * @return The set of child resource activities of the build of this project.\n */\n protected Set<ResourceActivity> getResourceActivities() {\n return Collections.emptySet();\n }", " public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {\n SCM scm = getScm();\n if(scm==null)\n return true; // no SCM", " FilePath workspace = build.getWorkspace();\n workspace.mkdirs();\n \n boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);\n if (r) {\n // Only calcRevisionsFromBuild if checkout was successful. Note that modern SCM implementations\n // won't reach this line anyway, as they throw AbortExceptions on checkout failure.\n calcPollingBaseline(build, launcher, listener);\n }\n return r;\n }", " /**\n * Pushes the baseline up to the newly checked out revision.\n */\n private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {\n SCMRevisionState baseline = build.getAction(SCMRevisionState.class);\n if (baseline==null) {\n try {\n baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);\n } catch (AbstractMethodError e) {\n baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling\n }\n if (baseline!=null)\n build.addAction(baseline);\n }\n pollingBaseline = baseline;\n }", " /**\n * Checks if there's any update in SCM, and returns true if any is found.\n *\n * @deprecated as of 1.346\n * Use {@link #poll(TaskListener)} instead.\n */\n public boolean pollSCMChanges( TaskListener listener ) {\n return poll(listener).hasChanges();\n }", " /**\n * Checks if there's any update in SCM, and returns true if any is found.\n *\n * <p>\n * The implementation is responsible for ensuring mutual exclusion between polling and builds\n * if necessary.\n *\n * @since 1.345\n */\n public PollingResult poll( TaskListener listener ) {\n SCM scm = getScm();\n if (scm==null) {\n listener.getLogger().println(Messages.AbstractProject_NoSCM());\n return NO_CHANGES;\n }\n if (!isBuildable()) {\n listener.getLogger().println(Messages.AbstractProject_Disabled());\n return NO_CHANGES;\n }", " R lb = getLastBuild();\n if (lb==null) {\n listener.getLogger().println(Messages.AbstractProject_NoBuilds());\n return isInQueue() ? NO_CHANGES : BUILD_NOW;\n }", " if (pollingBaseline==null) {\n R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this\n for (R r=lb; r!=null; r=r.getPreviousBuild()) {\n SCMRevisionState s = r.getAction(SCMRevisionState.class);\n if (s!=null) {\n pollingBaseline = s;\n break;\n }\n if (r==success) break; // searched far enough\n }\n // NOTE-NO-BASELINE:\n // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline\n // as action, so we need to compute it. This happens later.\n }", " try {\n SCMPollListener.fireBeforePolling(this, listener);\n PollingResult r = _poll(listener, scm, lb);\n SCMPollListener.firePollingSuccess(this,listener, r);\n return r;\n } catch (AbortException e) {\n listener.getLogger().println(e.getMessage());\n listener.fatalError(Messages.AbstractProject_Aborted());\n LOGGER.log(Level.FINE, \"Polling \"+this+\" aborted\",e);\n SCMPollListener.firePollingFailed(this, listener,e);\n return NO_CHANGES;\n } catch (IOException e) {\n e.printStackTrace(listener.fatalError(e.getMessage()));\n SCMPollListener.firePollingFailed(this, listener,e);\n return NO_CHANGES;\n } catch (InterruptedException e) {\n e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));\n SCMPollListener.firePollingFailed(this, listener,e);\n return NO_CHANGES;\n } catch (RuntimeException e) {\n SCMPollListener.firePollingFailed(this, listener,e);\n throw e;\n } catch (Error e) {\n SCMPollListener.firePollingFailed(this, listener,e);\n throw e;\n }\n }", " /**\n * {@link #poll(TaskListener)} method without the try/catch block that does listener notification and .\n */\n private PollingResult _poll(TaskListener listener, SCM scm, R lb) throws IOException, InterruptedException {\n if (scm.requiresWorkspaceForPolling()) {\n // lock the workspace of the last build\n FilePath ws=lb.getWorkspace();", " WorkspaceOfflineReason workspaceOfflineReason = workspaceOffline( lb );\n if ( workspaceOfflineReason != null ) {\n // workspace offline\n for (WorkspaceBrowser browser : Jenkins.getInstance().getExtensionList(WorkspaceBrowser.class)) {\n ws = browser.getWorkspace(this);\n if (ws != null) {\n return pollWithWorkspace(listener, scm, lb, ws, browser.getWorkspaceList());\n }\n }", " // build now, or nothing will ever be built\n Label label = getAssignedLabel();\n if (label != null && label.isSelfLabel()) {\n // if the build is fixed on a node, then attempting a build will do us\n // no good. We should just wait for the slave to come back.\n listener.getLogger().print(Messages.AbstractProject_NoWorkspace());\n listener.getLogger().println( \" (\" + workspaceOfflineReason.name() + \")\");\n return NO_CHANGES;\n }\n listener.getLogger().println( ws==null\n ? Messages.AbstractProject_WorkspaceOffline()\n : Messages.AbstractProject_NoWorkspace());\n if (isInQueue()) {\n listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());\n return NO_CHANGES;\n } else {\n listener.getLogger().print(Messages.AbstractProject_NewBuildForWorkspace());\n listener.getLogger().println( \" (\" + workspaceOfflineReason.name() + \")\");\n return BUILD_NOW;\n }\n } else {\n WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();\n return pollWithWorkspace(listener, scm, lb, ws, l);", " }\n } else {\n // polling without workspace\n LOGGER.fine(\"Polling SCM changes of \" + getName());", " if (pollingBaseline==null) // see NOTE-NO-BASELINE above\n calcPollingBaseline(lb,null,listener);\n PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);\n pollingBaseline = r.remote;\n return r;\n }\n }", " private PollingResult pollWithWorkspace(TaskListener listener, SCM scm, R lb, FilePath ws, WorkspaceList l) throws InterruptedException, IOException {\n // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.\n // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.\n //\n // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,\n // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)\n // by having multiple workspaces\n WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);\n Launcher launcher = ws.createLauncher(listener).decorateByEnv(getEnvironment(lb.getBuiltOn(),listener));\n try {\n LOGGER.fine(\"Polling SCM changes of \" + getName());\n if (pollingBaseline==null) // see NOTE-NO-BASELINE above\n calcPollingBaseline(lb,launcher,listener);\n PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);\n pollingBaseline = r.remote;\n return r;\n } finally {\n lease.release();\n }\n }", " enum WorkspaceOfflineReason {\n nonexisting_workspace,\n builton_node_gone,\n builton_node_no_executors\n }", " private WorkspaceOfflineReason workspaceOffline(R build) throws IOException, InterruptedException {\n FilePath ws = build.getWorkspace();\n if (ws==null || !ws.exists()) {\n return WorkspaceOfflineReason.nonexisting_workspace;\n }\n \n Node builtOn = build.getBuiltOn();\n if (builtOn == null) { // node built-on doesn't exist anymore\n return WorkspaceOfflineReason.builton_node_gone;\n }\n \n if (builtOn.toComputer() == null) { // node still exists, but has 0 executors - o.s.l.t.\n return WorkspaceOfflineReason.builton_node_no_executors;\n }", " return null;\n }", " /**\n * Returns true if this user has made a commit to this project.\n *\n * @since 1.191\n */\n public boolean hasParticipant(User user) {\n for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())\n if(build.hasParticipant(user))\n return true;\n return false;\n }", " @Exported\n public SCM getScm() {\n return scm;\n }", " public void setScm(SCM scm) throws IOException {\n this.scm = scm;\n save();\n }", " /**\n * Adds a new {@link Trigger} to this {@link Project} if not active yet.\n */\n public void addTrigger(Trigger<?> trigger) throws IOException {\n addToList(trigger,triggers());\n }", " public void removeTrigger(TriggerDescriptor trigger) throws IOException {\n removeFromList(trigger,triggers());\n }", " protected final synchronized <T extends Describable<T>>\n void addToList( T item, List<T> collection ) throws IOException {\n for( int i=0; i<collection.size(); i++ ) {\n if(collection.get(i).getDescriptor()==item.getDescriptor()) {\n // replace\n collection.set(i,item);\n save();\n return;\n }\n }\n // add\n collection.add(item);\n save();\n updateTransientActions();\n }", " protected final synchronized <T extends Describable<T>>\n void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {\n for( int i=0; i< collection.size(); i++ ) {\n if(collection.get(i).getDescriptor()==item) {\n // found it\n collection.remove(i);\n save();\n updateTransientActions();\n return;\n }\n }\n }", " @SuppressWarnings(\"unchecked\")\n public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {\n return (Map)Descriptor.toMap(triggers());\n }", " /**\n * Gets the specific trigger, or null if the propert is not configured for this job.\n */\n public <T extends Trigger> T getTrigger(Class<T> clazz) {\n for (Trigger p : triggers()) {\n if(clazz.isInstance(p))\n return clazz.cast(p);\n }\n return null;\n }", "//\n//\n// fingerprint related\n//\n//\n /**\n * True if the builds of this project produces {@link Fingerprint} records.\n */\n public abstract boolean isFingerprintConfigured();", " /**\n * Gets the other {@link AbstractProject}s that should be built\n * when a build of this project is completed.\n */\n @Exported\n public final List<AbstractProject> getDownstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getDownstream(this);\n }", " @Exported\n public final List<AbstractProject> getUpstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getUpstream(this);\n }", " /**\n * Returns only those upstream projects that defines {@link BuildTrigger} to this project.\n * This is a subset of {@link #getUpstreamProjects()}\n *\n * @return A List of upstream projects that has a {@link BuildTrigger} to this project.\n */\n public final List<AbstractProject> getBuildTriggerUpstreamProjects() {\n ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();\n for (AbstractProject<?,?> ap : getUpstreamProjects()) {\n BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);\n if (buildTrigger != null)\n if (buildTrigger.getChildProjects(ap).contains(this))\n result.add(ap);\n } \n return result;\n } \n \n /**\n * Gets all the upstream projects including transitive upstream projects.\n *\n * @since 1.138\n */\n public final Set<AbstractProject> getTransitiveUpstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getTransitiveUpstream(this);\n }", " /**\n * Gets all the downstream projects including transitive downstream projects.\n *\n * @since 1.138\n */\n public final Set<AbstractProject> getTransitiveDownstreamProjects() {\n return Jenkins.getInstance().getDependencyGraph().getTransitiveDownstream(this);\n }", " /**\n * Gets the dependency relationship map between this project (as the source)\n * and that project (as the sink.)\n *\n * @return\n * can be empty but not null. build number of this project to the build\n * numbers of that project.\n */\n public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {\n TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);", " checkAndRecord(that, r, this.getBuilds());\n // checkAndRecord(that, r, that.getBuilds());", " return r;\n }", " /**\n * Helper method for getDownstreamRelationship.\n *\n * For each given build, find the build number range of the given project and put that into the map.\n */\n private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {\n for (R build : builds) {\n RangeSet rs = build.getDownstreamRelationship(that);\n if(rs==null || rs.isEmpty())\n continue;", " int n = build.getNumber();", " RangeSet value = r.get(n);\n if(value==null)\n r.put(n,rs);\n else\n value.add(rs);\n }\n }", " /**\n * Builds the dependency graph.\n * @see DependencyGraph\n */\n protected abstract void buildDependencyGraph(DependencyGraph graph);", " @Override\n protected SearchIndexBuilder makeSearchIndex() {\n SearchIndexBuilder sib = super.makeSearchIndex();\n if(isBuildable() && hasPermission(Jenkins.ADMINISTER))\n sib.add(\"build\",\"build\");\n return sib;\n }", " @Override\n protected HistoryWidget createHistoryWidget() {\n return new BuildHistoryWidget<R>(this,builds,HISTORY_ADAPTER);\n }\n \n public boolean isParameterized() {\n return getProperty(ParametersDefinitionProperty.class) != null;\n }", "//\n//\n// actions\n//\n//\n /**\n * Schedules a new build command.\n */\n public void doBuild( StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay ) throws IOException, ServletException {\n if (delay==null) delay=new TimeDuration(getQuietPeriod());", " // if a build is parameterized, let that take over\n ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);\n if (pp != null && !req.getMethod().equals(\"POST\")) {\n // show the parameter entry form.\n req.getView(pp, \"index.jelly\").forward(req, rsp);\n return;\n }", " BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);", " if (pp != null) {\n pp._doBuild(req,rsp,delay);\n return;\n }", " if (!isBuildable())\n throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+\" is not buildable\"));", " Jenkins.getInstance().getQueue().schedule(this, (int)delay.getTime(), getBuildCause(req));\n rsp.sendRedirect(\".\");\n }", " /**\n * Computes the build cause, using RemoteCause or UserCause as appropriate.\n */\n /*package*/ CauseAction getBuildCause(StaplerRequest req) {\n Cause cause;\n if (authToken != null && authToken.getToken() != null && req.getParameter(\"token\") != null) {\n // Optional additional cause text when starting via token\n String causeText = req.getParameter(\"cause\");\n cause = new RemoteCause(req.getRemoteAddr(), causeText);\n } else {\n cause = new UserIdCause();\n }\n return new CauseAction(cause);\n }", " /**\n * Computes the delay by taking the default value and the override in the request parameter into the account.\n *\n * @deprecated as of 1.488\n * Inject {@link TimeDuration}.\n */\n public int getDelay(StaplerRequest req) throws ServletException {\n String delay = req.getParameter(\"delay\");\n if (delay==null) return getQuietPeriod();", " try {\n // TODO: more unit handling\n if(delay.endsWith(\"sec\")) delay=delay.substring(0,delay.length()-3);\n if(delay.endsWith(\"secs\")) delay=delay.substring(0,delay.length()-4);\n return Integer.parseInt(delay);\n } catch (NumberFormatException e) {\n throw new ServletException(\"Invalid delay parameter value: \"+delay);\n }\n }", " /**\n * Supports build trigger with parameters via an HTTP GET or POST.\n * Currently only String parameters are supported.\n */\n public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {\n BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);", " ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);\n if (pp != null) {\n pp.buildWithParameters(req,rsp,delay);\n } else {\n \tthrow new IllegalStateException(\"This build is not parameterized!\");\n }\n \t\n }", " /**\n * Schedules a new SCM polling command.\n */\n public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);\n schedulePolling();\n rsp.sendRedirect(\".\");\n }", " /**\n * Cancels a scheduled build.\n */\n @RequirePOST\n public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n checkPermission(ABORT);", " Jenkins.getInstance().getQueue().cancel(this);\n rsp.forwardToPreviousPage(req);\n }", " /**\n * Deletes this project.\n */\n @Override\n @RequirePOST\n public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException {\n delete();\n if (req == null || rsp == null)\n return;\n View view = req.findAncestorObject(View.class);\n if (view == null)\n rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl());\n else \n rsp.sendRedirect2(req.getContextPath() + '/' + view.getUrl());\n }\n \n @Override\n protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {\n super.submit(req,rsp);\n JSONObject json = req.getSubmittedForm();", " makeDisabled(req.getParameter(\"disable\")!=null);", " jdk = req.getParameter(\"jdk\");\n if(req.getParameter(\"hasCustomQuietPeriod\")!=null) {\n quietPeriod = Integer.parseInt(req.getParameter(\"quiet_period\"));\n } else {\n quietPeriod = null;\n }\n if(req.getParameter(\"hasCustomScmCheckoutRetryCount\")!=null) {\n scmCheckoutRetryCount = Integer.parseInt(req.getParameter(\"scmCheckoutRetryCount\"));\n } else {\n scmCheckoutRetryCount = null;\n }\n blockBuildWhenDownstreamBuilding = req.getParameter(\"blockBuildWhenDownstreamBuilding\")!=null;\n blockBuildWhenUpstreamBuilding = req.getParameter(\"blockBuildWhenUpstreamBuilding\")!=null;", " if(req.hasParameter(\"customWorkspace\")) {\n customWorkspace = Util.fixEmptyAndTrim(req.getParameter(\"customWorkspace.directory\"));\n } else {\n customWorkspace = null;\n }", " if (json.has(\"scmCheckoutStrategy\"))\n scmCheckoutStrategy = req.bindJSON(SCMCheckoutStrategy.class,\n json.getJSONObject(\"scmCheckoutStrategy\"));\n else\n scmCheckoutStrategy = null;", " \n if(req.getParameter(\"hasSlaveAffinity\")!=null) {\n assignedNode = Util.fixEmptyAndTrim(req.getParameter(\"_.assignedLabelString\"));\n } else {\n assignedNode = null;\n }\n canRoam = assignedNode==null;", " concurrentBuild = req.getSubmittedForm().has(\"concurrentBuild\");", " authToken = BuildAuthorizationToken.create(req);", " setScm(SCMS.parseSCM(req,this));", " for (Trigger t : triggers())\n t.stop();\n triggers = buildDescribable(req, Trigger.for_(this));\n for (Trigger t : triggers)\n t.start(this,true);", " for (Publisher _t : Descriptor.newInstancesFromHeteroList(req, json, \"publisher\", Jenkins.getInstance().getExtensionList(BuildTrigger.DescriptorImpl.class))) {\n BuildTrigger t = (BuildTrigger) _t;", " List<AbstractProject> childProjects;\n SecurityContext orig = ACL.impersonate(ACL.SYSTEM);\n try {\n childProjects = t.getChildProjects(this);\n } finally {\n SecurityContextHolder.setContext(orig);\n }\n for (AbstractProject downstream : childProjects) {", " downstream.checkPermission(BUILD);\n }\n }\n }", " /**\n * @deprecated\n * As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.\n */\n protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {\n return buildDescribable(req,descriptors);\n }", " protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)\n throws FormException, ServletException {", " JSONObject data = req.getSubmittedForm();\n List<T> r = new Vector<T>();\n for (Descriptor<T> d : descriptors) {\n String safeName = d.getJsonSafeClassName();\n if (req.getParameter(safeName) != null) {\n T instance = d.newInstance(req, data.getJSONObject(safeName));\n r.add(instance);\n }\n }\n return r;\n }", " /**\n * Serves the workspace files.\n */\n public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {\n checkPermission(AbstractProject.WORKSPACE);\n FilePath ws = getSomeWorkspace();\n if ((ws == null) || (!ws.exists())) {\n // if there's no workspace, report a nice error message\n // Would be good if when asked for *plain*, do something else!\n // (E.g. return 404, or send empty doc.)\n // Not critical; client can just check if content type is not text/plain,\n // which also serves to detect old versions of Hudson.\n req.getView(this,\"noWorkspace.jelly\").forward(req,rsp);\n return null;\n } else {\n return new DirectoryBrowserSupport(this, ws, getDisplayName()+\" workspace\", \"folder.png\", true);\n }\n }", " /**\n * Wipes out the workspace.\n */\n public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {\n checkPermission(Functions.isWipeOutPermissionEnabled() ? WIPEOUT : BUILD);\n R b = getSomeBuildWithWorkspace();\n FilePath ws = b!=null ? b.getWorkspace() : null;\n if (ws!=null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {\n ws.deleteRecursive();\n for (WorkspaceListener wl : WorkspaceListener.all()) {\n wl.afterDelete(this);\n }\n return new HttpRedirect(\".\");\n } else {\n // If we get here, that means the SCM blocked the workspace deletion.\n return new ForwardToView(this,\"wipeOutWorkspaceBlocked.jelly\");\n }\n }", " @CLIMethod(name=\"disable-job\")\n @RequirePOST\n public HttpResponse doDisable() throws IOException, ServletException {\n checkPermission(CONFIGURE);\n makeDisabled(true);\n return new HttpRedirect(\".\");\n }", " @CLIMethod(name=\"enable-job\")\n @RequirePOST\n public HttpResponse doEnable() throws IOException, ServletException {\n checkPermission(CONFIGURE);\n makeDisabled(false);\n return new HttpRedirect(\".\");\n }", " /**\n * RSS feed for changes in this project.\n */\n public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {\n class FeedItem {\n ChangeLogSet.Entry e;\n int idx;", " public FeedItem(Entry e, int idx) {\n this.e = e;\n this.idx = idx;\n }", " AbstractBuild<?,?> getBuild() {\n return e.getParent().build;\n }\n }", " List<FeedItem> entries = new ArrayList<FeedItem>();", " for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {\n int idx=0;\n for( ChangeLogSet.Entry e : r.getChangeSet())\n entries.add(new FeedItem(e,idx++));\n }", " RSS.forwardToRss(\n getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+\" changes\",\n getUrl()+\"changes\",\n entries, new FeedAdapter<FeedItem>() {\n public String getEntryTitle(FeedItem item) {\n return \"#\"+item.getBuild().number+' '+item.e.getMsg()+\" (\"+item.e.getAuthor()+\")\";\n }", " public String getEntryUrl(FeedItem item) {\n return item.getBuild().getUrl()+\"changes#detail\"+item.idx;\n }", " public String getEntryID(FeedItem item) {\n return getEntryUrl(item);\n }", " public String getEntryDescription(FeedItem item) {\n StringBuilder buf = new StringBuilder();\n for(String path : item.e.getAffectedPaths())\n buf.append(path).append('\\n');\n return buf.toString();\n }", " public Calendar getEntryTimestamp(FeedItem item) {\n return item.getBuild().getTimestamp();\n }", " public String getEntryAuthor(FeedItem entry) {\n return JenkinsLocationConfiguration.get().getAdminAddress();\n }\n },\n req, rsp );\n }", " /**\n * {@link AbstractProject} subtypes should implement this base class as a descriptor.\n *\n * @since 1.294\n */\n public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {\n /**\n * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s\n * from showing up on their configuration screen. This is often useful when you are building\n * a workflow/company specific project type, where you want to limit the number of choices\n * given to the users.\n *\n * <p>\n * Some {@link Descriptor}s define their own schemes for controlling applicability\n * (such as {@link BuildStepDescriptor#isApplicable(Class)}),\n * This method works like AND in conjunction with them;\n * Both this method and that method need to return true in order for a given {@link Descriptor}\n * to show up for the given {@link Project}.\n *\n * <p>\n * The default implementation returns true for everything.\n *\n * @see BuildStepDescriptor#isApplicable(Class) \n * @see BuildWrapperDescriptor#isApplicable(AbstractProject) \n * @see TriggerDescriptor#isApplicable(Item)\n */\n @Override\n public boolean isApplicable(Descriptor descriptor) {\n return true;\n }", " public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {\n if (Util.fixEmpty(value)==null)\n return FormValidation.ok(); // nothing typed yet\n try {\n Label.parseExpression(value);\n } catch (ANTLRException e) {\n return FormValidation.error(e,\n Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));\n }\n Label l = Jenkins.getInstance().getLabel(value);\n if (l.isEmpty()) {\n for (LabelAtom a : l.listAtoms()) {\n if (a.isEmpty()) {\n LabelAtom nearest = LabelAtom.findNearest(a.getName());\n return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch_DidYouMean(a.getName(),nearest.getDisplayName()));\n }\n }\n return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());\n }\n return FormValidation.ok();\n }", " public FormValidation doCheckCustomWorkspace(@QueryParameter(value=\"customWorkspace.directory\") String customWorkspace){\n \tif(Util.fixEmptyAndTrim(customWorkspace)==null)\n \t\treturn FormValidation.error(Messages.AbstractProject_CustomWorkspaceEmpty());\n \telse\n \t\treturn FormValidation.ok();\n }\n \n public AutoCompletionCandidates doAutoCompleteUpstreamProjects(@QueryParameter String value) {\n AutoCompletionCandidates candidates = new AutoCompletionCandidates();\n List<Job> jobs = Jenkins.getInstance().getItems(Job.class);\n for (Job job: jobs) {\n if (job.getFullName().startsWith(value)) {\n if (job.hasPermission(Item.READ)) {\n candidates.add(job.getFullName());\n }\n }\n }\n return candidates;\n }", " public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {\n AutoCompletionCandidates c = new AutoCompletionCandidates();\n Set<Label> labels = Jenkins.getInstance().getLabels();\n List<String> queries = new AutoCompleteSeeder(value).getSeeds();", " for (String term : queries) {\n for (Label l : labels) {\n if (l.getName().startsWith(term)) {\n c.add(l.getName());\n }\n }\n }\n return c;\n }", " public List<SCMCheckoutStrategyDescriptor> getApplicableSCMCheckoutStrategyDescriptors(AbstractProject p) {\n return SCMCheckoutStrategyDescriptor._for(p);\n }", " /**\n * Utility class for taking the current input value and computing a list\n * of potential terms to match against the list of defined labels.\n */\n static class AutoCompleteSeeder {\n private String source;", " AutoCompleteSeeder(String source) {\n this.source = source;\n }", " List<String> getSeeds() {\n ArrayList<String> terms = new ArrayList<String>();\n boolean trailingQuote = source.endsWith(\"\\\"\");\n boolean leadingQuote = source.startsWith(\"\\\"\");\n boolean trailingSpace = source.endsWith(\" \");", " if (trailingQuote || (trailingSpace && !leadingQuote)) {\n terms.add(\"\");\n } else {\n if (leadingQuote) {\n int quote = source.lastIndexOf('\"');\n if (quote == 0) {\n terms.add(source.substring(1));\n } else {\n terms.add(\"\");\n }\n } else {\n int space = source.lastIndexOf(' ');\n if (space > -1) {\n terms.add(source.substring(space+1));\n } else {\n terms.add(source);\n }\n }\n }", " return terms;\n }\n }\n }", " /**\n * Finds a {@link AbstractProject} that has the name closest to the given name.\n */\n public static AbstractProject findNearest(String name) {\n return findNearest(name,Hudson.getInstance());\n }", " /**\n * Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.\n *\n * @since 1.419\n */\n public static AbstractProject findNearest(String name, ItemGroup context) {\n List<AbstractProject> projects = Hudson.getInstance().getAllItems(AbstractProject.class);\n String[] names = new String[projects.size()];\n for( int i=0; i<projects.size(); i++ )\n names[i] = projects.get(i).getRelativeNameFrom(context);", " String nearest = EditDistance.findNearest(name, names);\n return (AbstractProject)Jenkins.getInstance().getItem(nearest,context);\n }", " private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {\n public int compare(Integer o1, Integer o2) {\n return o2-o1;\n }\n };", " private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());", " /**\n * Permission to abort a build\n */\n public static final Permission ABORT = CANCEL;", " /**\n * Replaceable \"Build Now\" text.\n */\n public static final Message<AbstractProject> BUILD_NOW_TEXT = new Message<AbstractProject>();", " /**\n * Used for CLI binding.\n */\n @CLIResolver\n public static AbstractProject resolveForCLI(\n @Argument(required=true,metaVar=\"NAME\",usage=\"Job name\") String name) throws CmdLineException {\n AbstractProject item = Jenkins.getInstance().getItemByFullName(name, AbstractProject.class);\n if (item==null)\n throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));\n return item;\n }", " public String getCustomWorkspace() {\n return customWorkspace;\n }", " /**\n * User-specified workspace directory, or null if it's up to Jenkins.\n *\n * <p>\n * Normally a project uses the workspace location assigned by its parent container,\n * but sometimes people have builds that have hard-coded paths.\n *\n * <p>\n * This is not {@link File} because it may have to hold a path representation on another OS.\n *\n * <p>\n * If this path is relative, it's resolved against {@link Node#getRootPath()} on the node where this workspace\n * is prepared. \n *\n * @since 1.410\n */\n public void setCustomWorkspace(String customWorkspace) throws IOException {\n this.customWorkspace= Util.fixEmptyAndTrim(customWorkspace);\n save();\n }\n \n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1943, 133], "buggy_code_start_loc": [1942, 25], "filenames": ["core/src/main/java/hudson/model/AbstractProject.java", "test/src/test/java/hudson/tasks/BuildTriggerTest.java"], "fixing_code_end_loc": [1950, 178], "fixing_code_start_loc": [1942, 26], "message": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:lts:*:*:*", "matchCriteriaId": "F5EDE52E-F7BE-457D-8E56-F24800F02241", "versionEndExcluding": null, "versionEndIncluding": "1.532.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:*:*:*:*", "matchCriteriaId": "07E4FEB5-A7D9-49FE-839A-0D650CC19C42", "versionEndExcluding": null, "versionEndIncluding": "1.550", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330."}, {"lang": "es", "value": "BuildTrigger en Jenkins en versiones anteriores a 1.551 y LTS en versiones anteriores a 1.532.2 permite a usuarios remotos autenticados eludir las restricciones de acceso y ejecutar trabajos arbitrarios configurando un trabajo para desencadenar otro trabajo. NOTA: esta vulnerabilidad existe debido a una soluci\u00f3n incompleta para CVE-2013-7330."}], "evaluatorComment": null, "id": "CVE-2014-2058", "lastModified": "2016-06-13T23:32:02.143", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-10-17T15:55:05.510", "references": [{"source": "security@debian.org", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2014/02/21/2"}, {"source": "security@debian.org", "tags": ["Patch"], "url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, {"source": "security@debian.org", "tags": ["Vendor Advisory"], "url": "https://wiki.jenkins-ci.org/display/SECURITY/Jenkins+Security+Advisory+2014-02-14"}], "sourceIdentifier": "security@debian.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-264"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, "type": "CWE-264"}
27
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * The MIT License\n *\n * Copyright (c) 2004-2009, Sun Microsystems, Inc., Alan Harder\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage hudson.tasks;\n", "", "import com.gargoylesoftware.htmlunit.html.HtmlForm;\nimport com.gargoylesoftware.htmlunit.html.HtmlPage;", "", "import hudson.maven.MavenModuleSet;\nimport hudson.maven.MavenModuleSetBuild;\nimport hudson.model.FreeStyleBuild;\nimport hudson.model.FreeStyleProject;", "", "import hudson.model.Result;\nimport hudson.model.Run;", "", "import org.jvnet.hudson.test.ExtractResourceSCM;\nimport org.jvnet.hudson.test.HudsonTestCase;\nimport org.jvnet.hudson.test.MockBuilder;", "/**\n * Tests for hudson.tasks.BuildTrigger\n * @author Alan.Harder@sun.com\n */\npublic class BuildTriggerTest extends HudsonTestCase {", " private FreeStyleProject createDownstreamProject() throws Exception {\n FreeStyleProject dp = createFreeStyleProject(\"downstream\");", " // Hm, no setQuietPeriod, have to submit form..\n WebClient webClient = new WebClient();\n HtmlPage page = webClient.getPage(dp,\"configure\");\n HtmlForm form = page.getFormByName(\"config\");\n form.getInputByName(\"hasCustomQuietPeriod\").click();\n form.getInputByName(\"quiet_period\").setValueAttribute(\"0\");\n submit(form);\n assertEquals(\"set quiet period\", 0, dp.getQuietPeriod());", " return dp;\n }", " private void doTriggerTest(boolean evenWhenUnstable, Result triggerResult,\n Result dontTriggerResult) throws Exception {\n FreeStyleProject p = createFreeStyleProject(),\n dp = createDownstreamProject();\n p.getPublishersList().add(new BuildTrigger(\"downstream\", evenWhenUnstable));\n p.getBuildersList().add(new MockBuilder(dontTriggerResult));\n jenkins.rebuildDependencyGraph();", " // First build should not trigger downstream job\n FreeStyleBuild b = p.scheduleBuild2(0).get();\n assertNoDownstreamBuild(dp, b);", " // Next build should trigger downstream job\n p.getBuildersList().replace(new MockBuilder(triggerResult));\n b = p.scheduleBuild2(0).get();\n assertDownstreamBuild(dp, b);\n }", " private void assertNoDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {\n for (int i = 0; i < 3; i++) {\n Thread.sleep(200);\n assertTrue(\"downstream build should not run! upstream log: \" + getLog(b),\n !dp.isInQueue() && !dp.isBuilding() && dp.getLastBuild()==null);\n }\n }", " private void assertDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {\n // Wait for downstream build\n for (int i = 0; dp.getLastBuild()==null && i < 20; i++) Thread.sleep(100);\n assertNotNull(\"downstream build didn't run.. upstream log: \" + getLog(b), dp.getLastBuild());\n }", " public void testBuildTrigger() throws Exception {\n doTriggerTest(false, Result.SUCCESS, Result.UNSTABLE);\n }", " public void testTriggerEvenWhenUnstable() throws Exception {\n doTriggerTest(true, Result.UNSTABLE, Result.FAILURE);\n }", " private void doMavenTriggerTest(boolean evenWhenUnstable) throws Exception {\n FreeStyleProject dp = createDownstreamProject();\n configureDefaultMaven();\n MavenModuleSet m = createMavenProject();\n m.getPublishersList().add(new BuildTrigger(\"downstream\", evenWhenUnstable));\n if (!evenWhenUnstable) {\n // Configure for UNSTABLE\n m.setGoals(\"clean test\");\n m.setScm(new ExtractResourceSCM(getClass().getResource(\"maven-test-failure.zip\")));\n } // otherwise do nothing which gets FAILURE\n // First build should not trigger downstream project\n MavenModuleSetBuild b = m.scheduleBuild2(0).get();\n assertNoDownstreamBuild(dp, b);", " if (evenWhenUnstable) {\n // Configure for UNSTABLE\n m.setGoals(\"clean test\");\n m.setScm(new ExtractResourceSCM(getClass().getResource(\"maven-test-failure.zip\")));\n } else {\n // Configure for SUCCESS\n m.setGoals(\"clean\");\n m.setScm(new ExtractResourceSCM(getClass().getResource(\"maven-empty.zip\")));\n }\n // Next build should trigger downstream project\n b = m.scheduleBuild2(0).get();\n assertDownstreamBuild(dp, b);\n }", " public void testMavenBuildTrigger() throws Exception {\n doMavenTriggerTest(false);\n }", " public void testMavenTriggerEvenWhenUnstable() throws Exception {\n doMavenTriggerTest(true);\n }", "", "}" ]
[ 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1943, 133], "buggy_code_start_loc": [1942, 25], "filenames": ["core/src/main/java/hudson/model/AbstractProject.java", "test/src/test/java/hudson/tasks/BuildTriggerTest.java"], "fixing_code_end_loc": [1950, 178], "fixing_code_start_loc": [1942, 26], "message": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:lts:*:*:*", "matchCriteriaId": "F5EDE52E-F7BE-457D-8E56-F24800F02241", "versionEndExcluding": null, "versionEndIncluding": "1.532.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:*:*:*:*", "matchCriteriaId": "07E4FEB5-A7D9-49FE-839A-0D650CC19C42", "versionEndExcluding": null, "versionEndIncluding": "1.550", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330."}, {"lang": "es", "value": "BuildTrigger en Jenkins en versiones anteriores a 1.551 y LTS en versiones anteriores a 1.532.2 permite a usuarios remotos autenticados eludir las restricciones de acceso y ejecutar trabajos arbitrarios configurando un trabajo para desencadenar otro trabajo. NOTA: esta vulnerabilidad existe debido a una soluci\u00f3n incompleta para CVE-2013-7330."}], "evaluatorComment": null, "id": "CVE-2014-2058", "lastModified": "2016-06-13T23:32:02.143", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-10-17T15:55:05.510", "references": [{"source": "security@debian.org", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2014/02/21/2"}, {"source": "security@debian.org", "tags": ["Patch"], "url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, {"source": "security@debian.org", "tags": ["Vendor Advisory"], "url": "https://wiki.jenkins-ci.org/display/SECURITY/Jenkins+Security+Advisory+2014-02-14"}], "sourceIdentifier": "security@debian.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-264"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, "type": "CWE-264"}
27
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * The MIT License\n *\n * Copyright (c) 2004-2009, Sun Microsystems, Inc., Alan Harder\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage hudson.tasks;\n", "import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;", "import com.gargoylesoftware.htmlunit.html.HtmlForm;\nimport com.gargoylesoftware.htmlunit.html.HtmlPage;", "import com.gargoylesoftware.htmlunit.html.HtmlTextInput;", "import hudson.maven.MavenModuleSet;\nimport hudson.maven.MavenModuleSetBuild;\nimport hudson.model.FreeStyleBuild;\nimport hudson.model.FreeStyleProject;", "import hudson.model.Item;", "import hudson.model.Result;\nimport hudson.model.Run;", "import hudson.security.AuthorizationMatrixProperty;\nimport hudson.security.LegacySecurityRealm;\nimport hudson.security.Permission;\nimport hudson.security.ProjectMatrixAuthorizationStrategy;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport jenkins.model.Jenkins;", "import org.jvnet.hudson.test.ExtractResourceSCM;\nimport org.jvnet.hudson.test.HudsonTestCase;\nimport org.jvnet.hudson.test.MockBuilder;", "/**\n * Tests for hudson.tasks.BuildTrigger\n * @author Alan.Harder@sun.com\n */\npublic class BuildTriggerTest extends HudsonTestCase {", " private FreeStyleProject createDownstreamProject() throws Exception {\n FreeStyleProject dp = createFreeStyleProject(\"downstream\");", " // Hm, no setQuietPeriod, have to submit form..\n WebClient webClient = new WebClient();\n HtmlPage page = webClient.getPage(dp,\"configure\");\n HtmlForm form = page.getFormByName(\"config\");\n form.getInputByName(\"hasCustomQuietPeriod\").click();\n form.getInputByName(\"quiet_period\").setValueAttribute(\"0\");\n submit(form);\n assertEquals(\"set quiet period\", 0, dp.getQuietPeriod());", " return dp;\n }", " private void doTriggerTest(boolean evenWhenUnstable, Result triggerResult,\n Result dontTriggerResult) throws Exception {\n FreeStyleProject p = createFreeStyleProject(),\n dp = createDownstreamProject();\n p.getPublishersList().add(new BuildTrigger(\"downstream\", evenWhenUnstable));\n p.getBuildersList().add(new MockBuilder(dontTriggerResult));\n jenkins.rebuildDependencyGraph();", " // First build should not trigger downstream job\n FreeStyleBuild b = p.scheduleBuild2(0).get();\n assertNoDownstreamBuild(dp, b);", " // Next build should trigger downstream job\n p.getBuildersList().replace(new MockBuilder(triggerResult));\n b = p.scheduleBuild2(0).get();\n assertDownstreamBuild(dp, b);\n }", " private void assertNoDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {\n for (int i = 0; i < 3; i++) {\n Thread.sleep(200);\n assertTrue(\"downstream build should not run! upstream log: \" + getLog(b),\n !dp.isInQueue() && !dp.isBuilding() && dp.getLastBuild()==null);\n }\n }", " private void assertDownstreamBuild(FreeStyleProject dp, Run<?,?> b) throws Exception {\n // Wait for downstream build\n for (int i = 0; dp.getLastBuild()==null && i < 20; i++) Thread.sleep(100);\n assertNotNull(\"downstream build didn't run.. upstream log: \" + getLog(b), dp.getLastBuild());\n }", " public void testBuildTrigger() throws Exception {\n doTriggerTest(false, Result.SUCCESS, Result.UNSTABLE);\n }", " public void testTriggerEvenWhenUnstable() throws Exception {\n doTriggerTest(true, Result.UNSTABLE, Result.FAILURE);\n }", " private void doMavenTriggerTest(boolean evenWhenUnstable) throws Exception {\n FreeStyleProject dp = createDownstreamProject();\n configureDefaultMaven();\n MavenModuleSet m = createMavenProject();\n m.getPublishersList().add(new BuildTrigger(\"downstream\", evenWhenUnstable));\n if (!evenWhenUnstable) {\n // Configure for UNSTABLE\n m.setGoals(\"clean test\");\n m.setScm(new ExtractResourceSCM(getClass().getResource(\"maven-test-failure.zip\")));\n } // otherwise do nothing which gets FAILURE\n // First build should not trigger downstream project\n MavenModuleSetBuild b = m.scheduleBuild2(0).get();\n assertNoDownstreamBuild(dp, b);", " if (evenWhenUnstable) {\n // Configure for UNSTABLE\n m.setGoals(\"clean test\");\n m.setScm(new ExtractResourceSCM(getClass().getResource(\"maven-test-failure.zip\")));\n } else {\n // Configure for SUCCESS\n m.setGoals(\"clean\");\n m.setScm(new ExtractResourceSCM(getClass().getResource(\"maven-empty.zip\")));\n }\n // Next build should trigger downstream project\n b = m.scheduleBuild2(0).get();\n assertDownstreamBuild(dp, b);\n }", " public void testMavenBuildTrigger() throws Exception {\n doMavenTriggerTest(false);\n }", " public void testMavenTriggerEvenWhenUnstable() throws Exception {\n doMavenTriggerTest(true);\n }", "\n public void testConfigureDownstreamProjectSecurity() throws Exception {\n jenkins.setSecurityRealm(new LegacySecurityRealm());\n ProjectMatrixAuthorizationStrategy auth = new ProjectMatrixAuthorizationStrategy();\n auth.add(Jenkins.READ, \"alice\");\n jenkins.setAuthorizationStrategy(auth);\n FreeStyleProject upstream = createFreeStyleProject(\"upstream\");\n Map<Permission,Set<String>> perms = new HashMap<Permission,Set<String>>();\n perms.put(Item.READ, Collections.singleton(\"alice\"));\n perms.put(Item.CONFIGURE, Collections.singleton(\"alice\"));\n upstream.addProperty(new AuthorizationMatrixProperty(perms));\n FreeStyleProject downstream = createFreeStyleProject(\"downstream\");\n /* Original SECURITY-55 test case:\n downstream.addProperty(new AuthorizationMatrixProperty(Collections.singletonMap(Item.READ, Collections.singleton(\"alice\"))));\n */\n WebClient wc = createWebClient();\n wc.login(\"alice\");\n HtmlPage page = wc.getPage(upstream, \"configure\");\n HtmlForm config = page.getFormByName(\"config\");\n config.getButtonByCaption(\"Add post-build action\").click(); // lib/hudson/project/config-publishers2.jelly\n page.getAnchorByText(\"Build other projects\").click();\n HtmlTextInput childProjects = config.getInputByName(\"buildTrigger.childProjects\");\n childProjects.setValueAttribute(\"downstream\");\n try {\n submit(config);\n fail();\n } catch (FailingHttpStatusCodeException x) {\n assertEquals(403, x.getStatusCode());\n }\n assertEquals(Collections.emptyList(), upstream.getDownstreamProjects());\n }\n", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1943, 133], "buggy_code_start_loc": [1942, 25], "filenames": ["core/src/main/java/hudson/model/AbstractProject.java", "test/src/test/java/hudson/tasks/BuildTriggerTest.java"], "fixing_code_end_loc": [1950, 178], "fixing_code_start_loc": [1942, 26], "message": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:lts:*:*:*", "matchCriteriaId": "F5EDE52E-F7BE-457D-8E56-F24800F02241", "versionEndExcluding": null, "versionEndIncluding": "1.532.1", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:jenkins:jenkins:*:*:*:*:*:*:*:*", "matchCriteriaId": "07E4FEB5-A7D9-49FE-839A-0D650CC19C42", "versionEndExcluding": null, "versionEndIncluding": "1.550", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "BuildTrigger in Jenkins before 1.551 and LTS before 1.532.2 allows remote authenticated users to bypass access restrictions and execute arbitrary jobs by configuring a job to trigger another job. NOTE: this vulnerability exists because of an incomplete fix for CVE-2013-7330."}, {"lang": "es", "value": "BuildTrigger en Jenkins en versiones anteriores a 1.551 y LTS en versiones anteriores a 1.532.2 permite a usuarios remotos autenticados eludir las restricciones de acceso y ejecutar trabajos arbitrarios configurando un trabajo para desencadenar otro trabajo. NOTA: esta vulnerabilidad existe debido a una soluci\u00f3n incompleta para CVE-2013-7330."}], "evaluatorComment": null, "id": "CVE-2014-2058", "lastModified": "2016-06-13T23:32:02.143", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-10-17T15:55:05.510", "references": [{"source": "security@debian.org", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2014/02/21/2"}, {"source": "security@debian.org", "tags": ["Patch"], "url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, {"source": "security@debian.org", "tags": ["Vendor Advisory"], "url": "https://wiki.jenkins-ci.org/display/SECURITY/Jenkins+Security+Advisory+2014-02-14"}], "sourceIdentifier": "security@debian.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-264"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/jenkinsci/jenkins/commit/b6b2a367a7976be80a799c6a49fa6c58d778b50e"}, "type": "CWE-264"}
27
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou 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\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_\n#define TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_", "#include <algorithm>\n#include <cstdint>\n#include <cstring>\n#include <initializer_list>", "#include \"tensorflow/lite/kernels/internal/compatibility.h\"", "namespace tflite {", "enum class FusedActivationFunctionType : uint8_t {\n kNone,\n kRelu6,\n kRelu1,\n kRelu\n};\nenum class PaddingType : uint8_t { kNone, kSame, kValid };", "struct PaddingValues {\n int16_t width;\n int16_t height;\n // offset is used for calculating \"remaining\" padding, for example, `width`\n // is 1 and `width_offset` is 1, so padding_left is 1 while padding_right is\n // 1 + 1 = 2.\n int16_t width_offset;\n // Same as width_offset except it's over the height dimension.\n int16_t height_offset;\n};", "// This enumeration allows for non-default formats for the weights array\n// of a fully-connected operator, allowing the use of special optimized\n// runtime paths.\nenum class FullyConnectedWeightsFormat : uint8_t {\n // Default format (flat 2D layout, the inner contiguous dimension\n // is input_depth, the outer non-contiguous dimension is output_depth)\n kDefault,\n // Summary: optimized layout for fast CPU runtime implementation,\n // aimed specifically at ARM CPUs at the moment, and specialized for\n // 8-bit quantized layers.\n //\n // The use case we're concerned with here is: 8-bit quantization,\n // large weights matrix that doesn't fit in cache (e.g. 4096x2048 in\n // a key application that drove this), very small batch size (e.g. 1 -- 4).\n //\n // Even with 8-bit quantization of weights, the performance of memory\n // accesses to the weights can become the dominant issue when\n // the batch size is small, so each weight value is used in only a few\n // arithmetic ops, i.e. the fully-connected node has a low arithmetic\n // intensity. The specific issues that arise are of three kinds:\n // (1) One may, ideally, max out DRAM bandwidth, i.e. be truly memory\n // bound. That's the \"good\" issue to run into.\n // (2) One may run into sub-optimal pre-fetching: the data hasn't been\n // prefetched into the cache by the time we need it.\n // (3) One may run into cache aliasing: multiple values that are\n // pre-fetched, alias each other in the L1 cache (which typically\n // has only 4-way set associativity in ARM CPUs) and thus evict\n // each other before we get to using them.\n //\n // The point of this shuffling is to avoid issues (2) and (3) so that\n // we get as fast as possible given only the hard constraint (1).\n // This is achieved by turning the difficulty into a solution: the\n // difficulty, that each value loaded from memory is used only in\n // one kernel iteration, making this operation memory-intensive, hints at\n // the solution, of shuffling the weights so that they are stored in the\n // exact order as the kernel needs to load them, so that the memory\n // accesses made by the kernel are trivial. This solves (2) because the\n // trivial memory access pattern allows the CPU's automatic prefetching\n // to perform very well (no need even for preload instructions), and this\n // solves (3) because the values being loaded concurrently are now\n // contiguous in the address space, thus don't alias each other in the cache.\n //\n // On ARM, we typically want our kernel to process a 4x16 block of weights\n // at a time, because:\n // - 16 is the number of bytes in a NEON register.\n // - 4 is how many rows we need to handle concurrently in the kernel in\n // order to have sufficient mutual independence of instructions to\n // maximize arithmetic throughput.\n //\n // Finally, the 'Int8' part in the name refers to the fact that this\n // weights format has each weights value encoded as a signed int8_t value,\n // even if the data type of the weights buffer is uint8_t. This is intended\n // to save runtime kernels the effort to have to XOR the top bit of these\n // bytes before using them in signed arithmetic, see this file for more\n // explanations on the 'signed int8_t trick' in matrix multiplication kernels:\n //\n // tensorflow/lite/toco/graph_transformations/ensure_uint8_weights_safe_for_fast_int8_kernels.cc\n //\n kShuffled4x16Int8,\n};", "// Quantization parameters, determining the mapping of quantized values\n// to real values (i.e. determining how quantized values are mathematically\n// interpreted).\n//\n// The correspondence is as follows:\n//\n// real_value = scale * (quantized_value - zero_point);\n//\n// In other words, zero_point designates which quantized value corresponds to\n// the real 0 value, and scale designates the difference between the real values\n// corresponding to consecutive quantized values differing by 1.\nstruct QuantizationParams {\n int32_t zero_point = 0;\n double scale = 0.0;\n};", "inline bool operator==(const QuantizationParams& qp1,\n const QuantizationParams& qp2) {\n return qp1.zero_point == qp2.zero_point && qp1.scale == qp2.scale;\n}", "template <int N>\nstruct Dims {\n int sizes[N];\n int strides[N];\n};", "class RuntimeShape {\n public:\n // Shapes with dimensions up to 5 are stored directly in the structure, while\n // larger shapes are separately allocated.\n static constexpr int kMaxSmallSize = 5;", " RuntimeShape& operator=(RuntimeShape const&) = delete;", " RuntimeShape() : size_(0) {}", " explicit RuntimeShape(int dimensions_count) : size_(dimensions_count) {\n if (dimensions_count > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n dims_pointer_ = new int32_t[dimensions_count];\n#endif // TF_LITE_STATIC_MEMORY\n }\n }", " RuntimeShape(int shape_size, int32_t value) : size_(0) {\n Resize(shape_size);\n for (int i = 0; i < shape_size; ++i) {\n SetDim(i, value);\n }\n }", " RuntimeShape(int dimensions_count, const int32_t* dims_data) : size_(0) {\n ReplaceWith(dimensions_count, dims_data);\n }", " RuntimeShape(const std::initializer_list<int> init_list) : size_(0) {\n BuildFrom(init_list);\n }", " // Avoid using this constructor. We should be able to delete it when C++17\n // rolls out.\n RuntimeShape(RuntimeShape const& other) : size_(other.DimensionsCount()) {\n if (size_ > kMaxSmallSize) {\n dims_pointer_ = new int32_t[size_];\n }\n std::memcpy(DimsData(), other.DimsData(), sizeof(int32_t) * size_);\n }", " bool operator==(const RuntimeShape& comp) const {\n return this->size_ == comp.size_ &&\n std::memcmp(DimsData(), comp.DimsData(), size_ * sizeof(int32_t)) ==\n 0;\n }", " ~RuntimeShape() {\n if (size_ > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n delete[] dims_pointer_;\n#endif // TF_LITE_STATIC_MEMORY\n }\n }", " inline int32_t DimensionsCount() const { return size_; }\n inline int32_t Dims(int i) const {\n TFLITE_DCHECK_GE(i, 0);\n TFLITE_DCHECK_LT(i, size_);\n return size_ > kMaxSmallSize ? dims_pointer_[i] : dims_[i];\n }\n inline void SetDim(int i, int32_t val) {\n TFLITE_DCHECK_GE(i, 0);\n TFLITE_DCHECK_LT(i, size_);\n if (size_ > kMaxSmallSize) {\n dims_pointer_[i] = val;\n } else {\n dims_[i] = val;\n }\n }", " inline int32_t* DimsData() {\n return size_ > kMaxSmallSize ? dims_pointer_ : dims_;\n }\n inline const int32_t* DimsData() const {\n return size_ > kMaxSmallSize ? dims_pointer_ : dims_;\n }\n // The caller must ensure that the shape is no bigger than 5-D.\n inline const int32_t* DimsDataUpTo5D() const { return dims_; }", " inline void Resize(int dimensions_count) {\n if (size_ > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n delete[] dims_pointer_;\n#endif // TF_LITE_STATIC_MEMORY\n }\n size_ = dimensions_count;\n if (dimensions_count > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n dims_pointer_ = new int32_t[dimensions_count];\n#endif // TF_LITE_STATIC_MEMORY\n }\n }", " inline void ReplaceWith(int dimensions_count, const int32_t* dims_data) {\n Resize(dimensions_count);\n int32_t* dst_dims = DimsData();\n std::memcpy(dst_dims, dims_data, dimensions_count * sizeof(int32_t));\n }", " template <typename T>\n inline void BuildFrom(const T& src_iterable) {\n const int dimensions_count =\n std::distance(src_iterable.begin(), src_iterable.end());\n Resize(dimensions_count);\n int32_t* data = DimsData();\n for (auto it : src_iterable) {\n *data = it;\n ++data;\n }\n }", " // This will probably be factored out. Old code made substantial use of 4-D\n // shapes, and so this function is used to extend smaller shapes. Note that\n // (a) as Dims<4>-dependent code is eliminated, the reliance on this should be\n // reduced, and (b) some kernels are stricly 4-D, but then the shapes of their\n // inputs should already be 4-D, so this function should not be needed.\n inline static RuntimeShape ExtendedShape(int new_shape_size,\n const RuntimeShape& shape) {\n return RuntimeShape(new_shape_size, shape, 1);\n }", " inline void BuildFrom(const std::initializer_list<int> init_list) {\n BuildFrom<const std::initializer_list<int>>(init_list);\n }", " // Returns the total count of elements, that is the size when flattened into a\n // vector.\n inline int FlatSize() const {\n int buffer_size = 1;\n const int* dims_data = reinterpret_cast<const int*>(DimsData());\n for (int i = 0; i < size_; i++) {\n buffer_size *= dims_data[i];\n }\n return buffer_size;\n }", " bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); }", " private:\n // For use only by ExtendedShape(), written to guarantee (return-value) copy\n // elision in C++17.\n // This creates a shape padded to the desired size with the specified value.\n RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value)\n : size_(0) {\n // If the following check fails, it is likely because a 4D-only kernel is\n // being used with an array of larger dimension count.\n TFLITE_CHECK_GE(new_shape_size, shape.DimensionsCount());\n Resize(new_shape_size);\n const int size_increase = new_shape_size - shape.DimensionsCount();\n for (int i = 0; i < size_increase; ++i) {\n SetDim(i, pad_value);\n }\n std::memcpy(DimsData() + size_increase, shape.DimsData(),\n sizeof(int32_t) * shape.DimensionsCount());\n }", " int32_t size_;\n union {\n int32_t dims_[kMaxSmallSize];\n int32_t* dims_pointer_;\n };\n};", "// Converts inference-style shape to legacy tflite::Dims<4>.\ninline tflite::Dims<4> ToRuntimeDims(const tflite::RuntimeShape& array_shape) {\n tflite::Dims<4> result;\n const int dimensions_count = array_shape.DimensionsCount();\n TFLITE_CHECK_LE(dimensions_count, 4);\n int cum_prod = 1;\n for (int i = 0; i < 4; i++) {\n const int new_dim =\n (i < dimensions_count) ? array_shape.Dims(dimensions_count - 1 - i) : 1;\n result.sizes[i] = new_dim;\n result.strides[i] = cum_prod;\n cum_prod *= new_dim;\n }\n return result;\n}", "// TODO(b/80418076): Move to legacy ops file, update invocations.\ninline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {\n return RuntimeShape(\n {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});\n}", "// Gets next index to iterate through a multidimensional array.\ninline bool NextIndex(const int num_dims, const int* dims, int* current) {\n if (num_dims == 0) {\n return false;\n }\n TFLITE_DCHECK(dims != nullptr);\n TFLITE_DCHECK(current != nullptr);\n int carry = 1;\n for (int idx = num_dims - 1; idx >= 0; --idx) {\n int current_val = current[idx] + carry;\n TFLITE_DCHECK_GE(dims[idx], current_val);\n if (dims[idx] == current_val) {\n current[idx] = 0;\n } else {\n current[idx] = current_val;\n carry = 0;\n break;\n }\n }\n return (carry == 0);\n}", "// Gets offset of index if reducing on axis. When reducing, the flattened offset\n// will not change, if the input index changes on the given axis. For example,\n// if you have a 3D tensor and you are reducing to 2D by eliminating axis 0,\n// then index (0, 1, 2) and index (1, 1, 2) will map to the same flattened\n// offset.\n// TODO(kanlig): uses Dims to represent dimensions.\ninline size_t ReducedOutputOffset(const int num_dims, const int* dims,\n const int* index, const int num_axis,\n const int* axis) {\n if (num_dims == 0) {\n return 0;\n }\n TFLITE_DCHECK(dims != nullptr);\n TFLITE_DCHECK(index != nullptr);\n size_t offset = 0;\n for (int idx = 0; idx < num_dims; ++idx) {\n // if we need to skip this axis\n bool is_axis = false;\n if (axis != nullptr) {\n for (int axis_idx = 0; axis_idx < num_axis; ++axis_idx) {\n if (idx == axis[axis_idx]) {\n is_axis = true;\n break;\n }\n }\n }\n if (!is_axis) {\n offset = offset * static_cast<size_t>(dims[idx]) +\n static_cast<size_t>(index[idx]);\n }\n }\n return offset;\n}", "inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), 4);\n const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D());\n TFLITE_DCHECK(i0 >= 0 && i0 < dims_data[0]);\n TFLITE_DCHECK(i1 >= 0 && i1 < dims_data[1]);\n TFLITE_DCHECK(i2 >= 0 && i2 < dims_data[2]);\n TFLITE_DCHECK(i3 >= 0 && i3 < dims_data[3]);\n return ((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3;\n}", "inline int Offset(const Dims<4>& dims, int i0, int i1, int i2, int i3) {\n TFLITE_DCHECK(i0 >= 0 && i0 < dims.sizes[0]);\n TFLITE_DCHECK(i1 >= 0 && i1 < dims.sizes[1]);\n TFLITE_DCHECK(i2 >= 0 && i2 < dims.sizes[2]);\n TFLITE_DCHECK(i3 >= 0 && i3 < dims.sizes[3]);\n return i0 * dims.strides[0] + i1 * dims.strides[1] + i2 * dims.strides[2] +\n i3 * dims.strides[3];\n}", "inline int Offset(const Dims<4>& dims, int* index) {\n return Offset(dims, index[0], index[1], index[2], index[3]);\n}", "inline int Offset(const RuntimeShape& shape, int* index) {\n return Offset(shape, index[0], index[1], index[2], index[3]);\n}", "// Get array size, DCHECKing that the dim index is in range.\n//\n// Note that this will be phased out with Dims<4>, since RuntimeShape::Dims()\n// already performs this check.\ntemplate <int N>\nint ArraySize(const Dims<N>& array, int index) {\n TFLITE_DCHECK(index >= 0 && index < N);\n return array.sizes[index];\n}", "// Get common array size, DCHECKing that they all agree.\ntemplate <typename ArrayType1, typename ArrayType2>\nint MatchingArraySize(const ArrayType1& array1, int index1,\n const ArrayType2& array2, int index2) {\n TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2));\n return ArraySize(array1, index1);\n}", "template <typename ArrayType1, typename ArrayType2, typename... Args>\nint MatchingArraySize(const ArrayType1& array1, int index1,\n const ArrayType2& array2, int index2, Args... args) {\n TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2));\n return MatchingArraySize(array1, index1, args...);\n}", "// Get common shape dim, DCHECKing that they all agree.\ninline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));", " return shape1.Dims(index1);", "}", "template <typename... Args>\nint MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2, Args... args) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return MatchingDim(shape1, index1, args...);\n}", "// Will be phased out with Dims<4>, replaced by RuntimeShape::FlatSize().\ntemplate <int N>\ninline int FlatSize(const Dims<N>& dims) {\n int flat_size = 1;\n for (int i = 0; i < N; ++i) {\n flat_size *= dims.sizes[i];\n }\n return flat_size;\n}", "TFLITE_DEPRECATED(\"Prefer FlatSize.\")\ninline int RequiredBufferSizeForDims(const Dims<4>& dims) {\n return FlatSize(dims);\n}", "inline int MatchingElementsSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0) {\n const int size_1 = shape.FlatSize();\n const int size_2 = check_shape_0.FlatSize();\n TFLITE_CHECK_EQ(size_1, size_2);\n return size_1;\n}", "inline int MatchingElementsSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1) {\n const int size_1 = shape.FlatSize();\n const int size_2 = check_shape_0.FlatSize();\n const int size_3 = check_shape_1.FlatSize();\n TFLITE_CHECK_EQ(size_1, size_2);\n TFLITE_CHECK_EQ(size_2, size_3);\n return size_1;\n}", "// Flat size calculation, checking that dimensions match with one or more other\n// arrays.\ninline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return shape.FlatSize();\n}", "inline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return MatchingFlatSize(shape, check_shape_1);\n}", "inline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return MatchingFlatSize(shape, check_shape_1, check_shape_2);\n}", "inline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2,\n const RuntimeShape& check_shape_3) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return MatchingFlatSize(shape, check_shape_1, check_shape_2, check_shape_3);\n}", "// Flat size calculation, checking that dimensions match with one or more other\n// arrays.\ntemplate <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return FlatSize(dims);\n}", "template <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return MatchingFlatSize(dims, check_dims_1);\n}", "template <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return MatchingFlatSize(dims, check_dims_1, check_dims_2);\n}", "template <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2,\n const Dims<N>& check_dims_3) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return MatchingFlatSize(dims, check_dims_1, check_dims_2, check_dims_3);\n}", "// Data is required to be contiguous, and so many operators can use either the\n// full array flat size or the flat size with one dimension skipped (commonly\n// the depth).\ntemplate <int N>\ninline int FlatSizeSkipDim(const Dims<N>& dims, int skip_dim) {\n TFLITE_DCHECK(skip_dim >= 0 && skip_dim < N);\n int flat_size = 1;\n for (int i = 0; i < N; ++i) {\n flat_size *= (i == skip_dim) ? 1 : dims.sizes[i];\n }\n return flat_size;\n}", "// A combination of MatchingFlatSize() and FlatSizeSkipDim().\ntemplate <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return FlatSizeSkipDim(dims, skip_dim);\n}", "template <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1);\n}", "template <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2);\n}", "template <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2,\n const Dims<N>& check_dims_3) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2,\n check_dims_3);\n}", "// Data is required to be contiguous, and so many operators can use either the\n// full array flat size or the flat size with one dimension skipped (commonly\n// the depth).\ninline int FlatSizeSkipDim(const RuntimeShape& shape, int skip_dim) {\n const int dims_count = shape.DimensionsCount();\n TFLITE_DCHECK(skip_dim >= 0 && skip_dim < dims_count);\n const auto* dims_data = shape.DimsData();\n int flat_size = 1;\n for (int i = 0; i < dims_count; ++i) {\n flat_size *= (i == skip_dim) ? 1 : dims_data[i];\n }\n return flat_size;\n}", "// A combination of MatchingFlatSize() and FlatSizeSkipDim().\ninline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return FlatSizeSkipDim(shape, skip_dim);\n}", "inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1);\n}", "inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2);\n}", "inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2,\n const RuntimeShape& check_shape_3) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2,\n check_shape_3);\n}", "template <int N>\nbool IsPackedWithoutStrides(const Dims<N>& dims) {\n int expected_stride = 1;\n for (int d = 0; d < N; d++) {\n if (dims.strides[d] != expected_stride) return false;\n expected_stride *= dims.sizes[d];\n }\n return true;\n}", "template <int N>\nvoid ComputeStrides(Dims<N>* dims) {\n dims->strides[0] = 1;\n for (int d = 1; d < N; d++) {\n dims->strides[d] = dims->strides[d - 1] * dims->sizes[d - 1];\n }\n}", "enum class BroadcastableOpCategory : uint8_t {\n kNone,\n kNonBroadcast, // Matching input shapes.\n kFirstInputBroadcastsFast, // Fivefold nested loops.\n kSecondInputBroadcastsFast, // Fivefold nested loops.\n kGenericBroadcast, // Fall-back.\n};", "struct MinMax {\n float min;\n float max;\n};\nstatic_assert(sizeof(MinMax) == 8, \"\");", "struct ActivationParams {\n FusedActivationFunctionType activation_type;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n};", "struct ReluParams : public ActivationParams {\n int32_t input_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n};", "// Styles of resizing op usages. For example, kImageStyle can be used with a Pad\n// op for pattern-specific optimization.\nenum class ResizingCategory : uint8_t {\n kNone,\n kImageStyle, // 4D, operating on inner dimensions, say {0, a, b, 0}.\n kGenericResize,\n};", "// For Add, Sub, Mul ops.\nstruct ArithmeticParams {\n // Shape dependent / common to data / op types.\n BroadcastableOpCategory broadcast_category;\n // uint8_t inference params.\n int32_t input1_offset;\n int32_t input2_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // Add / Sub, not Mul, uint8_t inference params.\n int left_shift;\n int32_t input1_multiplier;\n int input1_shift;\n int32_t input2_multiplier;\n int input2_shift;", " // TODO(b/158622529): Union the following activation params.\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n // int64_t activation params.\n int64_t int64_activation_min;\n int64_t int64_activation_max;", " // Processed output dimensions.\n // Let input \"a\" be the one that broadcasts in the faster-changing dimension.\n // Then, after coalescing, for shapes {a0, a1, a2, a3, a4} and\n // {b0, b1, b2, b3, b4},\n // broadcast_shape[4] = b0 = a0.\n // broadcast_shape[3] = b1; a1 = 1.\n // broadcast_shape[2] = b2 = a2.\n // broadcast_shape[1] = a3; b3 = 1.\n // broadcast_shape[0] = b4 = a4.\n int broadcast_shape[5];\n};", "struct ConcatenationParams {\n int8_t axis;\n const int32_t* input_zeropoint;\n const float* input_scale;\n uint16_t inputs_count;\n int32_t output_zeropoint;\n float output_scale;\n};", "struct ComparisonParams {\n // uint8_t inference params.\n int left_shift;\n int32_t input1_offset;\n int32_t input1_multiplier;\n int input1_shift;\n int32_t input2_offset;\n int32_t input2_multiplier;\n int input2_shift;\n // Shape dependent / common to inference types.\n bool is_broadcast;\n};", "struct ConvParams {\n PaddingType padding_type;\n PaddingValues padding_values;\n // TODO(starka): This was just \"stride\", so check that width+height is OK.\n int16_t stride_width;\n int16_t stride_height;\n int16_t dilation_width_factor;\n int16_t dilation_height_factor;\n // uint8_t inference params.\n // TODO(b/65838351): Use smaller types if appropriate.\n int32_t input_offset;\n int32_t weights_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n};", "struct DepthToSpaceParams {\n int32_t block_size;\n};", "struct DepthwiseParams {\n PaddingType padding_type;\n PaddingValues padding_values;\n int16_t stride_width;\n int16_t stride_height;\n int16_t dilation_width_factor;\n int16_t dilation_height_factor;\n int16_t depth_multiplier;\n // uint8_t inference params.\n // TODO(b/65838351): Use smaller types if appropriate.\n int32_t input_offset;\n int32_t weights_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n const int32_t* output_multiplier_per_channel;\n const int32_t* output_shift_per_channel;\n};", "struct DequantizationParams {\n double scale;\n int32_t zero_point;\n};", "struct PerChannelDequantizationParams {\n const float* scale;\n const int32_t* zero_point;\n int32_t quantized_dimension;\n};", "struct FakeQuantParams {\n MinMax minmax;\n int32_t num_bits;\n};", "struct FullyConnectedParams {\n // uint8_t inference params.\n // TODO(b/65838351): Use smaller types if appropriate.\n int32_t input_offset;\n int32_t weights_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n // Mark the operands as cacheable if they are unchanging, e.g. weights.\n bool lhs_cacheable;\n bool rhs_cacheable;\n FullyConnectedWeightsFormat weights_format;\n};", "struct GatherParams {\n int16_t axis;\n};", "struct L2NormalizationParams {\n // uint8_t inference params.\n int32_t input_zero_point;\n};", "struct LocalResponseNormalizationParams {\n int32_t range;\n double bias;\n double alpha;\n double beta;\n};", "struct HardSwishParams {\n // zero_point of the input activations.\n int16_t input_zero_point;\n // zero_point of the output activations.\n int16_t output_zero_point;\n // 16bit fixed-point component of the multiplier to apply to go from the\n // \"high-res input scale\", which is the input scale multiplied by 2^7, to the\n // \"relu-ish scale\", which 3.0/32768.\n // See the implementation of HardSwishPrepare.\n int16_t reluish_multiplier_fixedpoint_int16;\n // exponent/bit-shift component of the aforementioned multiplier.\n int reluish_multiplier_exponent;\n // 16bit fixed-point component of the multiplier to apply to go from the\n // \"high-res input scale\", which is the input scale multiplied by 2^7, to the\n // output scale.\n // See the implementation of HardSwishPrepare.\n int16_t output_multiplier_fixedpoint_int16;\n // exponent/bit-shift component of the aforementioned multiplier.\n int output_multiplier_exponent;\n};", "struct LogisticParams {\n // uint8_t inference params.\n int32_t input_zero_point;\n int32_t input_range_radius;\n int32_t input_multiplier;\n int input_left_shift;\n};", "struct LstmCellParams {\n int32_t weights_zero_point;\n int32_t accum_multiplier;\n int accum_shift;\n int state_integer_bits;\n};", "struct MeanParams {\n int8_t axis_count;\n int16_t axis[4];\n};", "struct PackParams {\n int8_t axis;\n const int32_t* input_zeropoint;\n const float* input_scale;\n uint16_t inputs_count;\n int32_t output_zeropoint;\n float output_scale;\n};", "struct PadParams {\n int8_t left_padding_count;\n int32_t left_padding[4];\n int8_t right_padding_count;\n int32_t right_padding[4];\n ResizingCategory resizing_category;\n};", "struct PreluParams {\n int32_t input_offset;\n int32_t alpha_offset;\n int32_t output_offset;\n int32_t output_multiplier_1;\n int output_shift_1;\n int32_t output_multiplier_2;\n int output_shift_2;\n};", "struct PoolParams {\n FusedActivationFunctionType activation;\n PaddingType padding_type;\n PaddingValues padding_values;\n int stride_height;\n int stride_width;\n int filter_height;\n int filter_width;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n};", "struct ReshapeParams {\n int8_t shape_count;\n int32_t shape[4];\n};", "struct ResizeBilinearParams {\n bool align_corners;\n // half_pixel_centers assumes pixels are of half the actual dimensions, and\n // yields more accurate resizes. Corresponds to the same argument for the\n // original TensorFlow op in TF2.0.\n bool half_pixel_centers;\n};", "struct ResizeNearestNeighborParams {\n bool align_corners;\n bool half_pixel_centers;\n};", "struct SliceParams {\n int8_t begin_count;\n int32_t begin[4];\n int8_t size_count;\n int32_t size[4];\n};", "struct SoftmaxParams {\n // beta is not really used (not a Tensorflow parameter) and not implemented\n // for LogSoftmax.\n double beta;\n // uint8_t inference params. Used even when beta defaults to 1.0.\n int32_t input_multiplier;\n int32_t input_left_shift;\n // Reverse scaling is only used by LogSoftmax.\n int32_t reverse_scaling_divisor;\n int32_t reverse_scaling_right_shift;\n int diff_min;\n int32_t zero_point;\n float scale;\n float* table;\n int16_t* exp_lut;\n int16_t* one_over_one_plus_x_lut;\n uint8_t* uint8_table1;\n uint8_t* uint8_table2;\n};", "struct SpaceToBatchParams {\n // \"Zero\" padding for uint8_t means padding with the output offset.\n int32_t output_offset;\n};", "struct SpaceToDepthParams {\n int32_t block_size;\n};", "struct SplitParams {\n // Graphs that split into, say, 2000 nodes are encountered. The indices in\n // OperatorEdges are of type uint16_t.\n uint16_t num_split;\n int16_t axis;\n};", "struct SqueezeParams {\n int8_t squeeze_dims_count;\n int32_t squeeze_dims[4];\n};", "struct StridedSliceParams {\n int8_t start_indices_count;\n int32_t start_indices[5];\n int8_t stop_indices_count;\n int32_t stop_indices[5];\n int8_t strides_count;\n int32_t strides[5];", " int16_t begin_mask;\n int16_t ellipsis_mask;\n int16_t end_mask;\n int16_t new_axis_mask;\n int16_t shrink_axis_mask;\n};", "struct TanhParams {\n int32_t input_zero_point;\n int32_t input_range_radius;\n int32_t input_multiplier;\n int input_left_shift;\n};", "struct TransposeParams {\n int8_t perm_count;\n int32_t perm[5];\n};", "struct UnpackParams {\n uint16_t num_split;\n int16_t axis;\n};", "struct LeakyReluParams {\n float alpha;\n int32_t input_offset;\n int32_t output_offset;\n int32_t output_multiplier_alpha;\n int32_t output_shift_alpha;\n int32_t output_multiplier_identity;\n int32_t output_shift_identity;\n};", "template <typename P>\ninline void SetActivationParams(float min, float max, P* params) {\n params->float_activation_min = min;\n params->float_activation_max = max;\n}", "template <typename P>\ninline void SetActivationParams(int32_t min, int32_t max, P* params) {\n params->quantized_activation_min = min;\n params->quantized_activation_max = max;\n}", "template <typename P>\ninline void SetActivationParams(int64_t min, int64_t max, P* params) {\n params->int64_activation_min = min;\n params->int64_activation_max = max;\n}", "template <typename P>\ninline void GetActivationParams(const P& params, int32_t* min, int32_t* max) {\n *min = params.quantized_activation_min;\n *max = params.quantized_activation_max;\n}", "template <typename P>\ninline void GetActivationParams(const P& params, float* min, float* max) {\n *min = params.float_activation_min;\n *max = params.float_activation_max;\n}", "template <typename P>\ninline void GetActivationParams(const P& params, int64_t* min, int64_t* max) {\n *min = params.int64_activation_min;\n *max = params.int64_activation_max;\n}\n} // namespace tflite", "#endif // TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [442], "buggy_code_start_loc": [441], "filenames": ["tensorflow/lite/kernels/internal/types.h"], "fixing_code_end_loc": [442], "fixing_code_start_loc": [441], "message": "In tensorflow-lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, when determining the common dimension size of two tensors, TFLite uses a `DCHECK` which is no-op outside of debug compilation modes. Since the function always returns the dimension of the first tensor, malicious attackers can craft cases where this is larger than that of the second tensor. In turn, this would result in reads/writes outside of bounds since the interpreter will wrongly assume that there is enough data in both tensors. The issue is patched in commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "7A5421A9-693F-472A-9A21-43950C884C77", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "B0FEB74E-5E54-4A2F-910C-FA1812C73DB2", "versionEndExcluding": "2.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "47D83682-6615-49BC-8043-F36B9D017578", "versionEndExcluding": "2.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "323B716A-E8F7-4CDA-B8FD-A56977D59C02", "versionEndExcluding": "2.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "C09502A8-B667-4867-BEBD-40333E98A601", "versionEndExcluding": "2.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.2:*:*:*:*:*:*:*", "matchCriteriaId": "B009C22E-30A4-4288-BCF6-C3E81DEAF45A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In tensorflow-lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, when determining the common dimension size of two tensors, TFLite uses a `DCHECK` which is no-op outside of debug compilation modes. Since the function always returns the dimension of the first tensor, malicious attackers can craft cases where this is larger than that of the second tensor. In turn, this would result in reads/writes outside of bounds since the interpreter will wrongly assume that there is enough data in both tensors. The issue is patched in commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1."}, {"lang": "es", "value": "En tensorflow-lite versiones anteriores a 1.15.4, 2.0.3, 2.1.2, 2.2.1 y 2.3.1, al determinar el tama\u00f1o de dimensi\u00f3n com\u00fan de dos tensores, TFLite usa un \"DCHECK\" que no es operativo fuera de los modos de compilaci\u00f3n de depuraci\u00f3n.&#xa0;Dado que la funci\u00f3n siempre devuelve la dimensi\u00f3n del primer tensor, los atacantes maliciosos pueden crear casos en los que este sea mayor que el del segundo tensor.&#xa0;A su vez, esto resultar\u00eda en lecturas y escrituras fuera de l\u00edmites, ya que el int\u00e9rprete asumir\u00e1 incorrectamente que existen suficientes datos en ambos tensores.&#xa0;El problema es parcheado en el commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, y es publicado en TensorFlow versiones 1.15.4, 2.0.3, 2.1.2, 2.2.1 o 2.3.1"}], "evaluatorComment": null, "id": "CVE-2020-15208", "lastModified": "2021-09-16T15:45:33.860", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-09-25T19:15:16.103", "references": [{"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-10/msg00065.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/8ee24e7949a203d234489f9da2c5bf45a7d5157d"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/releases/tag/v2.3.1"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-mxjj-953w-2c2v"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}, {"lang": "en", "value": "CWE-787"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/8ee24e7949a203d234489f9da2c5bf45a7d5157d"}, "type": "CWE-125"}
28
Determine whether the {function_name} code is vulnerable or not.
[ "/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.", "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou 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\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_\n#define TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_", "#include <algorithm>\n#include <cstdint>\n#include <cstring>\n#include <initializer_list>", "#include \"tensorflow/lite/kernels/internal/compatibility.h\"", "namespace tflite {", "enum class FusedActivationFunctionType : uint8_t {\n kNone,\n kRelu6,\n kRelu1,\n kRelu\n};\nenum class PaddingType : uint8_t { kNone, kSame, kValid };", "struct PaddingValues {\n int16_t width;\n int16_t height;\n // offset is used for calculating \"remaining\" padding, for example, `width`\n // is 1 and `width_offset` is 1, so padding_left is 1 while padding_right is\n // 1 + 1 = 2.\n int16_t width_offset;\n // Same as width_offset except it's over the height dimension.\n int16_t height_offset;\n};", "// This enumeration allows for non-default formats for the weights array\n// of a fully-connected operator, allowing the use of special optimized\n// runtime paths.\nenum class FullyConnectedWeightsFormat : uint8_t {\n // Default format (flat 2D layout, the inner contiguous dimension\n // is input_depth, the outer non-contiguous dimension is output_depth)\n kDefault,\n // Summary: optimized layout for fast CPU runtime implementation,\n // aimed specifically at ARM CPUs at the moment, and specialized for\n // 8-bit quantized layers.\n //\n // The use case we're concerned with here is: 8-bit quantization,\n // large weights matrix that doesn't fit in cache (e.g. 4096x2048 in\n // a key application that drove this), very small batch size (e.g. 1 -- 4).\n //\n // Even with 8-bit quantization of weights, the performance of memory\n // accesses to the weights can become the dominant issue when\n // the batch size is small, so each weight value is used in only a few\n // arithmetic ops, i.e. the fully-connected node has a low arithmetic\n // intensity. The specific issues that arise are of three kinds:\n // (1) One may, ideally, max out DRAM bandwidth, i.e. be truly memory\n // bound. That's the \"good\" issue to run into.\n // (2) One may run into sub-optimal pre-fetching: the data hasn't been\n // prefetched into the cache by the time we need it.\n // (3) One may run into cache aliasing: multiple values that are\n // pre-fetched, alias each other in the L1 cache (which typically\n // has only 4-way set associativity in ARM CPUs) and thus evict\n // each other before we get to using them.\n //\n // The point of this shuffling is to avoid issues (2) and (3) so that\n // we get as fast as possible given only the hard constraint (1).\n // This is achieved by turning the difficulty into a solution: the\n // difficulty, that each value loaded from memory is used only in\n // one kernel iteration, making this operation memory-intensive, hints at\n // the solution, of shuffling the weights so that they are stored in the\n // exact order as the kernel needs to load them, so that the memory\n // accesses made by the kernel are trivial. This solves (2) because the\n // trivial memory access pattern allows the CPU's automatic prefetching\n // to perform very well (no need even for preload instructions), and this\n // solves (3) because the values being loaded concurrently are now\n // contiguous in the address space, thus don't alias each other in the cache.\n //\n // On ARM, we typically want our kernel to process a 4x16 block of weights\n // at a time, because:\n // - 16 is the number of bytes in a NEON register.\n // - 4 is how many rows we need to handle concurrently in the kernel in\n // order to have sufficient mutual independence of instructions to\n // maximize arithmetic throughput.\n //\n // Finally, the 'Int8' part in the name refers to the fact that this\n // weights format has each weights value encoded as a signed int8_t value,\n // even if the data type of the weights buffer is uint8_t. This is intended\n // to save runtime kernels the effort to have to XOR the top bit of these\n // bytes before using them in signed arithmetic, see this file for more\n // explanations on the 'signed int8_t trick' in matrix multiplication kernels:\n //\n // tensorflow/lite/toco/graph_transformations/ensure_uint8_weights_safe_for_fast_int8_kernels.cc\n //\n kShuffled4x16Int8,\n};", "// Quantization parameters, determining the mapping of quantized values\n// to real values (i.e. determining how quantized values are mathematically\n// interpreted).\n//\n// The correspondence is as follows:\n//\n// real_value = scale * (quantized_value - zero_point);\n//\n// In other words, zero_point designates which quantized value corresponds to\n// the real 0 value, and scale designates the difference between the real values\n// corresponding to consecutive quantized values differing by 1.\nstruct QuantizationParams {\n int32_t zero_point = 0;\n double scale = 0.0;\n};", "inline bool operator==(const QuantizationParams& qp1,\n const QuantizationParams& qp2) {\n return qp1.zero_point == qp2.zero_point && qp1.scale == qp2.scale;\n}", "template <int N>\nstruct Dims {\n int sizes[N];\n int strides[N];\n};", "class RuntimeShape {\n public:\n // Shapes with dimensions up to 5 are stored directly in the structure, while\n // larger shapes are separately allocated.\n static constexpr int kMaxSmallSize = 5;", " RuntimeShape& operator=(RuntimeShape const&) = delete;", " RuntimeShape() : size_(0) {}", " explicit RuntimeShape(int dimensions_count) : size_(dimensions_count) {\n if (dimensions_count > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n dims_pointer_ = new int32_t[dimensions_count];\n#endif // TF_LITE_STATIC_MEMORY\n }\n }", " RuntimeShape(int shape_size, int32_t value) : size_(0) {\n Resize(shape_size);\n for (int i = 0; i < shape_size; ++i) {\n SetDim(i, value);\n }\n }", " RuntimeShape(int dimensions_count, const int32_t* dims_data) : size_(0) {\n ReplaceWith(dimensions_count, dims_data);\n }", " RuntimeShape(const std::initializer_list<int> init_list) : size_(0) {\n BuildFrom(init_list);\n }", " // Avoid using this constructor. We should be able to delete it when C++17\n // rolls out.\n RuntimeShape(RuntimeShape const& other) : size_(other.DimensionsCount()) {\n if (size_ > kMaxSmallSize) {\n dims_pointer_ = new int32_t[size_];\n }\n std::memcpy(DimsData(), other.DimsData(), sizeof(int32_t) * size_);\n }", " bool operator==(const RuntimeShape& comp) const {\n return this->size_ == comp.size_ &&\n std::memcmp(DimsData(), comp.DimsData(), size_ * sizeof(int32_t)) ==\n 0;\n }", " ~RuntimeShape() {\n if (size_ > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n delete[] dims_pointer_;\n#endif // TF_LITE_STATIC_MEMORY\n }\n }", " inline int32_t DimensionsCount() const { return size_; }\n inline int32_t Dims(int i) const {\n TFLITE_DCHECK_GE(i, 0);\n TFLITE_DCHECK_LT(i, size_);\n return size_ > kMaxSmallSize ? dims_pointer_[i] : dims_[i];\n }\n inline void SetDim(int i, int32_t val) {\n TFLITE_DCHECK_GE(i, 0);\n TFLITE_DCHECK_LT(i, size_);\n if (size_ > kMaxSmallSize) {\n dims_pointer_[i] = val;\n } else {\n dims_[i] = val;\n }\n }", " inline int32_t* DimsData() {\n return size_ > kMaxSmallSize ? dims_pointer_ : dims_;\n }\n inline const int32_t* DimsData() const {\n return size_ > kMaxSmallSize ? dims_pointer_ : dims_;\n }\n // The caller must ensure that the shape is no bigger than 5-D.\n inline const int32_t* DimsDataUpTo5D() const { return dims_; }", " inline void Resize(int dimensions_count) {\n if (size_ > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n delete[] dims_pointer_;\n#endif // TF_LITE_STATIC_MEMORY\n }\n size_ = dimensions_count;\n if (dimensions_count > kMaxSmallSize) {\n#ifdef TF_LITE_STATIC_MEMORY\n TFLITE_CHECK(false && \"No shape resizing supported on this platform\");\n#else // TF_LITE_STATIC_MEMORY\n dims_pointer_ = new int32_t[dimensions_count];\n#endif // TF_LITE_STATIC_MEMORY\n }\n }", " inline void ReplaceWith(int dimensions_count, const int32_t* dims_data) {\n Resize(dimensions_count);\n int32_t* dst_dims = DimsData();\n std::memcpy(dst_dims, dims_data, dimensions_count * sizeof(int32_t));\n }", " template <typename T>\n inline void BuildFrom(const T& src_iterable) {\n const int dimensions_count =\n std::distance(src_iterable.begin(), src_iterable.end());\n Resize(dimensions_count);\n int32_t* data = DimsData();\n for (auto it : src_iterable) {\n *data = it;\n ++data;\n }\n }", " // This will probably be factored out. Old code made substantial use of 4-D\n // shapes, and so this function is used to extend smaller shapes. Note that\n // (a) as Dims<4>-dependent code is eliminated, the reliance on this should be\n // reduced, and (b) some kernels are stricly 4-D, but then the shapes of their\n // inputs should already be 4-D, so this function should not be needed.\n inline static RuntimeShape ExtendedShape(int new_shape_size,\n const RuntimeShape& shape) {\n return RuntimeShape(new_shape_size, shape, 1);\n }", " inline void BuildFrom(const std::initializer_list<int> init_list) {\n BuildFrom<const std::initializer_list<int>>(init_list);\n }", " // Returns the total count of elements, that is the size when flattened into a\n // vector.\n inline int FlatSize() const {\n int buffer_size = 1;\n const int* dims_data = reinterpret_cast<const int*>(DimsData());\n for (int i = 0; i < size_; i++) {\n buffer_size *= dims_data[i];\n }\n return buffer_size;\n }", " bool operator!=(const RuntimeShape& comp) const { return !((*this) == comp); }", " private:\n // For use only by ExtendedShape(), written to guarantee (return-value) copy\n // elision in C++17.\n // This creates a shape padded to the desired size with the specified value.\n RuntimeShape(int new_shape_size, const RuntimeShape& shape, int pad_value)\n : size_(0) {\n // If the following check fails, it is likely because a 4D-only kernel is\n // being used with an array of larger dimension count.\n TFLITE_CHECK_GE(new_shape_size, shape.DimensionsCount());\n Resize(new_shape_size);\n const int size_increase = new_shape_size - shape.DimensionsCount();\n for (int i = 0; i < size_increase; ++i) {\n SetDim(i, pad_value);\n }\n std::memcpy(DimsData() + size_increase, shape.DimsData(),\n sizeof(int32_t) * shape.DimensionsCount());\n }", " int32_t size_;\n union {\n int32_t dims_[kMaxSmallSize];\n int32_t* dims_pointer_;\n };\n};", "// Converts inference-style shape to legacy tflite::Dims<4>.\ninline tflite::Dims<4> ToRuntimeDims(const tflite::RuntimeShape& array_shape) {\n tflite::Dims<4> result;\n const int dimensions_count = array_shape.DimensionsCount();\n TFLITE_CHECK_LE(dimensions_count, 4);\n int cum_prod = 1;\n for (int i = 0; i < 4; i++) {\n const int new_dim =\n (i < dimensions_count) ? array_shape.Dims(dimensions_count - 1 - i) : 1;\n result.sizes[i] = new_dim;\n result.strides[i] = cum_prod;\n cum_prod *= new_dim;\n }\n return result;\n}", "// TODO(b/80418076): Move to legacy ops file, update invocations.\ninline RuntimeShape DimsToShape(const tflite::Dims<4>& dims) {\n return RuntimeShape(\n {dims.sizes[3], dims.sizes[2], dims.sizes[1], dims.sizes[0]});\n}", "// Gets next index to iterate through a multidimensional array.\ninline bool NextIndex(const int num_dims, const int* dims, int* current) {\n if (num_dims == 0) {\n return false;\n }\n TFLITE_DCHECK(dims != nullptr);\n TFLITE_DCHECK(current != nullptr);\n int carry = 1;\n for (int idx = num_dims - 1; idx >= 0; --idx) {\n int current_val = current[idx] + carry;\n TFLITE_DCHECK_GE(dims[idx], current_val);\n if (dims[idx] == current_val) {\n current[idx] = 0;\n } else {\n current[idx] = current_val;\n carry = 0;\n break;\n }\n }\n return (carry == 0);\n}", "// Gets offset of index if reducing on axis. When reducing, the flattened offset\n// will not change, if the input index changes on the given axis. For example,\n// if you have a 3D tensor and you are reducing to 2D by eliminating axis 0,\n// then index (0, 1, 2) and index (1, 1, 2) will map to the same flattened\n// offset.\n// TODO(kanlig): uses Dims to represent dimensions.\ninline size_t ReducedOutputOffset(const int num_dims, const int* dims,\n const int* index, const int num_axis,\n const int* axis) {\n if (num_dims == 0) {\n return 0;\n }\n TFLITE_DCHECK(dims != nullptr);\n TFLITE_DCHECK(index != nullptr);\n size_t offset = 0;\n for (int idx = 0; idx < num_dims; ++idx) {\n // if we need to skip this axis\n bool is_axis = false;\n if (axis != nullptr) {\n for (int axis_idx = 0; axis_idx < num_axis; ++axis_idx) {\n if (idx == axis[axis_idx]) {\n is_axis = true;\n break;\n }\n }\n }\n if (!is_axis) {\n offset = offset * static_cast<size_t>(dims[idx]) +\n static_cast<size_t>(index[idx]);\n }\n }\n return offset;\n}", "inline int Offset(const RuntimeShape& shape, int i0, int i1, int i2, int i3) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), 4);\n const int* dims_data = reinterpret_cast<const int*>(shape.DimsDataUpTo5D());\n TFLITE_DCHECK(i0 >= 0 && i0 < dims_data[0]);\n TFLITE_DCHECK(i1 >= 0 && i1 < dims_data[1]);\n TFLITE_DCHECK(i2 >= 0 && i2 < dims_data[2]);\n TFLITE_DCHECK(i3 >= 0 && i3 < dims_data[3]);\n return ((i0 * dims_data[1] + i1) * dims_data[2] + i2) * dims_data[3] + i3;\n}", "inline int Offset(const Dims<4>& dims, int i0, int i1, int i2, int i3) {\n TFLITE_DCHECK(i0 >= 0 && i0 < dims.sizes[0]);\n TFLITE_DCHECK(i1 >= 0 && i1 < dims.sizes[1]);\n TFLITE_DCHECK(i2 >= 0 && i2 < dims.sizes[2]);\n TFLITE_DCHECK(i3 >= 0 && i3 < dims.sizes[3]);\n return i0 * dims.strides[0] + i1 * dims.strides[1] + i2 * dims.strides[2] +\n i3 * dims.strides[3];\n}", "inline int Offset(const Dims<4>& dims, int* index) {\n return Offset(dims, index[0], index[1], index[2], index[3]);\n}", "inline int Offset(const RuntimeShape& shape, int* index) {\n return Offset(shape, index[0], index[1], index[2], index[3]);\n}", "// Get array size, DCHECKing that the dim index is in range.\n//\n// Note that this will be phased out with Dims<4>, since RuntimeShape::Dims()\n// already performs this check.\ntemplate <int N>\nint ArraySize(const Dims<N>& array, int index) {\n TFLITE_DCHECK(index >= 0 && index < N);\n return array.sizes[index];\n}", "// Get common array size, DCHECKing that they all agree.\ntemplate <typename ArrayType1, typename ArrayType2>\nint MatchingArraySize(const ArrayType1& array1, int index1,\n const ArrayType2& array2, int index2) {\n TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2));\n return ArraySize(array1, index1);\n}", "template <typename ArrayType1, typename ArrayType2, typename... Args>\nint MatchingArraySize(const ArrayType1& array1, int index1,\n const ArrayType2& array2, int index2, Args... args) {\n TFLITE_DCHECK_EQ(ArraySize(array1, index1), ArraySize(array2, index2));\n return MatchingArraySize(array1, index1, args...);\n}", "// Get common shape dim, DCHECKing that they all agree.\ninline int MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));", " return std::min(shape1.Dims(index1), shape2.Dims(index2));", "}", "template <typename... Args>\nint MatchingDim(const RuntimeShape& shape1, int index1,\n const RuntimeShape& shape2, int index2, Args... args) {\n TFLITE_DCHECK_EQ(shape1.Dims(index1), shape2.Dims(index2));\n return MatchingDim(shape1, index1, args...);\n}", "// Will be phased out with Dims<4>, replaced by RuntimeShape::FlatSize().\ntemplate <int N>\ninline int FlatSize(const Dims<N>& dims) {\n int flat_size = 1;\n for (int i = 0; i < N; ++i) {\n flat_size *= dims.sizes[i];\n }\n return flat_size;\n}", "TFLITE_DEPRECATED(\"Prefer FlatSize.\")\ninline int RequiredBufferSizeForDims(const Dims<4>& dims) {\n return FlatSize(dims);\n}", "inline int MatchingElementsSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0) {\n const int size_1 = shape.FlatSize();\n const int size_2 = check_shape_0.FlatSize();\n TFLITE_CHECK_EQ(size_1, size_2);\n return size_1;\n}", "inline int MatchingElementsSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1) {\n const int size_1 = shape.FlatSize();\n const int size_2 = check_shape_0.FlatSize();\n const int size_3 = check_shape_1.FlatSize();\n TFLITE_CHECK_EQ(size_1, size_2);\n TFLITE_CHECK_EQ(size_2, size_3);\n return size_1;\n}", "// Flat size calculation, checking that dimensions match with one or more other\n// arrays.\ninline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return shape.FlatSize();\n}", "inline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return MatchingFlatSize(shape, check_shape_1);\n}", "inline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return MatchingFlatSize(shape, check_shape_1, check_shape_2);\n}", "inline int MatchingFlatSize(const RuntimeShape& shape,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2,\n const RuntimeShape& check_shape_3) {\n TFLITE_DCHECK_EQ(shape.DimensionsCount(), check_shape_0.DimensionsCount());\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n return MatchingFlatSize(shape, check_shape_1, check_shape_2, check_shape_3);\n}", "// Flat size calculation, checking that dimensions match with one or more other\n// arrays.\ntemplate <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return FlatSize(dims);\n}", "template <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return MatchingFlatSize(dims, check_dims_1);\n}", "template <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return MatchingFlatSize(dims, check_dims_1, check_dims_2);\n}", "template <int N>\ninline int MatchingFlatSize(const Dims<N>& dims, const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2,\n const Dims<N>& check_dims_3) {\n for (int i = 0; i < N; ++i) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n return MatchingFlatSize(dims, check_dims_1, check_dims_2, check_dims_3);\n}", "// Data is required to be contiguous, and so many operators can use either the\n// full array flat size or the flat size with one dimension skipped (commonly\n// the depth).\ntemplate <int N>\ninline int FlatSizeSkipDim(const Dims<N>& dims, int skip_dim) {\n TFLITE_DCHECK(skip_dim >= 0 && skip_dim < N);\n int flat_size = 1;\n for (int i = 0; i < N; ++i) {\n flat_size *= (i == skip_dim) ? 1 : dims.sizes[i];\n }\n return flat_size;\n}", "// A combination of MatchingFlatSize() and FlatSizeSkipDim().\ntemplate <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return FlatSizeSkipDim(dims, skip_dim);\n}", "template <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1);\n}", "template <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2);\n}", "template <int N>\ninline int MatchingFlatSizeSkipDim(const Dims<N>& dims, int skip_dim,\n const Dims<N>& check_dims_0,\n const Dims<N>& check_dims_1,\n const Dims<N>& check_dims_2,\n const Dims<N>& check_dims_3) {\n for (int i = 0; i < N; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(ArraySize(dims, i), ArraySize(check_dims_0, i));\n }\n }\n return MatchingFlatSizeSkipDim(dims, skip_dim, check_dims_1, check_dims_2,\n check_dims_3);\n}", "// Data is required to be contiguous, and so many operators can use either the\n// full array flat size or the flat size with one dimension skipped (commonly\n// the depth).\ninline int FlatSizeSkipDim(const RuntimeShape& shape, int skip_dim) {\n const int dims_count = shape.DimensionsCount();\n TFLITE_DCHECK(skip_dim >= 0 && skip_dim < dims_count);\n const auto* dims_data = shape.DimsData();\n int flat_size = 1;\n for (int i = 0; i < dims_count; ++i) {\n flat_size *= (i == skip_dim) ? 1 : dims_data[i];\n }\n return flat_size;\n}", "// A combination of MatchingFlatSize() and FlatSizeSkipDim().\ninline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return FlatSizeSkipDim(shape, skip_dim);\n}", "inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1);\n}", "inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2);\n}", "inline int MatchingFlatSizeSkipDim(const RuntimeShape& shape, int skip_dim,\n const RuntimeShape& check_shape_0,\n const RuntimeShape& check_shape_1,\n const RuntimeShape& check_shape_2,\n const RuntimeShape& check_shape_3) {\n const int dims_count = shape.DimensionsCount();\n for (int i = 0; i < dims_count; ++i) {\n if (i != skip_dim) {\n TFLITE_DCHECK_EQ(shape.Dims(i), check_shape_0.Dims(i));\n }\n }\n return MatchingFlatSizeSkipDim(shape, skip_dim, check_shape_1, check_shape_2,\n check_shape_3);\n}", "template <int N>\nbool IsPackedWithoutStrides(const Dims<N>& dims) {\n int expected_stride = 1;\n for (int d = 0; d < N; d++) {\n if (dims.strides[d] != expected_stride) return false;\n expected_stride *= dims.sizes[d];\n }\n return true;\n}", "template <int N>\nvoid ComputeStrides(Dims<N>* dims) {\n dims->strides[0] = 1;\n for (int d = 1; d < N; d++) {\n dims->strides[d] = dims->strides[d - 1] * dims->sizes[d - 1];\n }\n}", "enum class BroadcastableOpCategory : uint8_t {\n kNone,\n kNonBroadcast, // Matching input shapes.\n kFirstInputBroadcastsFast, // Fivefold nested loops.\n kSecondInputBroadcastsFast, // Fivefold nested loops.\n kGenericBroadcast, // Fall-back.\n};", "struct MinMax {\n float min;\n float max;\n};\nstatic_assert(sizeof(MinMax) == 8, \"\");", "struct ActivationParams {\n FusedActivationFunctionType activation_type;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n};", "struct ReluParams : public ActivationParams {\n int32_t input_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n};", "// Styles of resizing op usages. For example, kImageStyle can be used with a Pad\n// op for pattern-specific optimization.\nenum class ResizingCategory : uint8_t {\n kNone,\n kImageStyle, // 4D, operating on inner dimensions, say {0, a, b, 0}.\n kGenericResize,\n};", "// For Add, Sub, Mul ops.\nstruct ArithmeticParams {\n // Shape dependent / common to data / op types.\n BroadcastableOpCategory broadcast_category;\n // uint8_t inference params.\n int32_t input1_offset;\n int32_t input2_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // Add / Sub, not Mul, uint8_t inference params.\n int left_shift;\n int32_t input1_multiplier;\n int input1_shift;\n int32_t input2_multiplier;\n int input2_shift;", " // TODO(b/158622529): Union the following activation params.\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n // int64_t activation params.\n int64_t int64_activation_min;\n int64_t int64_activation_max;", " // Processed output dimensions.\n // Let input \"a\" be the one that broadcasts in the faster-changing dimension.\n // Then, after coalescing, for shapes {a0, a1, a2, a3, a4} and\n // {b0, b1, b2, b3, b4},\n // broadcast_shape[4] = b0 = a0.\n // broadcast_shape[3] = b1; a1 = 1.\n // broadcast_shape[2] = b2 = a2.\n // broadcast_shape[1] = a3; b3 = 1.\n // broadcast_shape[0] = b4 = a4.\n int broadcast_shape[5];\n};", "struct ConcatenationParams {\n int8_t axis;\n const int32_t* input_zeropoint;\n const float* input_scale;\n uint16_t inputs_count;\n int32_t output_zeropoint;\n float output_scale;\n};", "struct ComparisonParams {\n // uint8_t inference params.\n int left_shift;\n int32_t input1_offset;\n int32_t input1_multiplier;\n int input1_shift;\n int32_t input2_offset;\n int32_t input2_multiplier;\n int input2_shift;\n // Shape dependent / common to inference types.\n bool is_broadcast;\n};", "struct ConvParams {\n PaddingType padding_type;\n PaddingValues padding_values;\n // TODO(starka): This was just \"stride\", so check that width+height is OK.\n int16_t stride_width;\n int16_t stride_height;\n int16_t dilation_width_factor;\n int16_t dilation_height_factor;\n // uint8_t inference params.\n // TODO(b/65838351): Use smaller types if appropriate.\n int32_t input_offset;\n int32_t weights_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n};", "struct DepthToSpaceParams {\n int32_t block_size;\n};", "struct DepthwiseParams {\n PaddingType padding_type;\n PaddingValues padding_values;\n int16_t stride_width;\n int16_t stride_height;\n int16_t dilation_width_factor;\n int16_t dilation_height_factor;\n int16_t depth_multiplier;\n // uint8_t inference params.\n // TODO(b/65838351): Use smaller types if appropriate.\n int32_t input_offset;\n int32_t weights_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n const int32_t* output_multiplier_per_channel;\n const int32_t* output_shift_per_channel;\n};", "struct DequantizationParams {\n double scale;\n int32_t zero_point;\n};", "struct PerChannelDequantizationParams {\n const float* scale;\n const int32_t* zero_point;\n int32_t quantized_dimension;\n};", "struct FakeQuantParams {\n MinMax minmax;\n int32_t num_bits;\n};", "struct FullyConnectedParams {\n // uint8_t inference params.\n // TODO(b/65838351): Use smaller types if appropriate.\n int32_t input_offset;\n int32_t weights_offset;\n int32_t output_offset;\n int32_t output_multiplier;\n int output_shift;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n // Mark the operands as cacheable if they are unchanging, e.g. weights.\n bool lhs_cacheable;\n bool rhs_cacheable;\n FullyConnectedWeightsFormat weights_format;\n};", "struct GatherParams {\n int16_t axis;\n};", "struct L2NormalizationParams {\n // uint8_t inference params.\n int32_t input_zero_point;\n};", "struct LocalResponseNormalizationParams {\n int32_t range;\n double bias;\n double alpha;\n double beta;\n};", "struct HardSwishParams {\n // zero_point of the input activations.\n int16_t input_zero_point;\n // zero_point of the output activations.\n int16_t output_zero_point;\n // 16bit fixed-point component of the multiplier to apply to go from the\n // \"high-res input scale\", which is the input scale multiplied by 2^7, to the\n // \"relu-ish scale\", which 3.0/32768.\n // See the implementation of HardSwishPrepare.\n int16_t reluish_multiplier_fixedpoint_int16;\n // exponent/bit-shift component of the aforementioned multiplier.\n int reluish_multiplier_exponent;\n // 16bit fixed-point component of the multiplier to apply to go from the\n // \"high-res input scale\", which is the input scale multiplied by 2^7, to the\n // output scale.\n // See the implementation of HardSwishPrepare.\n int16_t output_multiplier_fixedpoint_int16;\n // exponent/bit-shift component of the aforementioned multiplier.\n int output_multiplier_exponent;\n};", "struct LogisticParams {\n // uint8_t inference params.\n int32_t input_zero_point;\n int32_t input_range_radius;\n int32_t input_multiplier;\n int input_left_shift;\n};", "struct LstmCellParams {\n int32_t weights_zero_point;\n int32_t accum_multiplier;\n int accum_shift;\n int state_integer_bits;\n};", "struct MeanParams {\n int8_t axis_count;\n int16_t axis[4];\n};", "struct PackParams {\n int8_t axis;\n const int32_t* input_zeropoint;\n const float* input_scale;\n uint16_t inputs_count;\n int32_t output_zeropoint;\n float output_scale;\n};", "struct PadParams {\n int8_t left_padding_count;\n int32_t left_padding[4];\n int8_t right_padding_count;\n int32_t right_padding[4];\n ResizingCategory resizing_category;\n};", "struct PreluParams {\n int32_t input_offset;\n int32_t alpha_offset;\n int32_t output_offset;\n int32_t output_multiplier_1;\n int output_shift_1;\n int32_t output_multiplier_2;\n int output_shift_2;\n};", "struct PoolParams {\n FusedActivationFunctionType activation;\n PaddingType padding_type;\n PaddingValues padding_values;\n int stride_height;\n int stride_width;\n int filter_height;\n int filter_width;\n // uint8_t, etc, activation params.\n int32_t quantized_activation_min;\n int32_t quantized_activation_max;\n // float activation params.\n float float_activation_min;\n float float_activation_max;\n};", "struct ReshapeParams {\n int8_t shape_count;\n int32_t shape[4];\n};", "struct ResizeBilinearParams {\n bool align_corners;\n // half_pixel_centers assumes pixels are of half the actual dimensions, and\n // yields more accurate resizes. Corresponds to the same argument for the\n // original TensorFlow op in TF2.0.\n bool half_pixel_centers;\n};", "struct ResizeNearestNeighborParams {\n bool align_corners;\n bool half_pixel_centers;\n};", "struct SliceParams {\n int8_t begin_count;\n int32_t begin[4];\n int8_t size_count;\n int32_t size[4];\n};", "struct SoftmaxParams {\n // beta is not really used (not a Tensorflow parameter) and not implemented\n // for LogSoftmax.\n double beta;\n // uint8_t inference params. Used even when beta defaults to 1.0.\n int32_t input_multiplier;\n int32_t input_left_shift;\n // Reverse scaling is only used by LogSoftmax.\n int32_t reverse_scaling_divisor;\n int32_t reverse_scaling_right_shift;\n int diff_min;\n int32_t zero_point;\n float scale;\n float* table;\n int16_t* exp_lut;\n int16_t* one_over_one_plus_x_lut;\n uint8_t* uint8_table1;\n uint8_t* uint8_table2;\n};", "struct SpaceToBatchParams {\n // \"Zero\" padding for uint8_t means padding with the output offset.\n int32_t output_offset;\n};", "struct SpaceToDepthParams {\n int32_t block_size;\n};", "struct SplitParams {\n // Graphs that split into, say, 2000 nodes are encountered. The indices in\n // OperatorEdges are of type uint16_t.\n uint16_t num_split;\n int16_t axis;\n};", "struct SqueezeParams {\n int8_t squeeze_dims_count;\n int32_t squeeze_dims[4];\n};", "struct StridedSliceParams {\n int8_t start_indices_count;\n int32_t start_indices[5];\n int8_t stop_indices_count;\n int32_t stop_indices[5];\n int8_t strides_count;\n int32_t strides[5];", " int16_t begin_mask;\n int16_t ellipsis_mask;\n int16_t end_mask;\n int16_t new_axis_mask;\n int16_t shrink_axis_mask;\n};", "struct TanhParams {\n int32_t input_zero_point;\n int32_t input_range_radius;\n int32_t input_multiplier;\n int input_left_shift;\n};", "struct TransposeParams {\n int8_t perm_count;\n int32_t perm[5];\n};", "struct UnpackParams {\n uint16_t num_split;\n int16_t axis;\n};", "struct LeakyReluParams {\n float alpha;\n int32_t input_offset;\n int32_t output_offset;\n int32_t output_multiplier_alpha;\n int32_t output_shift_alpha;\n int32_t output_multiplier_identity;\n int32_t output_shift_identity;\n};", "template <typename P>\ninline void SetActivationParams(float min, float max, P* params) {\n params->float_activation_min = min;\n params->float_activation_max = max;\n}", "template <typename P>\ninline void SetActivationParams(int32_t min, int32_t max, P* params) {\n params->quantized_activation_min = min;\n params->quantized_activation_max = max;\n}", "template <typename P>\ninline void SetActivationParams(int64_t min, int64_t max, P* params) {\n params->int64_activation_min = min;\n params->int64_activation_max = max;\n}", "template <typename P>\ninline void GetActivationParams(const P& params, int32_t* min, int32_t* max) {\n *min = params.quantized_activation_min;\n *max = params.quantized_activation_max;\n}", "template <typename P>\ninline void GetActivationParams(const P& params, float* min, float* max) {\n *min = params.float_activation_min;\n *max = params.float_activation_max;\n}", "template <typename P>\ninline void GetActivationParams(const P& params, int64_t* min, int64_t* max) {\n *min = params.int64_activation_min;\n *max = params.int64_activation_max;\n}\n} // namespace tflite", "#endif // TENSORFLOW_LITE_KERNELS_INTERNAL_TYPES_H_" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [442], "buggy_code_start_loc": [441], "filenames": ["tensorflow/lite/kernels/internal/types.h"], "fixing_code_end_loc": [442], "fixing_code_start_loc": [441], "message": "In tensorflow-lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, when determining the common dimension size of two tensors, TFLite uses a `DCHECK` which is no-op outside of debug compilation modes. Since the function always returns the dimension of the first tensor, malicious attackers can craft cases where this is larger than that of the second tensor. In turn, this would result in reads/writes outside of bounds since the interpreter will wrongly assume that there is enough data in both tensors. The issue is patched in commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "7A5421A9-693F-472A-9A21-43950C884C77", "versionEndExcluding": "1.15.4", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "B0FEB74E-5E54-4A2F-910C-FA1812C73DB2", "versionEndExcluding": "2.0.3", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.0.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "47D83682-6615-49BC-8043-F36B9D017578", "versionEndExcluding": "2.1.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.1.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "323B716A-E8F7-4CDA-B8FD-A56977D59C02", "versionEndExcluding": "2.2.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.2.0", "vulnerable": true}, {"criteria": "cpe:2.3:a:google:tensorflow:*:*:*:*:lite:*:*:*", "matchCriteriaId": "C09502A8-B667-4867-BEBD-40333E98A601", "versionEndExcluding": "2.3.1", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "2.3.0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.2:*:*:*:*:*:*:*", "matchCriteriaId": "B009C22E-30A4-4288-BCF6-C3E81DEAF45A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In tensorflow-lite before versions 1.15.4, 2.0.3, 2.1.2, 2.2.1 and 2.3.1, when determining the common dimension size of two tensors, TFLite uses a `DCHECK` which is no-op outside of debug compilation modes. Since the function always returns the dimension of the first tensor, malicious attackers can craft cases where this is larger than that of the second tensor. In turn, this would result in reads/writes outside of bounds since the interpreter will wrongly assume that there is enough data in both tensors. The issue is patched in commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, and is released in TensorFlow versions 1.15.4, 2.0.3, 2.1.2, 2.2.1, or 2.3.1."}, {"lang": "es", "value": "En tensorflow-lite versiones anteriores a 1.15.4, 2.0.3, 2.1.2, 2.2.1 y 2.3.1, al determinar el tama\u00f1o de dimensi\u00f3n com\u00fan de dos tensores, TFLite usa un \"DCHECK\" que no es operativo fuera de los modos de compilaci\u00f3n de depuraci\u00f3n.&#xa0;Dado que la funci\u00f3n siempre devuelve la dimensi\u00f3n del primer tensor, los atacantes maliciosos pueden crear casos en los que este sea mayor que el del segundo tensor.&#xa0;A su vez, esto resultar\u00eda en lecturas y escrituras fuera de l\u00edmites, ya que el int\u00e9rprete asumir\u00e1 incorrectamente que existen suficientes datos en ambos tensores.&#xa0;El problema es parcheado en el commit 8ee24e7949a203d234489f9da2c5bf45a7d5157d, y es publicado en TensorFlow versiones 1.15.4, 2.0.3, 2.1.2, 2.2.1 o 2.3.1"}], "evaluatorComment": null, "id": "CVE-2020-15208", "lastModified": "2021-09-16T15:45:33.860", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 7.4, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 2.2, "impactScore": 5.2, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-09-25T19:15:16.103", "references": [{"source": "security-advisories@github.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2020-10/msg00065.html"}, {"source": "security-advisories@github.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/commit/8ee24e7949a203d234489f9da2c5bf45a7d5157d"}, {"source": "security-advisories@github.com", "tags": ["Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/releases/tag/v2.3.1"}, {"source": "security-advisories@github.com", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/tensorflow/tensorflow/security/advisories/GHSA-mxjj-953w-2c2v"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-125"}, {"lang": "en", "value": "CWE-787"}], "source": "security-advisories@github.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/tensorflow/tensorflow/commit/8ee24e7949a203d234489f9da2c5bf45a7d5157d"}, "type": "CWE-125"}
28
Determine whether the {function_name} code is vulnerable or not.
[ "# PrivateAddressCheck", "[![Build Status](https://travis-ci.org/jtdowney/private_address_check.svg?branch=master)](https://travis-ci.org/jtdowney/private_address_check)\n[![Code Climate](https://codeclimate.com/github/jtdowney/private_address_check/badges/gpa.svg)](https://codeclimate.com/github/jtdowney/private_address_check)", "Checks if a URL or hostname would cause a request to a private network (RFC 1918). This is useful in preventing attacks like [Server Side Request Forgery](https://cwe.mitre.org/data/definitions/918.html).", "## Requirements", "* Ruby >= 2.0", "## Installation", "Add this line to your application's Gemfile:", "```ruby\ngem 'private_address_check'\n```", "And then execute:", " $ bundle", "Or install it yourself as:", " $ gem install private_address_check", "## Usage", "```ruby\nrequire \"private_address_check\"", "PrivateAddressCheck.private_address?(\"8.8.8.8\") # => false\nPrivateAddressCheck.private_address?(\"10.10.10.2\") # => true\nPrivateAddressCheck.private_address?(\"127.0.0.1\") # => true\nPrivateAddressCheck.private_address?(\"172.16.2.10\") # => true\nPrivateAddressCheck.private_address?(\"192.168.1.10\") # => true\nPrivateAddressCheck.private_address?(\"fd00::2\") # => true\nPrivateAddressCheck.resolves_to_private_address?(\"github.com\") # => false\nPrivateAddressCheck.resolves_to_private_address?(\"localhost\") # => true", "require \"private_address_check/tcpsocket_ext\"\nrequire \"net/http\"\nrequire \"uri\"", "Net::HTTP.get_response(URI.parse(\"http://192.168.1.1\")) # => attempts connection like normal", "PrivateAddressCheck.only_public_connections do\n Net::HTTP.get_response(URI.parse(\"http://192.168.1.1\"))\nend\n# => raises PrivateAddressCheck::PrivateConnectionAttemptedError\n```", "## Development", "After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.", "To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).", "## Contributing", "Bug reports and pull requests are welcome on GitHub at https://github.com/jtdowney/private_address_check. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.\n", "", "\n## License", "The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT)." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [69, 23, 10], "buggy_code_start_loc": [63, 17, 5], "filenames": ["README.md", "lib/private_address_check/tcpsocket_ext.rb", "test/private_address_check/tcpsocket_ext_test.rb"], "fixing_code_end_loc": [78, 21, 15], "fixing_code_start_loc": [64, 17, 6], "message": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:private_address_check_project:private_address_check:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "6FCBC921-366D-465C-9171-A5F2101A6078", "versionEndExcluding": "0.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address."}, {"lang": "es", "value": "La gema de Ruby private_address_check en versiones anteriores a la 0.5.0 es vulnerable a una condici\u00f3n de carrera TOCTOU (time-of-check time-of-use) debido a que no se comprueba la direcci\u00f3n empleada por el socket. Las entradas DNS con un TLL de 0 pueden desencadenar este caso donde la resoluci\u00f3n inicial es una direcci\u00f3n p\u00fablica, pero la siguiente es una direcci\u00f3n privada."}], "evaluatorComment": null, "id": "CVE-2018-3759", "lastModified": "2019-10-09T23:40:35.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-13T15:29:00.267", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-362"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}, "type": "CWE-362"}
29
Determine whether the {function_name} code is vulnerable or not.
[ "# PrivateAddressCheck", "[![Build Status](https://travis-ci.org/jtdowney/private_address_check.svg?branch=master)](https://travis-ci.org/jtdowney/private_address_check)\n[![Code Climate](https://codeclimate.com/github/jtdowney/private_address_check/badges/gpa.svg)](https://codeclimate.com/github/jtdowney/private_address_check)", "Checks if a URL or hostname would cause a request to a private network (RFC 1918). This is useful in preventing attacks like [Server Side Request Forgery](https://cwe.mitre.org/data/definitions/918.html).", "## Requirements", "* Ruby >= 2.0", "## Installation", "Add this line to your application's Gemfile:", "```ruby\ngem 'private_address_check'\n```", "And then execute:", " $ bundle", "Or install it yourself as:", " $ gem install private_address_check", "## Usage", "```ruby\nrequire \"private_address_check\"", "PrivateAddressCheck.private_address?(\"8.8.8.8\") # => false\nPrivateAddressCheck.private_address?(\"10.10.10.2\") # => true\nPrivateAddressCheck.private_address?(\"127.0.0.1\") # => true\nPrivateAddressCheck.private_address?(\"172.16.2.10\") # => true\nPrivateAddressCheck.private_address?(\"192.168.1.10\") # => true\nPrivateAddressCheck.private_address?(\"fd00::2\") # => true\nPrivateAddressCheck.resolves_to_private_address?(\"github.com\") # => false\nPrivateAddressCheck.resolves_to_private_address?(\"localhost\") # => true", "require \"private_address_check/tcpsocket_ext\"\nrequire \"net/http\"\nrequire \"uri\"", "Net::HTTP.get_response(URI.parse(\"http://192.168.1.1\")) # => attempts connection like normal", "PrivateAddressCheck.only_public_connections do\n Net::HTTP.get_response(URI.parse(\"http://192.168.1.1\"))\nend\n# => raises PrivateAddressCheck::PrivateConnectionAttemptedError\n```", "## Development", "After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.", "To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).", "## Contributing", "Bug reports and pull requests are welcome on GitHub at https://github.com/jtdowney/private_address_check. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.\n", "## Security", "If you've found a security issue in `private_address_check`, please reach out to @jtdowney via email to report.", "### Time of check to time of use", "A library like `private_address_check` is going to be easily susceptible to attacks like [time of check to time of use](https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use). DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address by the subsequent resolution is a private address. There are some possible defenses and workarounds:", "- Use the TCPSocket extension in this library which checks the address the socket uses. This is most useful if your system is built on native Ruby like Net::HTTP.\n- Use a feature like the `resolve` capability in curl and [curb](https://www.rubydoc.info/github/taf2/curb/Curl/Easy#resolve=-instance_method) to force the resolution to a pre-checked IP address.\n- Implement your own caching DNS resolver with something like dnsmasq or unbound. These tools let you set a minimum cache time that can override the TTL of 0.", "\n## License", "The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT)." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [69, 23, 10], "buggy_code_start_loc": [63, 17, 5], "filenames": ["README.md", "lib/private_address_check/tcpsocket_ext.rb", "test/private_address_check/tcpsocket_ext_test.rb"], "fixing_code_end_loc": [78, 21, 15], "fixing_code_start_loc": [64, 17, 6], "message": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:private_address_check_project:private_address_check:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "6FCBC921-366D-465C-9171-A5F2101A6078", "versionEndExcluding": "0.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address."}, {"lang": "es", "value": "La gema de Ruby private_address_check en versiones anteriores a la 0.5.0 es vulnerable a una condici\u00f3n de carrera TOCTOU (time-of-check time-of-use) debido a que no se comprueba la direcci\u00f3n empleada por el socket. Las entradas DNS con un TLL de 0 pueden desencadenar este caso donde la resoluci\u00f3n inicial es una direcci\u00f3n p\u00fablica, pero la siguiente es una direcci\u00f3n privada."}], "evaluatorComment": null, "id": "CVE-2018-3759", "lastModified": "2019-10-09T23:40:35.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-13T15:29:00.267", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-362"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}, "type": "CWE-362"}
29
Determine whether the {function_name} code is vulnerable or not.
[ "module PrivateAddressCheck\n PrivateConnectionAttemptedError = Class.new(StandardError)", " module_function", " def only_public_connections\n Thread.current[:private_address_check] = true\n yield\n ensure\n Thread.current[:private_address_check] = false\n end\nend", "TCPSocket.class_eval do\n alias initialize_without_private_address_check initialize\n", " def initialize(remote_host, remote_port, local_host = nil, local_port = nil)\n if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_host)", " raise PrivateAddressCheck::PrivateConnectionAttemptedError\n end", "\n initialize_without_private_address_check(remote_host, remote_port, local_host, local_port)", " end\nend" ]
[ 1, 1, 1, 1, 0, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [69, 23, 10], "buggy_code_start_loc": [63, 17, 5], "filenames": ["README.md", "lib/private_address_check/tcpsocket_ext.rb", "test/private_address_check/tcpsocket_ext_test.rb"], "fixing_code_end_loc": [78, 21, 15], "fixing_code_start_loc": [64, 17, 6], "message": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:private_address_check_project:private_address_check:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "6FCBC921-366D-465C-9171-A5F2101A6078", "versionEndExcluding": "0.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address."}, {"lang": "es", "value": "La gema de Ruby private_address_check en versiones anteriores a la 0.5.0 es vulnerable a una condici\u00f3n de carrera TOCTOU (time-of-check time-of-use) debido a que no se comprueba la direcci\u00f3n empleada por el socket. Las entradas DNS con un TLL de 0 pueden desencadenar este caso donde la resoluci\u00f3n inicial es una direcci\u00f3n p\u00fablica, pero la siguiente es una direcci\u00f3n privada."}], "evaluatorComment": null, "id": "CVE-2018-3759", "lastModified": "2019-10-09T23:40:35.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-13T15:29:00.267", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-362"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}, "type": "CWE-362"}
29
Determine whether the {function_name} code is vulnerable or not.
[ "module PrivateAddressCheck\n PrivateConnectionAttemptedError = Class.new(StandardError)", " module_function", " def only_public_connections\n Thread.current[:private_address_check] = true\n yield\n ensure\n Thread.current[:private_address_check] = false\n end\nend", "TCPSocket.class_eval do\n alias initialize_without_private_address_check initialize\n", " def initialize(*args)\n initialize_without_private_address_check(*args)\n if Thread.current[:private_address_check] && PrivateAddressCheck.resolves_to_private_address?(remote_address.ip_address)", " raise PrivateAddressCheck::PrivateConnectionAttemptedError\n end", "", " end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [69, 23, 10], "buggy_code_start_loc": [63, 17, 5], "filenames": ["README.md", "lib/private_address_check/tcpsocket_ext.rb", "test/private_address_check/tcpsocket_ext_test.rb"], "fixing_code_end_loc": [78, 21, 15], "fixing_code_start_loc": [64, 17, 6], "message": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:private_address_check_project:private_address_check:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "6FCBC921-366D-465C-9171-A5F2101A6078", "versionEndExcluding": "0.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address."}, {"lang": "es", "value": "La gema de Ruby private_address_check en versiones anteriores a la 0.5.0 es vulnerable a una condici\u00f3n de carrera TOCTOU (time-of-check time-of-use) debido a que no se comprueba la direcci\u00f3n empleada por el socket. Las entradas DNS con un TLL de 0 pueden desencadenar este caso donde la resoluci\u00f3n inicial es una direcci\u00f3n p\u00fablica, pero la siguiente es una direcci\u00f3n privada."}], "evaluatorComment": null, "id": "CVE-2018-3759", "lastModified": "2019-10-09T23:40:35.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-13T15:29:00.267", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-362"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}, "type": "CWE-362"}
29
Determine whether the {function_name} code is vulnerable or not.
[ "require 'test_helper'\nrequire 'private_address_check/tcpsocket_ext'", "class TCPSocketExtTest < Minitest::Test\n def test_private_address", "", " assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do\n PrivateAddressCheck.only_public_connections do", " TCPSocket.new(\"localhost\", 80)", " end\n end", "", " end", " def test_public_address\n connected = false\n PrivateAddressCheck.only_public_connections do\n TCPSocket.new(\"example.com\", 80)\n connected = true\n end", " assert connected\n end", " def test_invalid_domain\n assert_raises SocketError do\n PrivateAddressCheck.only_public_connections do\n TCPSocket.new(\"not_a_domain\", 80)\n end\n end\n end\nend" ]
[ 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [69, 23, 10], "buggy_code_start_loc": [63, 17, 5], "filenames": ["README.md", "lib/private_address_check/tcpsocket_ext.rb", "test/private_address_check/tcpsocket_ext_test.rb"], "fixing_code_end_loc": [78, 21, 15], "fixing_code_start_loc": [64, 17, 6], "message": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:private_address_check_project:private_address_check:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "6FCBC921-366D-465C-9171-A5F2101A6078", "versionEndExcluding": "0.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address."}, {"lang": "es", "value": "La gema de Ruby private_address_check en versiones anteriores a la 0.5.0 es vulnerable a una condici\u00f3n de carrera TOCTOU (time-of-check time-of-use) debido a que no se comprueba la direcci\u00f3n empleada por el socket. Las entradas DNS con un TLL de 0 pueden desencadenar este caso donde la resoluci\u00f3n inicial es una direcci\u00f3n p\u00fablica, pero la siguiente es una direcci\u00f3n privada."}], "evaluatorComment": null, "id": "CVE-2018-3759", "lastModified": "2019-10-09T23:40:35.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-13T15:29:00.267", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-362"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}, "type": "CWE-362"}
29
Determine whether the {function_name} code is vulnerable or not.
[ "require 'test_helper'\nrequire 'private_address_check/tcpsocket_ext'", "class TCPSocketExtTest < Minitest::Test\n def test_private_address", " server = TCPServer.new(63453)\n thread = Thread.start { server.accept }", " assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do\n PrivateAddressCheck.only_public_connections do", " TCPSocket.new(\"localhost\", 63453)", " end\n end", " ensure\n thread.exit if thread", " end", " def test_public_address\n connected = false\n PrivateAddressCheck.only_public_connections do\n TCPSocket.new(\"example.com\", 80)\n connected = true\n end", " assert connected\n end", " def test_invalid_domain\n assert_raises SocketError do\n PrivateAddressCheck.only_public_connections do\n TCPSocket.new(\"not_a_domain\", 80)\n end\n end\n end\nend" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [69, 23, 10], "buggy_code_start_loc": [63, 17, 5], "filenames": ["README.md", "lib/private_address_check/tcpsocket_ext.rb", "test/private_address_check/tcpsocket_ext_test.rb"], "fixing_code_end_loc": [78, 21, 15], "fixing_code_start_loc": [64, 17, 6], "message": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:private_address_check_project:private_address_check:*:*:*:*:*:ruby:*:*", "matchCriteriaId": "6FCBC921-366D-465C-9171-A5F2101A6078", "versionEndExcluding": "0.5.0", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "private_address_check ruby gem before 0.5.0 is vulnerable to a time-of-check time-of-use (TOCTOU) race condition due to the address the socket uses not being checked. DNS entries with a TTL of 0 can trigger this case where the initial resolution is a public address but the subsequent resolution is a private address."}, {"lang": "es", "value": "La gema de Ruby private_address_check en versiones anteriores a la 0.5.0 es vulnerable a una condici\u00f3n de carrera TOCTOU (time-of-check time-of-use) debido a que no se comprueba la direcci\u00f3n empleada por el socket. Las entradas DNS con un TLL de 0 pueden desencadenar este caso donde la resoluci\u00f3n inicial es una direcci\u00f3n p\u00fablica, pero la siguiente es una direcci\u00f3n privada."}], "evaluatorComment": null, "id": "CVE-2018-3759", "lastModified": "2019-10-09T23:40:35.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 4.3, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.6, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "HIGH", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 3.7, "baseSeverity": "LOW", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.2, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-06-13T15:29:00.267", "references": [{"source": "support@hackerone.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}], "sourceIdentifier": "support@hackerone.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-362"}], "source": "support@hackerone.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/jtdowney/private_address_check/commit/4068228187db87fea7577f7020099399772bb147"}, "type": "CWE-362"}
29
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% PPPP DDDD FFFFF %\n% P P D D F %\n% PPPP D D FFF %\n% P D D F %\n% P DDDD F %\n% %\n% %\n% Read/Write Portable Document Format %\n% %\n% Software Design %\n% Cristy %\n% July 1992 %\n% %\n% %\n% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% https://imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/color.h\"\n#include \"MagickCore/color-private.h\"\n#include \"MagickCore/colorspace.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/compress.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/delegate.h\"\n#include \"MagickCore/delegate-private.h\"\n#include \"MagickCore/draw.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/geometry.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/monitor.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/nt-base-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/profile.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/resource_.h\"\n#include \"MagickCore/resize.h\"\n#include \"MagickCore/signature.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/token.h\"\n#include \"MagickCore/transform.h\"\n#include \"MagickCore/utility.h\"\n#include \"MagickCore/module.h\"\n\f\n/*\n Define declarations.\n*/\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n#define CCITTParam \"-1\"\n#else\n#define CCITTParam \"0\"\n#endif\n\f\n/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n WritePDFImage(const ImageInfo *,Image *,ExceptionInfo *);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I n v o k e P D F D e l e g a t e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% InvokePDFDelegate() executes the PDF interpreter with the specified command.\n%\n% The format of the InvokePDFDelegate method is:\n%\n% MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose,\n% const char *command,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o verbose: A value other than zero displays the command prior to\n% executing it.\n%\n% o command: the address of a character string containing the command to\n% execute.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\n#if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT)\nstatic int MagickDLLCall PDFDelegateMessage(void *handle,const char *message,\n int length)\n{\n char\n **messages;", " ssize_t\n offset;", " offset=0;\n messages=(char **) handle;\n if (*messages == (char *) NULL)\n *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *));\n else\n {\n offset=strlen(*messages);\n *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1,\n sizeof(char *));\n }\n if (*messages == (char *) NULL)\n return(0);\n (void) memcpy(*messages+offset,message,length);\n (*messages)[length+offset] ='\\0';\n return(length);\n}\n#endif", "static MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose,\n const char *command,char *message,ExceptionInfo *exception)\n{\n int\n status;", "#define ExecuteGhostscriptCommand(command,status) \\\n{ \\\n status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \\\n exception); \\\n if (status == 0) \\\n return(MagickTrue); \\\n if (status < 0) \\\n return(MagickFalse); \\\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \\\n \"FailedToExecuteCommand\",\"`%s' (%d)\",command,status); \\\n return(MagickFalse); \\\n}", "#if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT)\n#define SetArgsStart(command,args_start) \\\n if (args_start == (const char *) NULL) \\\n { \\\n if (*command != '\"') \\\n args_start=strchr(command,' '); \\\n else \\\n { \\\n args_start=strchr(command+1,'\"'); \\\n if (args_start != (const char *) NULL) \\\n args_start++; \\\n } \\\n }", " char\n **argv,\n *errors;", " const char\n *args_start = (const char *) NULL;", " const GhostInfo\n *ghost_info;", " gs_main_instance\n *interpreter;", " gsapi_revision_t\n revision;", " int\n argc,\n code;", " register ssize_t\n i;", "#if defined(MAGICKCORE_WINDOWS_SUPPORT)\n ghost_info=NTGhostscriptDLLVectors();\n#else\n GhostInfo\n ghost_info_struct;", " ghost_info=(&ghost_info_struct);\n (void) memset(&ghost_info_struct,0,sizeof(ghost_info_struct));\n ghost_info_struct.delete_instance=(void (*)(gs_main_instance *))\n gsapi_delete_instance;\n ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit;\n ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *))\n gsapi_new_instance;\n ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **))\n gsapi_init_with_args;\n ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int,\n int *)) gsapi_run_string;\n ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int (*)(void *,char *,\n int),int (*)(void *,const char *,int),int (*)(void *, const char *, int)))\n gsapi_set_stdio;\n ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision;\n#endif\n if (ghost_info == (GhostInfo *) NULL)\n ExecuteGhostscriptCommand(command,status);\n if ((ghost_info->revision)(&revision,sizeof(revision)) != 0)\n revision.revision=0;\n if (verbose != MagickFalse)\n {\n (void) fprintf(stdout,\"[ghostscript library %.2f]\",(double)\n revision.revision/100.0);\n SetArgsStart(command,args_start);\n (void) fputs(args_start,stdout);\n }\n errors=(char *) NULL;\n status=(ghost_info->new_instance)(&interpreter,(void *) &errors);\n if (status < 0)\n ExecuteGhostscriptCommand(command,status);\n code=0;\n argv=StringToArgv(command,&argc);\n if (argv == (char **) NULL)\n {\n (ghost_info->delete_instance)(interpreter);\n return(MagickFalse);\n }\n (void) (ghost_info->set_stdio)(interpreter,(int (MagickDLLCall *)(void *,\n char *,int)) NULL,PDFDelegateMessage,PDFDelegateMessage);\n status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1);\n if (status == 0)\n status=(ghost_info->run_string)(interpreter,\"systemdict /start get exec\\n\",\n 0,&code);\n (ghost_info->exit)(interpreter);\n (ghost_info->delete_instance)(interpreter);\n for (i=0; i < (ssize_t) argc; i++)\n argv[i]=DestroyString(argv[i]);\n argv=(char **) RelinquishMagickMemory(argv);\n if (status != 0)\n {\n SetArgsStart(command,args_start);\n if (status == -101) /* quit */\n (void) FormatLocaleString(message,MagickPathExtent,\n \"[ghostscript library %.2f]%s: %s\",(double) revision.revision/100.0,\n args_start,errors);\n else\n {\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,\n \"PDFDelegateFailed\",\"`[ghostscript library %.2f]%s': %s\",(double)\n revision.revision/100.0,args_start,errors);\n if (errors != (char *) NULL)\n errors=DestroyString(errors);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Ghostscript returns status %d, exit code %d\",status,code);\n return(MagickFalse);\n }\n }\n if (errors != (char *) NULL)\n errors=DestroyString(errors);\n return(MagickTrue);\n#else\n ExecuteGhostscriptCommand(command,status);\n#endif\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I s P D F %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% IsPDF() returns MagickTrue if the image format type, identified by the\n% magick string, is PDF.\n%\n% The format of the IsPDF method is:\n%\n% MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset)\n%\n% A description of each parameter follows:\n%\n% o magick: compare image format pattern against these bytes.\n%\n% o offset: Specifies the offset of the magick string.\n%\n*/\nstatic MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset)\n{\n if (offset < 5)\n return(MagickFalse);\n if (LocaleNCompare((const char *) magick,\"%PDF-\",5) == 0)\n return(MagickTrue);\n return(MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadPDFImage() reads a Portable Document Format image file and\n% returns it. It allocates the memory necessary for the new Image structure\n% and returns a pointer to the new image.\n%\n% The format of the ReadPDFImage method is:\n%\n% Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static MagickBooleanType IsPDFRendered(const char *path)\n{\n MagickBooleanType\n status;", " struct stat\n attributes;", " if ((path == (const char *) NULL) || (*path == '\\0'))\n return(MagickFalse);\n status=GetPathAttributes(path,&attributes);\n if ((status != MagickFalse) && S_ISREG(attributes.st_mode) &&\n (attributes.st_size > 0))\n return(MagickTrue);\n return(MagickFalse);\n}", "static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define BeginXMPPacket \"<?xpacket begin=\"\n#define CMYKProcessColor \"CMYKProcessColor\"\n#define CropBox \"CropBox\"\n#define DefaultCMYK \"DefaultCMYK\"\n#define DeviceCMYK \"DeviceCMYK\"\n#define EndXMPPacket \"<?xpacket end=\"\n#define MediaBox \"MediaBox\"\n#define RenderPostscriptText \"Rendering Postscript... \"\n#define PDFRotate \"Rotate\"\n#define SpotColor \"Separation\"\n#define TrimBox \"TrimBox\"\n#define PDFVersion \"PDF-\"", " char\n command[MagickPathExtent],\n *density,\n filename[MagickPathExtent],\n geometry[MagickPathExtent],\n input_filename[MagickPathExtent],\n message[MagickPathExtent],\n *options,\n postscript_filename[MagickPathExtent];", " const char\n *option;", " const DelegateInfo\n *delegate_info;", " double\n angle;", " GeometryInfo\n geometry_info;", " Image\n *image,\n *next,\n *pdf_image;", " ImageInfo\n *read_info;", " int\n c,\n file;", " MagickBooleanType\n cmyk,\n cropbox,\n fitPage,\n status,\n stop_on_error,\n trimbox;", " MagickStatusType\n flags;", " PointInfo\n delta;", " RectangleInfo\n bounding_box,\n page;", " register char\n *p;", " register ssize_t\n i;", " SegmentInfo\n bounds,\n hires_bounds;", " size_t\n scene,\n spotcolor;", " ssize_t\n count;", " assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n /*\n Open image file.\n */\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Set the page density.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n (void) memset(&page,0,sizeof(page));\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)-\n 0.5);\n page.height=(size_t) ceil((double) (page.height*image->resolution.y/delta.y)-\n 0.5);\n /*\n Determine page geometry from the PDF media box.\n */\n cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n cropbox=IsStringTrue(GetImageOption(image_info,\"pdf:use-cropbox\"));\n stop_on_error=IsStringTrue(GetImageOption(image_info,\"pdf:stop-on-error\"));\n trimbox=IsStringTrue(GetImageOption(image_info,\"pdf:use-trimbox\"));\n count=0;\n spotcolor=0;\n (void) memset(&bounding_box,0,sizeof(bounding_box));\n (void) memset(&bounds,0,sizeof(bounds));\n (void) memset(&hires_bounds,0,sizeof(hires_bounds));\n (void) memset(command,0,sizeof(command));\n angle=0.0;\n p=command;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n /*\n Note PDF elements.\n */\n if (c == '\\n')\n c=' ';\n *p++=(char) c;\n if ((c != (int) '/') && (c != (int) '%') &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *(--p)='\\0';\n p=command;\n if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0)\n count=(ssize_t) sscanf(command,\"Rotate %lf\",&angle);\n /*\n Is this a CMYK document?\n */\n if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)\n {\n char\n name[MagickPathExtent],\n property[MagickPathExtent],\n *value;", " /*\n Note spot names.\n */\n (void) FormatLocaleString(property,MagickPathExtent,\n \"pdf:SpotColor-%.20g\",(double) spotcolor++);\n i=0;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n if ((isspace(c) != 0) || (c == '/') || ((i+1) == MagickPathExtent))\n break;\n name[i++]=(char) c;\n }\n name[i]='\\0';\n value=ConstantString(name);\n (void) SubstituteString(&value,\"#20\",\" \");\n if (*value != '\\0')\n (void) SetImageProperty(image,property,value,exception);\n value=DestroyString(value);\n continue;\n }\n if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0)\n (void) SetImageProperty(image,\"pdf:Version\",command,exception);\n if (image_info->page != (char *) NULL)\n continue;\n count=0;\n if (cropbox != MagickFalse)\n {\n if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n {\n /*\n Note region defined by crop box.\n */\n count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n }\n else\n if (trimbox != MagickFalse)\n {\n if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0)\n {\n /*\n Note region defined by trim box.\n */\n count=(ssize_t) sscanf(command,\"TrimBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"TrimBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n }\n else\n if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n {\n /*\n Note region defined by media box.\n */\n count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (count != 4)\n continue;\n if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) ||\n (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1)))\n continue;\n hires_bounds=bounds;\n }\n if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) &&\n (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon))\n {\n /*\n Set PDF render geometry.\n */\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%gx%g%+.15g%+.15g\",\n hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1,\n hires_bounds.x1,hires_bounds.y1);\n (void) SetImageProperty(image,\"pdf:HiResBoundingBox\",geometry,exception);\n page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)*\n image->resolution.x/delta.x)-0.5);\n page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)*\n image->resolution.y/delta.y)-0.5);\n }\n fitPage=MagickFalse;\n option=GetImageOption(image_info,\"pdf:fit-page\");\n if (option != (char *) NULL)\n {\n char\n *page_geometry;", " page_geometry=GetPageGeometry(option);\n flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width,\n &page.height);\n page_geometry=DestroyString(page_geometry);\n if (flags == NoValue)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidGeometry\",\"`%s'\",option);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)\n -0.5);\n page.height=(size_t) ceil((double) (page.height*image->resolution.y/\n delta.y) -0.5);\n fitPage=MagickTrue;\n }\n if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0))\n {\n size_t\n swap;", " swap=page.width;\n page.width=page.height;\n page.height=swap;\n }\n if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)\n cmyk=MagickFalse;\n /*\n Create Ghostscript control file.\n */\n file=AcquireUniqueFileResource(postscript_filename);\n if (file == -1)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n count=write(file,\" \",1);\n file=close(file)-1;\n /*\n Render Postscript with the Ghostscript delegate.\n */\n if (image_info->monochrome != MagickFalse)\n delegate_info=GetDelegateInfo(\"ps:mono\",(char *) NULL,exception);\n else\n if (cmyk != MagickFalse)\n delegate_info=GetDelegateInfo(\"ps:cmyk\",(char *) NULL,exception);\n else\n delegate_info=GetDelegateInfo(\"ps:alpha\",(char *) NULL,exception);\n if (delegate_info == (const DelegateInfo *) NULL)\n {\n (void) RelinquishUniqueFileResource(postscript_filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n density=AcquireString(\"\");\n options=AcquireString(\"\");\n (void) FormatLocaleString(density,MagickPathExtent,\"%gx%g\",\n image->resolution.x,image->resolution.y);\n if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse))\n (void) FormatLocaleString(options,MagickPathExtent,\"-g%.20gx%.20g \",(double)\n page.width,(double) page.height);\n if (fitPage != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dPSFitPage \",MagickPathExtent);\n if (cmyk != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseCIEColor \",MagickPathExtent);\n if (cropbox != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseCropBox \",MagickPathExtent);\n if (stop_on_error != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dPDFSTOPONERROR \",\n MagickPathExtent);\n if (trimbox != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseTrimBox \",MagickPathExtent);\n option=GetImageOption(image_info,\"authenticate\");\n if (option != (char *) NULL)\n {\n char\n passphrase[MagickPathExtent];", " (void) FormatLocaleString(passphrase,MagickPathExtent,\n \"\\\"-sPDFPassword=%s\\\" \",option);\n (void) ConcatenateMagickString(options,passphrase,MagickPathExtent);\n }\n read_info=CloneImageInfo(image_info);\n *read_info->magick='\\0';\n if (read_info->number_scenes != 0)\n {\n char\n pages[MagickPathExtent];", " (void) FormatLocaleString(pages,MagickPathExtent,\"-dFirstPage=%.20g \"\n \"-dLastPage=%.20g\",(double) read_info->scene+1,(double)\n (read_info->scene+read_info->number_scenes));\n (void) ConcatenateMagickString(options,pages,MagickPathExtent);\n read_info->number_scenes=0;\n if (read_info->scenes != (char *) NULL)\n *read_info->scenes='\\0';\n }\n (void) CopyMagickString(filename,read_info->filename,MagickPathExtent);\n (void) AcquireUniqueFilename(filename);\n (void) RelinquishUniqueFileResource(filename);\n (void) ConcatenateMagickString(filename,\"%d\",MagickPathExtent);\n (void) FormatLocaleString(command,MagickPathExtent,\n GetDelegateCommands(delegate_info),\n read_info->antialias != MagickFalse ? 4 : 1,\n read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,\n postscript_filename,input_filename);\n options=DestroyString(options);\n density=DestroyString(density);\n *message='\\0';\n status=InvokePDFDelegate(read_info->verbose,command,message,exception);\n (void) RelinquishUniqueFileResource(postscript_filename);\n (void) RelinquishUniqueFileResource(input_filename);\n pdf_image=(Image *) NULL;\n if (status == MagickFalse)\n for (i=1; ; i++)\n {\n (void) InterpretImageFilename(image_info,image,filename,(int) i,\n read_info->filename,exception);\n if (IsPDFRendered(read_info->filename) == MagickFalse)\n break;\n (void) RelinquishUniqueFileResource(read_info->filename);\n }\n else\n for (i=1; ; i++)\n {\n (void) InterpretImageFilename(image_info,image,filename,(int) i,\n read_info->filename,exception);\n if (IsPDFRendered(read_info->filename) == MagickFalse)\n break;\n read_info->blob=NULL;\n read_info->length=0;\n next=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n if (next == (Image *) NULL)\n break;\n AppendImageToList(&pdf_image,next);\n }\n read_info=DestroyImageInfo(read_info);\n if (pdf_image == (Image *) NULL)\n {\n if (*message != '\\0')\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,\n \"PDFDelegateFailed\",\"`%s'\",message);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (LocaleCompare(pdf_image->magick,\"BMP\") == 0)\n {\n Image\n *cmyk_image;", " cmyk_image=ConsolidateCMYKImages(pdf_image,exception);\n if (cmyk_image != (Image *) NULL)\n {\n pdf_image=DestroyImageList(pdf_image);\n pdf_image=cmyk_image;\n }\n }\n (void) SeekBlob(image,0,SEEK_SET);\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n /*\n Note document structuring comments.\n */\n *p++=(char) c;\n if ((strchr(\"\\n\\r%\",c) == (char *) NULL) &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *p='\\0';\n p=command;\n if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0)\n {\n StringInfo\n *profile;", " /*\n Read XMP profile.\n */\n p=command;\n profile=StringToStringInfo(command);\n for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++)\n {\n SetStringInfoLength(profile,(size_t) (i+1));\n c=ReadBlobByte(image);\n GetStringInfoDatum(profile)[i]=(unsigned char) c;\n *p++=(char) c;\n if ((strchr(\"\\n\\r%\",c) == (char *) NULL) &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *p='\\0';\n p=command;\n if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0)\n break;\n }\n SetStringInfoLength(profile,(size_t) i);\n (void) SetImageProfile(image,\"xmp\",profile,exception);\n profile=DestroyStringInfo(profile);\n continue;\n }\n }\n (void) CloseBlob(image);\n if (image_info->number_scenes != 0)\n {\n Image\n *clone_image;", " /*\n Add place holder images to meet the subimage specification requirement.\n */\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception);\n if (clone_image != (Image *) NULL)\n PrependImageToList(&pdf_image,clone_image);\n }\n }\n do\n {\n (void) CopyMagickString(pdf_image->filename,filename,MagickPathExtent);\n (void) CopyMagickString(pdf_image->magick,image->magick,MagickPathExtent);\n pdf_image->page=page;\n (void) CloneImageProfiles(pdf_image,image);\n (void) CloneImageProperties(pdf_image,image);\n next=SyncNextImageInList(pdf_image);\n if (next != (Image *) NULL)\n pdf_image=next;\n } while (next != (Image *) NULL);\n image=DestroyImage(image);\n scene=0;\n for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; )\n {\n next->scene=scene++;\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(pdf_image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% RegisterPDFImage() adds properties for the PDF image format to\n% the list of supported formats. The properties include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterPDFImage method is:\n%\n% size_t RegisterPDFImage(void)\n%\n*/\nModuleExport size_t RegisterPDFImage(void)\n{\n MagickInfo\n *entry;", " entry=AcquireMagickInfo(\"PDF\",\"AI\",\"Adobe Illustrator CS2\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->flags^=CoderAdjoinFlag;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PDF\",\"EPDF\",\n \"Encapsulated Portable Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->flags^=CoderAdjoinFlag;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PDF\",\"PDF\",\"Portable Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->magick=(IsImageFormatHandler *) IsPDF;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PDF\",\"PDFA\",\"Portable Document Archive Format\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->magick=(IsImageFormatHandler *) IsPDF;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% UnregisterPDFImage() removes format registrations made by the\n% PDF module from the list of supported formats.\n%\n% The format of the UnregisterPDFImage method is:\n%\n% UnregisterPDFImage(void)\n%\n*/\nModuleExport void UnregisterPDFImage(void)\n{\n (void) UnregisterMagickInfo(\"AI\");\n (void) UnregisterMagickInfo(\"EPDF\");\n (void) UnregisterMagickInfo(\"PDF\");\n (void) UnregisterMagickInfo(\"PDFA\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% WritePDFImage() writes an image in the Portable Document image\n% format.\n%\n% The format of the WritePDFImage method is:\n%\n% MagickBooleanType WritePDFImage(const ImageInfo *image_info,\n% Image *image,ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: the image info.\n%\n% o image: The image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static char *EscapeParenthesis(const char *source)\n{\n char\n *destination;", " register char\n *q;", " register const char\n *p;", " size_t\n length;", " assert(source != (const char *) NULL);\n length=0;\n for (p=source; *p != '\\0'; p++)\n {\n if ((*p == '\\\\') || (*p == '(') || (*p == ')'))\n {\n if (~length < 1)\n ThrowFatalException(ResourceLimitFatalError,\"UnableToEscapeString\");\n length++;\n }\n length++;\n }\n destination=(char *) NULL;\n if (~length >= (MagickPathExtent-1))\n destination=(char *) AcquireQuantumMemory(length+MagickPathExtent,\n sizeof(*destination));\n if (destination == (char *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"UnableToEscapeString\");\n *destination='\\0';\n q=destination;\n for (p=source; *p != '\\0'; p++)\n {\n if ((*p == '\\\\') || (*p == '(') || (*p == ')'))\n *q++='\\\\';\n *q++=(*p);\n }\n *q='\\0';\n return(destination);\n}", "static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16)\n{\n register const unsigned char\n *p;", " if (utf16 != (wchar_t *) NULL)\n {\n register wchar_t\n *q;", " wchar_t\n c;", " /*\n Convert UTF-8 to UTF-16.\n */\n q=utf16;\n for (p=utf8; *p != '\\0'; p++)\n {\n if ((*p & 0x80) == 0)\n *q=(*p);\n else\n if ((*p & 0xE0) == 0xC0)\n {\n c=(*p);\n *q=(c & 0x1F) << 6;\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n *q|=(*p & 0x3F);\n }\n else\n if ((*p & 0xF0) == 0xE0)\n {\n c=(*p);\n *q=c << 12;\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n c=(*p);\n *q|=(c & 0x3F) << 6;\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n *q|=(*p & 0x3F);\n }\n else\n return(0);\n q++;\n }\n *q++=(wchar_t) '\\0';\n return((size_t) (q-utf16));\n }\n /*\n Compute UTF-16 string length.\n */\n for (p=utf8; *p != '\\0'; p++)\n {\n if ((*p & 0x80) == 0)\n ;\n else\n if ((*p & 0xE0) == 0xC0)\n {\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n }\n else\n if ((*p & 0xF0) == 0xE0)\n {\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n }\n else\n return(0);\n }\n return((size_t) (p-utf8));\n}", "static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source,size_t *length)\n{\n wchar_t\n *utf16;", " *length=UTF8ToUTF16(source,(wchar_t *) NULL);\n if (*length == 0)\n {\n register ssize_t\n i;", " /*\n Not UTF-8, just copy.\n */\n *length=strlen((const char *) source);\n utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16));\n if (utf16 == (wchar_t *) NULL)\n return((wchar_t *) NULL);\n for (i=0; i <= (ssize_t) *length; i++)\n utf16[i]=source[i];\n return(utf16);\n }\n utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16));\n if (utf16 == (wchar_t *) NULL)\n return((wchar_t *) NULL);\n *length=UTF8ToUTF16(source,utf16);\n return(utf16);\n}", "static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,\n Image *image,Image *inject_image,ExceptionInfo *exception)\n{\n Image\n *group4_image;", " ImageInfo\n *write_info;", " MagickBooleanType\n status;", " size_t\n length;", " unsigned char\n *group4;", " status=MagickTrue;\n write_info=CloneImageInfo(image_info);\n (void) CopyMagickString(write_info->filename,\"GROUP4:\",MagickPathExtent);\n (void) CopyMagickString(write_info->magick,\"GROUP4\",MagickPathExtent);\n group4_image=CloneImage(inject_image,0,0,MagickTrue,exception);\n if (group4_image == (Image *) NULL)\n return(MagickFalse);\n group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,\n exception);\n group4_image=DestroyImage(group4_image);\n if (group4 == (unsigned char *) NULL)\n return(MagickFalse);\n write_info=DestroyImageInfo(write_info);\n if (WriteBlob(image,length,group4) != (ssize_t) length)\n status=MagickFalse;\n group4=(unsigned char *) RelinquishMagickMemory(group4);\n return(status);\n}", "static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n#define CFormat \"/Filter [ /%s ]\\n\"\n#define ObjectsPerImage 14\n#define ThrowPDFException(exception,message) \\\n{ \\\n if (xref != (MagickOffsetType *) NULL) \\\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\\n ThrowWriterException((exception),(message)); \\\n}", "DisableMSCWarning(4310)\n static const char\n XMPProfile[]=\n {\n \"<?xpacket begin=\\\"%s\\\" id=\\\"W5M0MpCehiHzreSzNTczkc9d\\\"?>\\n\"\n \"<x:xmpmeta xmlns:x=\\\"adobe:ns:meta/\\\" x:xmptk=\\\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\\\">\\n\"\n \" <rdf:RDF xmlns:rdf=\\\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\\\">\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:xap=\\\"http://ns.adobe.com/xap/1.0/\\\">\\n\"\n \" <xap:ModifyDate>%s</xap:ModifyDate>\\n\"\n \" <xap:CreateDate>%s</xap:CreateDate>\\n\"\n \" <xap:MetadataDate>%s</xap:MetadataDate>\\n\"\n \" <xap:CreatorTool>%s</xap:CreatorTool>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:dc=\\\"http://purl.org/dc/elements/1.1/\\\">\\n\"\n \" <dc:format>application/pdf</dc:format>\\n\"\n \" <dc:title>\\n\"\n \" <rdf:Alt>\\n\"\n \" <rdf:li xml:lang=\\\"x-default\\\">%s</rdf:li>\\n\"\n \" </rdf:Alt>\\n\"\n \" </dc:title>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:xapMM=\\\"http://ns.adobe.com/xap/1.0/mm/\\\">\\n\"\n \" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\\n\"\n \" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:pdf=\\\"http://ns.adobe.com/pdf/1.3/\\\">\\n\"\n \" <pdf:Producer>%s</pdf:Producer>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:pdfaid=\\\"http://www.aiim.org/pdfa/ns/id/\\\">\\n\"\n \" <pdfaid:part>3</pdfaid:part>\\n\"\n \" <pdfaid:conformance>B</pdfaid:conformance>\\n\"\n \" </rdf:Description>\\n\"\n \" </rdf:RDF>\\n\"\n \"</x:xmpmeta>\\n\"\n \"<?xpacket end=\\\"w\\\"?>\\n\"\n },\n XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };\nRestoreMSCWarning", " char\n basename[MagickPathExtent],\n buffer[MagickPathExtent],\n *escape,\n date[MagickPathExtent],\n **labels,\n page_geometry[MagickPathExtent],\n *url;", " CompressionType\n compression;", " const char\n *device,\n *option,\n *value;", " const StringInfo\n *profile;", " double\n pointsize;", " GeometryInfo\n geometry_info;", " Image\n *next,\n *tile_image;", " MagickBooleanType\n status;", " MagickOffsetType\n offset,\n scene,\n *xref;", " MagickSizeType\n number_pixels;", " MagickStatusType\n flags;", " PointInfo\n delta,\n resolution,\n scale;", " RectangleInfo\n geometry,\n media_info,\n page_info;", " register const Quantum\n *p;", " register unsigned char\n *q;", " register ssize_t\n i,\n x;", " size_t\n channels,\n imageListLength,\n info_id,\n length,\n object,\n pages_id,\n root_id,\n text_size,\n version;", " ssize_t\n count,\n page_count,\n y;", " struct tm\n local_time;", " time_t\n seconds;", " unsigned char\n *pixels;", " /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n /*\n Allocate X ref memory.\n */\n xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(xref,0,2048UL*sizeof(*xref));\n /*\n Write Info object.\n */\n object=0;\n version=3;\n if (image_info->compression == JPEG2000Compression)\n version=(size_t) MagickMax(version,5);\n for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))\n if (next->alpha_trait != UndefinedPixelTrait)\n version=(size_t) MagickMax(version,4);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n version=(size_t) MagickMax(version,6);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (StringInfo *) NULL)\n version=(size_t) MagickMax(version,7);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double)\n version);\n (void) WriteBlobString(image,buffer);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n (void) WriteBlobByte(image,'%');\n (void) WriteBlobByte(image,0xe2);\n (void) WriteBlobByte(image,0xe3);\n (void) WriteBlobByte(image,0xcf);\n (void) WriteBlobByte(image,0xd3);\n (void) WriteBlobByte(image,'\\n');\n }\n /*\n Write Catalog object.\n */\n xref[object++]=TellBlob(image);\n root_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (LocaleCompare(image_info->magick,\"PDFA\") != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+1);\n else\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Metadata %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+2);\n }\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Catalog\");\n option=GetImageOption(image_info,\"pdf:page-direction\");\n if ((option != (const char *) NULL) &&\n (LocaleCompare(option,\"right-to-left\") == 0))\n (void) WriteBlobString(image,\"/ViewerPreferences<</PageDirection/R2L>>\\n\");\n (void) WriteBlobString(image,\"\\n\");\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n GetPathComponent(image->filename,BasePath,basename);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n char\n create_date[MagickPathExtent],\n modify_date[MagickPathExtent],\n timestamp[MagickPathExtent],\n *url,\n xmp_profile[MagickPathExtent];", " /*\n Write XMP object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Subtype /XML\\n\");\n *modify_date='\\0';\n value=GetImageProperty(image,\"date:modify\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(modify_date,value,MagickPathExtent);\n *create_date='\\0';\n value=GetImageProperty(image,\"date:create\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(create_date,value,MagickPathExtent);\n (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);\n url=(char *) MagickAuthoritativeURL;\n escape=EscapeParenthesis(basename);\n i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,\n XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);\n escape=DestroyString(escape);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g\\n\",\n (double) i);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Metadata\\n\");\n (void) WriteBlobString(image,\">>\\nstream\\n\");\n (void) WriteBlobString(image,xmp_profile);\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n }\n /*\n Write Pages object.\n */\n xref[object++]=TellBlob(image);\n pages_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Pages\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Kids [ %.20g 0 R \",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n count=(ssize_t) (pages_id+ObjectsPerImage+1);\n page_count=1;\n if (image_info->adjoin != MagickFalse)\n {\n Image\n *kid_image;", " /*\n Predict page object id's.\n */\n kid_image=image;\n for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)\n {\n page_count++;\n profile=GetImageProfile(kid_image,\"icc\");\n if (profile != (StringInfo *) NULL)\n count+=2;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double)\n count);\n (void) WriteBlobString(image,buffer);\n kid_image=GetNextImageInList(kid_image);\n }\n xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,\n sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n (void) WriteBlobString(image,\"]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Count %.20g\\n\",(double)\n page_count);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n MagickBooleanType\n has_icc_profile;", " profile=GetImageProfile(image,\"icc\");\n has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if ((SetImageMonochrome(image,exception) == MagickFalse) ||\n (image->alpha_trait != UndefinedPixelTrait))\n compression=RLECompression;\n break;\n }\n#if !defined(MAGICKCORE_JPEG_DELEGATE)\n case JPEGCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)\n case JPEG2000Compression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_ZLIB_DELEGATE)\n case ZipCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\",\n image->filename);\n break;\n }\n#endif\n case LZWCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* LZW compression is forbidden */\n break;\n }\n case NoCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* ASCII 85 compression is forbidden */\n break;\n }\n default:\n break;\n }\n if (compression == JPEG2000Compression)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Scale relative to dots-per-inch.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n resolution.x=image->resolution.x;\n resolution.y=image->resolution.y;\n if ((resolution.x == 0.0) || (resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image->units == PixelsPerCentimeterResolution)\n {\n resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);\n resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);\n }\n SetGeometry(image,&geometry);\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\",\n (double) image->columns,(double) image->rows);\n if (image_info->page != (char *) NULL)\n (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);\n else\n if ((image->page.width != 0) && (image->page.height != 0))\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double)\n image->page.height,(double) image->page.x,(double) image->page.y);\n else\n if ((image->gravity != UndefinedGravity) &&\n (LocaleCompare(image_info->magick,\"PDF\") == 0))\n (void) CopyMagickString(page_geometry,PSPageGeometry,\n MagickPathExtent);\n (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent);\n (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n scale.x=(double) (geometry.width*delta.x)/resolution.x;\n geometry.width=(size_t) floor(scale.x+0.5);\n scale.y=(double) (geometry.height*delta.y)/resolution.y;\n geometry.height=(size_t) floor(scale.y+0.5);\n (void) ParseAbsoluteGeometry(page_geometry,&media_info);\n (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);\n if (image->gravity != UndefinedGravity)\n {\n geometry.x=(-page_info.x);\n geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);\n }\n pointsize=12.0;\n if (image_info->pointsize != 0.0)\n pointsize=image_info->pointsize;\n text_size=0;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n text_size=(size_t) (MultilineCensus(value)*pointsize+12);\n (void) text_size;\n /*\n Write Page object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Page\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Parent %.20g 0 R\\n\",\n (double) pages_id);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Resources <<\\n\");\n labels=(char **) NULL;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n labels=StringToList(value);\n if (labels != (char **) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/Font << /F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+4);\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/XObject << /Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+5);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ProcSet %.20g 0 R >>\\n\",\n (double) object+3);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/CropBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Contents %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Thumb %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 10 : 8));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Contents object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n (void) WriteBlobString(image,\"q\\n\");\n if (labels != (char **) NULL)\n for (i=0; labels[i] != (char *) NULL; i++)\n {\n (void) WriteBlobString(image,\"BT\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/F%.20g %g Tf\\n\",\n (double) image->scene,pointsize);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\",\n (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+\n 12));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\",\n labels[i]);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"ET\\n\");\n labels[i]=DestroyString(labels[i]);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x,\n (double) geometry.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Im%.20g Do\\n\",(double)\n image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"Q\\n\");\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Procset object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n if ((image->storage_class == DirectClass) || (image->colors > 256))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageC\",MagickPathExtent);\n else\n if ((compression == FaxCompression) || (compression == Group4Compression))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageB\",MagickPathExtent);\n else\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageI\",MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\" ]\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Font object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (labels != (char **) NULL)\n {\n (void) WriteBlobString(image,\"/Type /Font\\n\");\n (void) WriteBlobString(image,\"/Subtype /Type1\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /F%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/BaseFont /Helvetica\\n\");\n (void) WriteBlobString(image,\"/Encoding /MacRomanEncoding\\n\");\n labels=(char **) RelinquishMagickMemory(labels);\n }\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write XObject object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Im%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) image->columns,(double) image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object+2);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/SMask %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 9 : 7));\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((compression == FaxCompression) || (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,image,exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(image,p))));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)", " {\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }", " pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runoffset encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n if (image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)", " {\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n ThrowPDFException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }", " pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(image,p);\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Colorspace object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n device=\"DeviceRGB\";\n channels=0;\n if (image->colorspace == CMYKColorspace)\n {\n device=\"DeviceCMYK\";\n channels=4;\n }\n else\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n device=\"DeviceGray\";\n channels=1;\n }\n else\n if ((image->storage_class == DirectClass) ||\n (image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n {\n device=\"DeviceRGB\";\n channels=3;\n }\n profile=GetImageProfile(image,\"icc\");\n if ((profile == (StringInfo *) NULL) || (channels == 0))\n {\n if (channels != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/%s\\n\",device);\n else\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[ /Indexed /%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors-\n 1,(double) object+3);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n const unsigned char\n *p;", " /*\n Write ICC profile. \n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[/ICCBased %.20g 0 R]\\n\",(double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n/N %.20g\\n\"\n \"/Filter /ASCII85Decode\\n/Length %.20g 0 R\\n/Alternate /%s\\n>>\\n\"\n \"stream\\n\",(double) channels,(double) object+1,device);\n (void) WriteBlobString(image,buffer);\n offset=TellBlob(image);\n Ascii85Initialize(image);\n p=GetStringInfoDatum(profile);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)\n Ascii85Encode(image,(unsigned char) *p++);\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"endstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Thumb object.\n */\n SetGeometry(image,&geometry);\n (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);\n if (tile_image == (Image *) NULL)\n return(MagickFalse);\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) tile_image->columns,(double) tile_image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n tile_image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n tile_image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object-(has_icc_profile != MagickFalse ? 3 : 1));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(tile_image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,tile_image,\n exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,tile_image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(\n tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(tile_image,p))));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((tile_image->storage_class == DirectClass) ||\n (tile_image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));\n if (tile_image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelRed(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelGreen(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlue(tile_image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowPDFException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(tile_image,p);\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char)\n GetPixelIndex(tile_image,p));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n tile_image=DestroyImage(tile_image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == FaxCompression) || (compression == Group4Compression))\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n /*\n Write Colormap object.\n */\n if (compression == NoCompression)\n (void) WriteBlobString(image,\"/Filter [ /ASCII85Decode ]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n if (compression == NoCompression)\n Ascii85Initialize(image);\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (compression == NoCompression)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].red)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].green)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].blue)));\n continue;\n }\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].red)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].green)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].blue)));\n }\n if (compression == NoCompression)\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write softmask object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Ma%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",\n (double) image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",\n (double) image->rows);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/ColorSpace /DeviceGray\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/BitsPerComponent %d\\n\",(compression == FaxCompression) ||\n (compression == Group4Compression) ? 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n image=DestroyImage(image);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", "", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n /*\n Write Metadata object.\n */\n xref[object++]=TellBlob(image);\n info_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (%s)\\n\",\n EscapeParenthesis(basename));\n else\n {\n wchar_t\n *utf16;", " utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);\n if (utf16 != (wchar_t *) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (\\xfe\\xff\");\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) length; i++)\n (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);\n (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\");\n utf16=(wchar_t *) RelinquishMagickMemory(utf16);\n }\n }\n (void) WriteBlobString(image,buffer);\n seconds=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(&seconds,&local_time);\n#else\n (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));\n#endif\n (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\",\n local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,\n local_time.tm_hour,local_time.tm_min,local_time.tm_sec);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/CreationDate (%s)\\n\",\n date);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ModDate (%s)\\n\",date);\n (void) WriteBlobString(image,buffer);\n url=(char *) MagickAuthoritativeURL;\n escape=EscapeParenthesis(url);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Producer (%s)\\n\",escape);\n escape=DestroyString(escape);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Xref object.\n */\n offset=TellBlob(image)-xref[0]+\n (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10;\n (void) WriteBlobString(image,\"xref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"0000000000 65535 f \\n\");\n for (i=0; i < (ssize_t) object; i++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\",\n (unsigned long) xref[i]);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"trailer\\n\");\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Size %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Info %.20g 0 R\\n\",(double)\n info_id);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Root %.20g 0 R\\n\",(double)\n root_id);\n (void) WriteBlobString(image,buffer);\n (void) SignatureImage(image,exception);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ID [<%s> <%s>]\\n\",\n GetImageProperty(image,\"signature\",exception),\n GetImageProperty(image,\"signature\",exception));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"startxref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"%%EOF\\n\");\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n (void) CloseBlob(image);\n return(MagickTrue);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2904], "buggy_code_start_loc": [1912], "filenames": ["coders/pdf.c"], "fixing_code_end_loc": [2913], "fixing_code_start_loc": [1913], "message": "In ImageMagick before 7.0.8-25 and GraphicsMagick through 1.3.31, several memory leaks exist in WritePDFImage in coders/pdf.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "E982CE9C-89F7-4A5D-B036-A9A483493D5B", "versionEndExcluding": "6.9.10-25", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F7DF2A1-ADDE-48C4-BD39-CCA15D0D767A", "versionEndExcluding": "7.0.8-25", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.0-0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:graphicsmagick:graphicsmagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "DA564A9F-4001-4846-A8BB-EAD95674C890", "versionEndExcluding": null, "versionEndIncluding": "1.3.31", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.10:*:*:*:*:*:*:*", "matchCriteriaId": "07C312A0-CD2C-4B9C-B064-6409B25C278F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:19.04:*:*:*:*:*:*:*", "matchCriteriaId": "CD783B0C-9246-47D9-A937-6144FE8BFF0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In ImageMagick before 7.0.8-25 and GraphicsMagick through 1.3.31, several memory leaks exist in WritePDFImage in coders/pdf.c."}, {"lang": "es", "value": "En ImageMagick, en versiones anteriores a la 7.0.8-25, y GraphicsMagick, hasta la versi\u00f3n 1.3.31, existen varias vulnerabilidades de fuga de memoria en WritePDFImage en coders/pdf.c."}], "evaluatorComment": null, "id": "CVE-2019-7397", "lastModified": "2021-04-28T17:30:09.007", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-02-05T00:29:00.510", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "http://hg.graphicsmagick.org/hg/GraphicsMagick/rev/11ad3aeb8ab1"}, {"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-04/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-05/msg00006.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/106847"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/306c1f0fa5754ca78efd16ab752f0e981d4f6b82"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/issues/1454"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4034-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2020/dsa-4712"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-401"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/306c1f0fa5754ca78efd16ab752f0e981d4f6b82"}, "type": "CWE-401"}
30
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% PPPP DDDD FFFFF %\n% P P D D F %\n% PPPP D D FFF %\n% P D D F %\n% P DDDD F %\n% %\n% %\n% Read/Write Portable Document Format %\n% %\n% Software Design %\n% Cristy %\n% July 1992 %\n% %\n% %\n% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %\n% dedicated to making software imaging solutions freely available. %\n% %\n% You may not use this file except in compliance with the License. You may %\n% obtain a copy of the License at %\n% %\n% https://imagemagick.org/script/license.php %\n% %\n% Unless required by applicable law or agreed to in writing, software %\n% distributed under the License is distributed on an \"AS IS\" BASIS, %\n% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %\n% See the License for the specific language governing permissions and %\n% limitations under the License. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\n*/\n\f\n/*\n Include declarations.\n*/\n#include \"MagickCore/studio.h\"\n#include \"MagickCore/attribute.h\"\n#include \"MagickCore/artifact.h\"\n#include \"MagickCore/blob.h\"\n#include \"MagickCore/blob-private.h\"\n#include \"MagickCore/cache.h\"\n#include \"MagickCore/color.h\"\n#include \"MagickCore/color-private.h\"\n#include \"MagickCore/colorspace.h\"\n#include \"MagickCore/colorspace-private.h\"\n#include \"MagickCore/compress.h\"\n#include \"MagickCore/constitute.h\"\n#include \"MagickCore/delegate.h\"\n#include \"MagickCore/delegate-private.h\"\n#include \"MagickCore/draw.h\"\n#include \"MagickCore/exception.h\"\n#include \"MagickCore/exception-private.h\"\n#include \"MagickCore/geometry.h\"\n#include \"MagickCore/image.h\"\n#include \"MagickCore/image-private.h\"\n#include \"MagickCore/list.h\"\n#include \"MagickCore/magick.h\"\n#include \"MagickCore/memory_.h\"\n#include \"MagickCore/monitor.h\"\n#include \"MagickCore/monitor-private.h\"\n#include \"MagickCore/nt-base-private.h\"\n#include \"MagickCore/option.h\"\n#include \"MagickCore/pixel-accessor.h\"\n#include \"MagickCore/profile.h\"\n#include \"MagickCore/property.h\"\n#include \"MagickCore/quantum-private.h\"\n#include \"MagickCore/resource_.h\"\n#include \"MagickCore/resize.h\"\n#include \"MagickCore/signature.h\"\n#include \"MagickCore/static.h\"\n#include \"MagickCore/string_.h\"\n#include \"MagickCore/module.h\"\n#include \"MagickCore/token.h\"\n#include \"MagickCore/transform.h\"\n#include \"MagickCore/utility.h\"\n#include \"MagickCore/module.h\"\n\f\n/*\n Define declarations.\n*/\n#if defined(MAGICKCORE_TIFF_DELEGATE)\n#define CCITTParam \"-1\"\n#else\n#define CCITTParam \"0\"\n#endif\n\f\n/*\n Forward declarations.\n*/\nstatic MagickBooleanType\n WritePDFImage(const ImageInfo *,Image *,ExceptionInfo *);\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I n v o k e P D F D e l e g a t e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% InvokePDFDelegate() executes the PDF interpreter with the specified command.\n%\n% The format of the InvokePDFDelegate method is:\n%\n% MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose,\n% const char *command,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o verbose: A value other than zero displays the command prior to\n% executing it.\n%\n% o command: the address of a character string containing the command to\n% execute.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/\n#if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT)\nstatic int MagickDLLCall PDFDelegateMessage(void *handle,const char *message,\n int length)\n{\n char\n **messages;", " ssize_t\n offset;", " offset=0;\n messages=(char **) handle;\n if (*messages == (char *) NULL)\n *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *));\n else\n {\n offset=strlen(*messages);\n *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1,\n sizeof(char *));\n }\n if (*messages == (char *) NULL)\n return(0);\n (void) memcpy(*messages+offset,message,length);\n (*messages)[length+offset] ='\\0';\n return(length);\n}\n#endif", "static MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose,\n const char *command,char *message,ExceptionInfo *exception)\n{\n int\n status;", "#define ExecuteGhostscriptCommand(command,status) \\\n{ \\\n status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \\\n exception); \\\n if (status == 0) \\\n return(MagickTrue); \\\n if (status < 0) \\\n return(MagickFalse); \\\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \\\n \"FailedToExecuteCommand\",\"`%s' (%d)\",command,status); \\\n return(MagickFalse); \\\n}", "#if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT)\n#define SetArgsStart(command,args_start) \\\n if (args_start == (const char *) NULL) \\\n { \\\n if (*command != '\"') \\\n args_start=strchr(command,' '); \\\n else \\\n { \\\n args_start=strchr(command+1,'\"'); \\\n if (args_start != (const char *) NULL) \\\n args_start++; \\\n } \\\n }", " char\n **argv,\n *errors;", " const char\n *args_start = (const char *) NULL;", " const GhostInfo\n *ghost_info;", " gs_main_instance\n *interpreter;", " gsapi_revision_t\n revision;", " int\n argc,\n code;", " register ssize_t\n i;", "#if defined(MAGICKCORE_WINDOWS_SUPPORT)\n ghost_info=NTGhostscriptDLLVectors();\n#else\n GhostInfo\n ghost_info_struct;", " ghost_info=(&ghost_info_struct);\n (void) memset(&ghost_info_struct,0,sizeof(ghost_info_struct));\n ghost_info_struct.delete_instance=(void (*)(gs_main_instance *))\n gsapi_delete_instance;\n ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit;\n ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *))\n gsapi_new_instance;\n ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **))\n gsapi_init_with_args;\n ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int,\n int *)) gsapi_run_string;\n ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int (*)(void *,char *,\n int),int (*)(void *,const char *,int),int (*)(void *, const char *, int)))\n gsapi_set_stdio;\n ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision;\n#endif\n if (ghost_info == (GhostInfo *) NULL)\n ExecuteGhostscriptCommand(command,status);\n if ((ghost_info->revision)(&revision,sizeof(revision)) != 0)\n revision.revision=0;\n if (verbose != MagickFalse)\n {\n (void) fprintf(stdout,\"[ghostscript library %.2f]\",(double)\n revision.revision/100.0);\n SetArgsStart(command,args_start);\n (void) fputs(args_start,stdout);\n }\n errors=(char *) NULL;\n status=(ghost_info->new_instance)(&interpreter,(void *) &errors);\n if (status < 0)\n ExecuteGhostscriptCommand(command,status);\n code=0;\n argv=StringToArgv(command,&argc);\n if (argv == (char **) NULL)\n {\n (ghost_info->delete_instance)(interpreter);\n return(MagickFalse);\n }\n (void) (ghost_info->set_stdio)(interpreter,(int (MagickDLLCall *)(void *,\n char *,int)) NULL,PDFDelegateMessage,PDFDelegateMessage);\n status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1);\n if (status == 0)\n status=(ghost_info->run_string)(interpreter,\"systemdict /start get exec\\n\",\n 0,&code);\n (ghost_info->exit)(interpreter);\n (ghost_info->delete_instance)(interpreter);\n for (i=0; i < (ssize_t) argc; i++)\n argv[i]=DestroyString(argv[i]);\n argv=(char **) RelinquishMagickMemory(argv);\n if (status != 0)\n {\n SetArgsStart(command,args_start);\n if (status == -101) /* quit */\n (void) FormatLocaleString(message,MagickPathExtent,\n \"[ghostscript library %.2f]%s: %s\",(double) revision.revision/100.0,\n args_start,errors);\n else\n {\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,\n \"PDFDelegateFailed\",\"`[ghostscript library %.2f]%s': %s\",(double)\n revision.revision/100.0,args_start,errors);\n if (errors != (char *) NULL)\n errors=DestroyString(errors);\n (void) LogMagickEvent(CoderEvent,GetMagickModule(),\n \"Ghostscript returns status %d, exit code %d\",status,code);\n return(MagickFalse);\n }\n }\n if (errors != (char *) NULL)\n errors=DestroyString(errors);\n return(MagickTrue);\n#else\n ExecuteGhostscriptCommand(command,status);\n#endif\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% I s P D F %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% IsPDF() returns MagickTrue if the image format type, identified by the\n% magick string, is PDF.\n%\n% The format of the IsPDF method is:\n%\n% MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset)\n%\n% A description of each parameter follows:\n%\n% o magick: compare image format pattern against these bytes.\n%\n% o offset: Specifies the offset of the magick string.\n%\n*/\nstatic MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset)\n{\n if (offset < 5)\n return(MagickFalse);\n if (LocaleNCompare((const char *) magick,\"%PDF-\",5) == 0)\n return(MagickTrue);\n return(MagickFalse);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e a d P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% ReadPDFImage() reads a Portable Document Format image file and\n% returns it. It allocates the memory necessary for the new Image structure\n% and returns a pointer to the new image.\n%\n% The format of the ReadPDFImage method is:\n%\n% Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)\n%\n% A description of each parameter follows:\n%\n% o image_info: the image info.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static MagickBooleanType IsPDFRendered(const char *path)\n{\n MagickBooleanType\n status;", " struct stat\n attributes;", " if ((path == (const char *) NULL) || (*path == '\\0'))\n return(MagickFalse);\n status=GetPathAttributes(path,&attributes);\n if ((status != MagickFalse) && S_ISREG(attributes.st_mode) &&\n (attributes.st_size > 0))\n return(MagickTrue);\n return(MagickFalse);\n}", "static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception)\n{\n#define BeginXMPPacket \"<?xpacket begin=\"\n#define CMYKProcessColor \"CMYKProcessColor\"\n#define CropBox \"CropBox\"\n#define DefaultCMYK \"DefaultCMYK\"\n#define DeviceCMYK \"DeviceCMYK\"\n#define EndXMPPacket \"<?xpacket end=\"\n#define MediaBox \"MediaBox\"\n#define RenderPostscriptText \"Rendering Postscript... \"\n#define PDFRotate \"Rotate\"\n#define SpotColor \"Separation\"\n#define TrimBox \"TrimBox\"\n#define PDFVersion \"PDF-\"", " char\n command[MagickPathExtent],\n *density,\n filename[MagickPathExtent],\n geometry[MagickPathExtent],\n input_filename[MagickPathExtent],\n message[MagickPathExtent],\n *options,\n postscript_filename[MagickPathExtent];", " const char\n *option;", " const DelegateInfo\n *delegate_info;", " double\n angle;", " GeometryInfo\n geometry_info;", " Image\n *image,\n *next,\n *pdf_image;", " ImageInfo\n *read_info;", " int\n c,\n file;", " MagickBooleanType\n cmyk,\n cropbox,\n fitPage,\n status,\n stop_on_error,\n trimbox;", " MagickStatusType\n flags;", " PointInfo\n delta;", " RectangleInfo\n bounding_box,\n page;", " register char\n *p;", " register ssize_t\n i;", " SegmentInfo\n bounds,\n hires_bounds;", " size_t\n scene,\n spotcolor;", " ssize_t\n count;", " assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n /*\n Open image file.\n */\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n status=AcquireUniqueSymbolicLink(image_info->filename,input_filename);\n if (status == MagickFalse)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n /*\n Set the page density.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n image->resolution.x=geometry_info.rho;\n image->resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n image->resolution.y=image->resolution.x;\n }\n (void) memset(&page,0,sizeof(page));\n (void) ParseAbsoluteGeometry(PSPageGeometry,&page);\n if (image_info->page != (char *) NULL)\n (void) ParseAbsoluteGeometry(image_info->page,&page);\n page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)-\n 0.5);\n page.height=(size_t) ceil((double) (page.height*image->resolution.y/delta.y)-\n 0.5);\n /*\n Determine page geometry from the PDF media box.\n */\n cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse;\n cropbox=IsStringTrue(GetImageOption(image_info,\"pdf:use-cropbox\"));\n stop_on_error=IsStringTrue(GetImageOption(image_info,\"pdf:stop-on-error\"));\n trimbox=IsStringTrue(GetImageOption(image_info,\"pdf:use-trimbox\"));\n count=0;\n spotcolor=0;\n (void) memset(&bounding_box,0,sizeof(bounding_box));\n (void) memset(&bounds,0,sizeof(bounds));\n (void) memset(&hires_bounds,0,sizeof(hires_bounds));\n (void) memset(command,0,sizeof(command));\n angle=0.0;\n p=command;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n /*\n Note PDF elements.\n */\n if (c == '\\n')\n c=' ';\n *p++=(char) c;\n if ((c != (int) '/') && (c != (int) '%') &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *(--p)='\\0';\n p=command;\n if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0)\n count=(ssize_t) sscanf(command,\"Rotate %lf\",&angle);\n /*\n Is this a CMYK document?\n */\n if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0)\n cmyk=MagickTrue;\n if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)\n {\n char\n name[MagickPathExtent],\n property[MagickPathExtent],\n *value;", " /*\n Note spot names.\n */\n (void) FormatLocaleString(property,MagickPathExtent,\n \"pdf:SpotColor-%.20g\",(double) spotcolor++);\n i=0;\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n if ((isspace(c) != 0) || (c == '/') || ((i+1) == MagickPathExtent))\n break;\n name[i++]=(char) c;\n }\n name[i]='\\0';\n value=ConstantString(name);\n (void) SubstituteString(&value,\"#20\",\" \");\n if (*value != '\\0')\n (void) SetImageProperty(image,property,value,exception);\n value=DestroyString(value);\n continue;\n }\n if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0)\n (void) SetImageProperty(image,\"pdf:Version\",command,exception);\n if (image_info->page != (char *) NULL)\n continue;\n count=0;\n if (cropbox != MagickFalse)\n {\n if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0)\n {\n /*\n Note region defined by crop box.\n */\n count=(ssize_t) sscanf(command,\"CropBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"CropBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n }\n else\n if (trimbox != MagickFalse)\n {\n if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0)\n {\n /*\n Note region defined by trim box.\n */\n count=(ssize_t) sscanf(command,\"TrimBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"TrimBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n }\n else\n if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0)\n {\n /*\n Note region defined by media box.\n */\n count=(ssize_t) sscanf(command,\"MediaBox [%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n if (count != 4)\n count=(ssize_t) sscanf(command,\"MediaBox[%lf %lf %lf %lf\",\n &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2);\n }\n if (count != 4)\n continue;\n if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) ||\n (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1)))\n continue;\n hires_bounds=bounds;\n }\n if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) &&\n (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon))\n {\n /*\n Set PDF render geometry.\n */\n (void) FormatLocaleString(geometry,MagickPathExtent,\"%gx%g%+.15g%+.15g\",\n hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1,\n hires_bounds.x1,hires_bounds.y1);\n (void) SetImageProperty(image,\"pdf:HiResBoundingBox\",geometry,exception);\n page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)*\n image->resolution.x/delta.x)-0.5);\n page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)*\n image->resolution.y/delta.y)-0.5);\n }\n fitPage=MagickFalse;\n option=GetImageOption(image_info,\"pdf:fit-page\");\n if (option != (char *) NULL)\n {\n char\n *page_geometry;", " page_geometry=GetPageGeometry(option);\n flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width,\n &page.height);\n page_geometry=DestroyString(page_geometry);\n if (flags == NoValue)\n {\n (void) ThrowMagickException(exception,GetMagickModule(),OptionError,\n \"InvalidGeometry\",\"`%s'\",option);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)\n -0.5);\n page.height=(size_t) ceil((double) (page.height*image->resolution.y/\n delta.y) -0.5);\n fitPage=MagickTrue;\n }\n if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0))\n {\n size_t\n swap;", " swap=page.width;\n page.width=page.height;\n page.height=swap;\n }\n if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse)\n cmyk=MagickFalse;\n /*\n Create Ghostscript control file.\n */\n file=AcquireUniqueFileResource(postscript_filename);\n if (file == -1)\n {\n ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\",\n image_info->filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n count=write(file,\" \",1);\n file=close(file)-1;\n /*\n Render Postscript with the Ghostscript delegate.\n */\n if (image_info->monochrome != MagickFalse)\n delegate_info=GetDelegateInfo(\"ps:mono\",(char *) NULL,exception);\n else\n if (cmyk != MagickFalse)\n delegate_info=GetDelegateInfo(\"ps:cmyk\",(char *) NULL,exception);\n else\n delegate_info=GetDelegateInfo(\"ps:alpha\",(char *) NULL,exception);\n if (delegate_info == (const DelegateInfo *) NULL)\n {\n (void) RelinquishUniqueFileResource(postscript_filename);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n density=AcquireString(\"\");\n options=AcquireString(\"\");\n (void) FormatLocaleString(density,MagickPathExtent,\"%gx%g\",\n image->resolution.x,image->resolution.y);\n if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse))\n (void) FormatLocaleString(options,MagickPathExtent,\"-g%.20gx%.20g \",(double)\n page.width,(double) page.height);\n if (fitPage != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dPSFitPage \",MagickPathExtent);\n if (cmyk != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseCIEColor \",MagickPathExtent);\n if (cropbox != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseCropBox \",MagickPathExtent);\n if (stop_on_error != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dPDFSTOPONERROR \",\n MagickPathExtent);\n if (trimbox != MagickFalse)\n (void) ConcatenateMagickString(options,\"-dUseTrimBox \",MagickPathExtent);\n option=GetImageOption(image_info,\"authenticate\");\n if (option != (char *) NULL)\n {\n char\n passphrase[MagickPathExtent];", " (void) FormatLocaleString(passphrase,MagickPathExtent,\n \"\\\"-sPDFPassword=%s\\\" \",option);\n (void) ConcatenateMagickString(options,passphrase,MagickPathExtent);\n }\n read_info=CloneImageInfo(image_info);\n *read_info->magick='\\0';\n if (read_info->number_scenes != 0)\n {\n char\n pages[MagickPathExtent];", " (void) FormatLocaleString(pages,MagickPathExtent,\"-dFirstPage=%.20g \"\n \"-dLastPage=%.20g\",(double) read_info->scene+1,(double)\n (read_info->scene+read_info->number_scenes));\n (void) ConcatenateMagickString(options,pages,MagickPathExtent);\n read_info->number_scenes=0;\n if (read_info->scenes != (char *) NULL)\n *read_info->scenes='\\0';\n }\n (void) CopyMagickString(filename,read_info->filename,MagickPathExtent);\n (void) AcquireUniqueFilename(filename);\n (void) RelinquishUniqueFileResource(filename);\n (void) ConcatenateMagickString(filename,\"%d\",MagickPathExtent);\n (void) FormatLocaleString(command,MagickPathExtent,\n GetDelegateCommands(delegate_info),\n read_info->antialias != MagickFalse ? 4 : 1,\n read_info->antialias != MagickFalse ? 4 : 1,density,options,filename,\n postscript_filename,input_filename);\n options=DestroyString(options);\n density=DestroyString(density);\n *message='\\0';\n status=InvokePDFDelegate(read_info->verbose,command,message,exception);\n (void) RelinquishUniqueFileResource(postscript_filename);\n (void) RelinquishUniqueFileResource(input_filename);\n pdf_image=(Image *) NULL;\n if (status == MagickFalse)\n for (i=1; ; i++)\n {\n (void) InterpretImageFilename(image_info,image,filename,(int) i,\n read_info->filename,exception);\n if (IsPDFRendered(read_info->filename) == MagickFalse)\n break;\n (void) RelinquishUniqueFileResource(read_info->filename);\n }\n else\n for (i=1; ; i++)\n {\n (void) InterpretImageFilename(image_info,image,filename,(int) i,\n read_info->filename,exception);\n if (IsPDFRendered(read_info->filename) == MagickFalse)\n break;\n read_info->blob=NULL;\n read_info->length=0;\n next=ReadImage(read_info,exception);\n (void) RelinquishUniqueFileResource(read_info->filename);\n if (next == (Image *) NULL)\n break;\n AppendImageToList(&pdf_image,next);\n }\n read_info=DestroyImageInfo(read_info);\n if (pdf_image == (Image *) NULL)\n {\n if (*message != '\\0')\n (void) ThrowMagickException(exception,GetMagickModule(),DelegateError,\n \"PDFDelegateFailed\",\"`%s'\",message);\n image=DestroyImage(image);\n return((Image *) NULL);\n }\n if (LocaleCompare(pdf_image->magick,\"BMP\") == 0)\n {\n Image\n *cmyk_image;", " cmyk_image=ConsolidateCMYKImages(pdf_image,exception);\n if (cmyk_image != (Image *) NULL)\n {\n pdf_image=DestroyImageList(pdf_image);\n pdf_image=cmyk_image;\n }\n }\n (void) SeekBlob(image,0,SEEK_SET);\n for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image))\n {\n /*\n Note document structuring comments.\n */\n *p++=(char) c;\n if ((strchr(\"\\n\\r%\",c) == (char *) NULL) &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *p='\\0';\n p=command;\n if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0)\n {\n StringInfo\n *profile;", " /*\n Read XMP profile.\n */\n p=command;\n profile=StringToStringInfo(command);\n for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++)\n {\n SetStringInfoLength(profile,(size_t) (i+1));\n c=ReadBlobByte(image);\n GetStringInfoDatum(profile)[i]=(unsigned char) c;\n *p++=(char) c;\n if ((strchr(\"\\n\\r%\",c) == (char *) NULL) &&\n ((size_t) (p-command) < (MagickPathExtent-1)))\n continue;\n *p='\\0';\n p=command;\n if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0)\n break;\n }\n SetStringInfoLength(profile,(size_t) i);\n (void) SetImageProfile(image,\"xmp\",profile,exception);\n profile=DestroyStringInfo(profile);\n continue;\n }\n }\n (void) CloseBlob(image);\n if (image_info->number_scenes != 0)\n {\n Image\n *clone_image;", " /*\n Add place holder images to meet the subimage specification requirement.\n */\n for (i=0; i < (ssize_t) image_info->scene; i++)\n {\n clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception);\n if (clone_image != (Image *) NULL)\n PrependImageToList(&pdf_image,clone_image);\n }\n }\n do\n {\n (void) CopyMagickString(pdf_image->filename,filename,MagickPathExtent);\n (void) CopyMagickString(pdf_image->magick,image->magick,MagickPathExtent);\n pdf_image->page=page;\n (void) CloneImageProfiles(pdf_image,image);\n (void) CloneImageProperties(pdf_image,image);\n next=SyncNextImageInList(pdf_image);\n if (next != (Image *) NULL)\n pdf_image=next;\n } while (next != (Image *) NULL);\n image=DestroyImage(image);\n scene=0;\n for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; )\n {\n next->scene=scene++;\n next=GetNextImageInList(next);\n }\n return(GetFirstImageInList(pdf_image));\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% R e g i s t e r P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% RegisterPDFImage() adds properties for the PDF image format to\n% the list of supported formats. The properties include the image format\n% tag, a method to read and/or write the format, whether the format\n% supports the saving of more than one frame to the same file or blob,\n% whether the format supports native in-memory I/O, and a brief\n% description of the format.\n%\n% The format of the RegisterPDFImage method is:\n%\n% size_t RegisterPDFImage(void)\n%\n*/\nModuleExport size_t RegisterPDFImage(void)\n{\n MagickInfo\n *entry;", " entry=AcquireMagickInfo(\"PDF\",\"AI\",\"Adobe Illustrator CS2\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->flags^=CoderAdjoinFlag;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PDF\",\"EPDF\",\n \"Encapsulated Portable Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->flags^=CoderAdjoinFlag;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PDF\",\"PDF\",\"Portable Document Format\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->magick=(IsImageFormatHandler *) IsPDF;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n entry=AcquireMagickInfo(\"PDF\",\"PDFA\",\"Portable Document Archive Format\");\n entry->decoder=(DecodeImageHandler *) ReadPDFImage;\n entry->encoder=(EncodeImageHandler *) WritePDFImage;\n entry->magick=(IsImageFormatHandler *) IsPDF;\n entry->flags^=CoderBlobSupportFlag;\n entry->mime_type=ConstantString(\"application/pdf\");\n (void) RegisterMagickInfo(entry);\n return(MagickImageCoderSignature);\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% U n r e g i s t e r P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% UnregisterPDFImage() removes format registrations made by the\n% PDF module from the list of supported formats.\n%\n% The format of the UnregisterPDFImage method is:\n%\n% UnregisterPDFImage(void)\n%\n*/\nModuleExport void UnregisterPDFImage(void)\n{\n (void) UnregisterMagickInfo(\"AI\");\n (void) UnregisterMagickInfo(\"EPDF\");\n (void) UnregisterMagickInfo(\"PDF\");\n (void) UnregisterMagickInfo(\"PDFA\");\n}\n\f\n/*\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% %\n% %\n% W r i t e P D F I m a g e %\n% %\n% %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n% WritePDFImage() writes an image in the Portable Document image\n% format.\n%\n% The format of the WritePDFImage method is:\n%\n% MagickBooleanType WritePDFImage(const ImageInfo *image_info,\n% Image *image,ExceptionInfo *exception)\n%\n% A description of each parameter follows.\n%\n% o image_info: the image info.\n%\n% o image: The image.\n%\n% o exception: return any errors or warnings in this structure.\n%\n*/", "static char *EscapeParenthesis(const char *source)\n{\n char\n *destination;", " register char\n *q;", " register const char\n *p;", " size_t\n length;", " assert(source != (const char *) NULL);\n length=0;\n for (p=source; *p != '\\0'; p++)\n {\n if ((*p == '\\\\') || (*p == '(') || (*p == ')'))\n {\n if (~length < 1)\n ThrowFatalException(ResourceLimitFatalError,\"UnableToEscapeString\");\n length++;\n }\n length++;\n }\n destination=(char *) NULL;\n if (~length >= (MagickPathExtent-1))\n destination=(char *) AcquireQuantumMemory(length+MagickPathExtent,\n sizeof(*destination));\n if (destination == (char *) NULL)\n ThrowFatalException(ResourceLimitFatalError,\"UnableToEscapeString\");\n *destination='\\0';\n q=destination;\n for (p=source; *p != '\\0'; p++)\n {\n if ((*p == '\\\\') || (*p == '(') || (*p == ')'))\n *q++='\\\\';\n *q++=(*p);\n }\n *q='\\0';\n return(destination);\n}", "static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16)\n{\n register const unsigned char\n *p;", " if (utf16 != (wchar_t *) NULL)\n {\n register wchar_t\n *q;", " wchar_t\n c;", " /*\n Convert UTF-8 to UTF-16.\n */\n q=utf16;\n for (p=utf8; *p != '\\0'; p++)\n {\n if ((*p & 0x80) == 0)\n *q=(*p);\n else\n if ((*p & 0xE0) == 0xC0)\n {\n c=(*p);\n *q=(c & 0x1F) << 6;\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n *q|=(*p & 0x3F);\n }\n else\n if ((*p & 0xF0) == 0xE0)\n {\n c=(*p);\n *q=c << 12;\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n c=(*p);\n *q|=(c & 0x3F) << 6;\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n *q|=(*p & 0x3F);\n }\n else\n return(0);\n q++;\n }\n *q++=(wchar_t) '\\0';\n return((size_t) (q-utf16));\n }\n /*\n Compute UTF-16 string length.\n */\n for (p=utf8; *p != '\\0'; p++)\n {\n if ((*p & 0x80) == 0)\n ;\n else\n if ((*p & 0xE0) == 0xC0)\n {\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n }\n else\n if ((*p & 0xF0) == 0xE0)\n {\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n p++;\n if ((*p & 0xC0) != 0x80)\n return(0);\n }\n else\n return(0);\n }\n return((size_t) (p-utf8));\n}", "static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source,size_t *length)\n{\n wchar_t\n *utf16;", " *length=UTF8ToUTF16(source,(wchar_t *) NULL);\n if (*length == 0)\n {\n register ssize_t\n i;", " /*\n Not UTF-8, just copy.\n */\n *length=strlen((const char *) source);\n utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16));\n if (utf16 == (wchar_t *) NULL)\n return((wchar_t *) NULL);\n for (i=0; i <= (ssize_t) *length; i++)\n utf16[i]=source[i];\n return(utf16);\n }\n utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16));\n if (utf16 == (wchar_t *) NULL)\n return((wchar_t *) NULL);\n *length=UTF8ToUTF16(source,utf16);\n return(utf16);\n}", "static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info,\n Image *image,Image *inject_image,ExceptionInfo *exception)\n{\n Image\n *group4_image;", " ImageInfo\n *write_info;", " MagickBooleanType\n status;", " size_t\n length;", " unsigned char\n *group4;", " status=MagickTrue;\n write_info=CloneImageInfo(image_info);\n (void) CopyMagickString(write_info->filename,\"GROUP4:\",MagickPathExtent);\n (void) CopyMagickString(write_info->magick,\"GROUP4\",MagickPathExtent);\n group4_image=CloneImage(inject_image,0,0,MagickTrue,exception);\n if (group4_image == (Image *) NULL)\n return(MagickFalse);\n group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,\n exception);\n group4_image=DestroyImage(group4_image);\n if (group4 == (unsigned char *) NULL)\n return(MagickFalse);\n write_info=DestroyImageInfo(write_info);\n if (WriteBlob(image,length,group4) != (ssize_t) length)\n status=MagickFalse;\n group4=(unsigned char *) RelinquishMagickMemory(group4);\n return(status);\n}", "static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image,\n ExceptionInfo *exception)\n{\n#define CFormat \"/Filter [ /%s ]\\n\"\n#define ObjectsPerImage 14\n#define ThrowPDFException(exception,message) \\\n{ \\\n if (xref != (MagickOffsetType *) NULL) \\\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\\n ThrowWriterException((exception),(message)); \\\n}", "DisableMSCWarning(4310)\n static const char\n XMPProfile[]=\n {\n \"<?xpacket begin=\\\"%s\\\" id=\\\"W5M0MpCehiHzreSzNTczkc9d\\\"?>\\n\"\n \"<x:xmpmeta xmlns:x=\\\"adobe:ns:meta/\\\" x:xmptk=\\\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\\\">\\n\"\n \" <rdf:RDF xmlns:rdf=\\\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\\\">\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:xap=\\\"http://ns.adobe.com/xap/1.0/\\\">\\n\"\n \" <xap:ModifyDate>%s</xap:ModifyDate>\\n\"\n \" <xap:CreateDate>%s</xap:CreateDate>\\n\"\n \" <xap:MetadataDate>%s</xap:MetadataDate>\\n\"\n \" <xap:CreatorTool>%s</xap:CreatorTool>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:dc=\\\"http://purl.org/dc/elements/1.1/\\\">\\n\"\n \" <dc:format>application/pdf</dc:format>\\n\"\n \" <dc:title>\\n\"\n \" <rdf:Alt>\\n\"\n \" <rdf:li xml:lang=\\\"x-default\\\">%s</rdf:li>\\n\"\n \" </rdf:Alt>\\n\"\n \" </dc:title>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:xapMM=\\\"http://ns.adobe.com/xap/1.0/mm/\\\">\\n\"\n \" <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\\n\"\n \" <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:pdf=\\\"http://ns.adobe.com/pdf/1.3/\\\">\\n\"\n \" <pdf:Producer>%s</pdf:Producer>\\n\"\n \" </rdf:Description>\\n\"\n \" <rdf:Description rdf:about=\\\"\\\"\\n\"\n \" xmlns:pdfaid=\\\"http://www.aiim.org/pdfa/ns/id/\\\">\\n\"\n \" <pdfaid:part>3</pdfaid:part>\\n\"\n \" <pdfaid:conformance>B</pdfaid:conformance>\\n\"\n \" </rdf:Description>\\n\"\n \" </rdf:RDF>\\n\"\n \"</x:xmpmeta>\\n\"\n \"<?xpacket end=\\\"w\\\"?>\\n\"\n },\n XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 };\nRestoreMSCWarning", " char\n basename[MagickPathExtent],\n buffer[MagickPathExtent],\n *escape,\n date[MagickPathExtent],\n **labels,\n page_geometry[MagickPathExtent],\n *url;", " CompressionType\n compression;", " const char\n *device,\n *option,\n *value;", " const StringInfo\n *profile;", " double\n pointsize;", " GeometryInfo\n geometry_info;", " Image\n *next,\n *tile_image;", " MagickBooleanType\n status;", " MagickOffsetType\n offset,\n scene,\n *xref;", " MagickSizeType\n number_pixels;", " MagickStatusType\n flags;", " PointInfo\n delta,\n resolution,\n scale;", " RectangleInfo\n geometry,\n media_info,\n page_info;", " register const Quantum\n *p;", " register unsigned char\n *q;", " register ssize_t\n i,\n x;", " size_t\n channels,\n imageListLength,\n info_id,\n length,\n object,\n pages_id,\n root_id,\n text_size,\n version;", " ssize_t\n count,\n page_count,\n y;", " struct tm\n local_time;", " time_t\n seconds;", " unsigned char\n *pixels;", " /*\n Open output image file.\n */\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);\n if (status == MagickFalse)\n return(status);\n /*\n Allocate X ref memory.\n */\n xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memset(xref,0,2048UL*sizeof(*xref));\n /*\n Write Info object.\n */\n object=0;\n version=3;\n if (image_info->compression == JPEG2000Compression)\n version=(size_t) MagickMax(version,5);\n for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))\n if (next->alpha_trait != UndefinedPixelTrait)\n version=(size_t) MagickMax(version,4);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n version=(size_t) MagickMax(version,6);\n profile=GetImageProfile(image,\"icc\");\n if (profile != (StringInfo *) NULL)\n version=(size_t) MagickMax(version,7);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double)\n version);\n (void) WriteBlobString(image,buffer);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n (void) WriteBlobByte(image,'%');\n (void) WriteBlobByte(image,0xe2);\n (void) WriteBlobByte(image,0xe3);\n (void) WriteBlobByte(image,0xcf);\n (void) WriteBlobByte(image,0xd3);\n (void) WriteBlobByte(image,'\\n');\n }\n /*\n Write Catalog object.\n */\n xref[object++]=TellBlob(image);\n root_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (LocaleCompare(image_info->magick,\"PDFA\") != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+1);\n else\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Metadata %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\",\n (double) object+2);\n }\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Catalog\");\n option=GetImageOption(image_info,\"pdf:page-direction\");\n if ((option != (const char *) NULL) &&\n (LocaleCompare(option,\"right-to-left\") == 0))\n (void) WriteBlobString(image,\"/ViewerPreferences<</PageDirection/R2L>>\\n\");\n (void) WriteBlobString(image,\"\\n\");\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n GetPathComponent(image->filename,BasePath,basename);\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n {\n char\n create_date[MagickPathExtent],\n modify_date[MagickPathExtent],\n timestamp[MagickPathExtent],\n *url,\n xmp_profile[MagickPathExtent];", " /*\n Write XMP object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Subtype /XML\\n\");\n *modify_date='\\0';\n value=GetImageProperty(image,\"date:modify\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(modify_date,value,MagickPathExtent);\n *create_date='\\0';\n value=GetImageProperty(image,\"date:create\",exception);\n if (value != (const char *) NULL)\n (void) CopyMagickString(create_date,value,MagickPathExtent);\n (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp);\n url=(char *) MagickAuthoritativeURL;\n escape=EscapeParenthesis(basename);\n i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile,\n XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url);\n escape=DestroyString(escape);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g\\n\",\n (double) i);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Type /Metadata\\n\");\n (void) WriteBlobString(image,\">>\\nstream\\n\");\n (void) WriteBlobString(image,xmp_profile);\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n }\n /*\n Write Pages object.\n */\n xref[object++]=TellBlob(image);\n pages_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Pages\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Kids [ %.20g 0 R \",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n count=(ssize_t) (pages_id+ObjectsPerImage+1);\n page_count=1;\n if (image_info->adjoin != MagickFalse)\n {\n Image\n *kid_image;", " /*\n Predict page object id's.\n */\n kid_image=image;\n for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage)\n {\n page_count++;\n profile=GetImageProfile(kid_image,\"icc\");\n if (profile != (StringInfo *) NULL)\n count+=2;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double)\n count);\n (void) WriteBlobString(image,buffer);\n kid_image=GetNextImageInList(kid_image);\n }\n xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL,\n sizeof(*xref));\n if (xref == (MagickOffsetType *) NULL)\n ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n (void) WriteBlobString(image,\"]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Count %.20g\\n\",(double)\n page_count);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n scene=0;\n imageListLength=GetImageListLength(image);\n do\n {\n MagickBooleanType\n has_icc_profile;", " profile=GetImageProfile(image,\"icc\");\n has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse;\n compression=image->compression;\n if (image_info->compression != UndefinedCompression)\n compression=image_info->compression;\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if ((SetImageMonochrome(image,exception) == MagickFalse) ||\n (image->alpha_trait != UndefinedPixelTrait))\n compression=RLECompression;\n break;\n }\n#if !defined(MAGICKCORE_JPEG_DELEGATE)\n case JPEGCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE)\n case JPEG2000Compression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\",\n image->filename);\n break;\n }\n#endif\n#if !defined(MAGICKCORE_ZLIB_DELEGATE)\n case ZipCompression:\n {\n compression=RLECompression;\n (void) ThrowMagickException(exception,GetMagickModule(),\n MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\",\n image->filename);\n break;\n }\n#endif\n case LZWCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* LZW compression is forbidden */\n break;\n }\n case NoCompression:\n {\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n compression=RLECompression; /* ASCII 85 compression is forbidden */\n break;\n }\n default:\n break;\n }\n if (compression == JPEG2000Compression)\n (void) TransformImageColorspace(image,sRGBColorspace,exception);\n /*\n Scale relative to dots-per-inch.\n */\n delta.x=DefaultResolution;\n delta.y=DefaultResolution;\n resolution.x=image->resolution.x;\n resolution.y=image->resolution.y;\n if ((resolution.x == 0.0) || (resolution.y == 0.0))\n {\n flags=ParseGeometry(PSDensityGeometry,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image_info->density != (char *) NULL)\n {\n flags=ParseGeometry(image_info->density,&geometry_info);\n resolution.x=geometry_info.rho;\n resolution.y=geometry_info.sigma;\n if ((flags & SigmaValue) == 0)\n resolution.y=resolution.x;\n }\n if (image->units == PixelsPerCentimeterResolution)\n {\n resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0);\n resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0);\n }\n SetGeometry(image,&geometry);\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\",\n (double) image->columns,(double) image->rows);\n if (image_info->page != (char *) NULL)\n (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent);\n else\n if ((image->page.width != 0) && (image->page.height != 0))\n (void) FormatLocaleString(page_geometry,MagickPathExtent,\n \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double)\n image->page.height,(double) image->page.x,(double) image->page.y);\n else\n if ((image->gravity != UndefinedGravity) &&\n (LocaleCompare(image_info->magick,\"PDF\") == 0))\n (void) CopyMagickString(page_geometry,PSPageGeometry,\n MagickPathExtent);\n (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent);\n (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n scale.x=(double) (geometry.width*delta.x)/resolution.x;\n geometry.width=(size_t) floor(scale.x+0.5);\n scale.y=(double) (geometry.height*delta.y)/resolution.y;\n geometry.height=(size_t) floor(scale.y+0.5);\n (void) ParseAbsoluteGeometry(page_geometry,&media_info);\n (void) ParseGravityGeometry(image,page_geometry,&page_info,exception);\n if (image->gravity != UndefinedGravity)\n {\n geometry.x=(-page_info.x);\n geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows);\n }\n pointsize=12.0;\n if (image_info->pointsize != 0.0)\n pointsize=image_info->pointsize;\n text_size=0;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n text_size=(size_t) (MultilineCensus(value)*pointsize+12);\n (void) text_size;\n /*\n Write Page object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /Page\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Parent %.20g 0 R\\n\",\n (double) pages_id);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/Resources <<\\n\");\n labels=(char **) NULL;\n value=GetImageProperty(image,\"label\",exception);\n if (value != (const char *) NULL)\n labels=StringToList(value);\n if (labels != (char **) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/Font << /F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+4);\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/XObject << /Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double)\n object+5);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ProcSet %.20g 0 R >>\\n\",\n (double) object+3);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/CropBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x,\n 72.0*media_info.height/resolution.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Contents %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Thumb %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 10 : 8));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Contents object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n (void) WriteBlobString(image,\"q\\n\");\n if (labels != (char **) NULL)\n for (i=0; labels[i] != (char *) NULL; i++)\n {\n (void) WriteBlobString(image,\"BT\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/F%.20g %g Tf\\n\",\n (double) image->scene,pointsize);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\",\n (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+\n 12));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\",\n labels[i]);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"ET\\n\");\n labels[i]=DestroyString(labels[i]);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x,\n (double) geometry.y);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Im%.20g Do\\n\",(double)\n image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"Q\\n\");\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Procset object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n if ((image->storage_class == DirectClass) || (image->colors > 256))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageC\",MagickPathExtent);\n else\n if ((compression == FaxCompression) || (compression == Group4Compression))\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageB\",MagickPathExtent);\n else\n (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageI\",MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\" ]\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Font object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (labels != (char **) NULL)\n {\n (void) WriteBlobString(image,\"/Type /Font\\n\");\n (void) WriteBlobString(image,\"/Subtype /Type1\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /F%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/BaseFont /Helvetica\\n\");\n (void) WriteBlobString(image,\"/Encoding /MacRomanEncoding\\n\");\n labels=(char **) RelinquishMagickMemory(labels);\n }\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write XObject object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Im%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) image->columns,(double) image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object+2);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n if (image->alpha_trait != UndefinedPixelTrait)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/SMask %.20g 0 R\\n\",\n (double) object+(has_icc_profile != MagickFalse ? 9 : 7));\n (void) WriteBlobString(image,buffer);\n }\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels)))\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n if ((compression == FaxCompression) || (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,image,exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(image,p))));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,image,\"jpeg\",exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,image,\"jp2\",exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)", " ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");", " pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runoffset encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(image,p));\n if (image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(image,p)));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)\n y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)", " ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");", " pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(image,p);\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p));\n p+=GetPixelChannels(image);\n }\n if (image->previous == (Image *) NULL)\n {\n status=SetImageProgress(image,SaveImageTag,\n (MagickOffsetType) y,image->rows);\n if (status == MagickFalse)\n break;\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Colorspace object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n device=\"DeviceRGB\";\n channels=0;\n if (image->colorspace == CMYKColorspace)\n {\n device=\"DeviceCMYK\";\n channels=4;\n }\n else\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(image,exception) != MagickFalse)))\n {\n device=\"DeviceGray\";\n channels=1;\n }\n else\n if ((image->storage_class == DirectClass) ||\n (image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n {\n device=\"DeviceRGB\";\n channels=3;\n }\n profile=GetImageProfile(image,\"icc\");\n if ((profile == (StringInfo *) NULL) || (channels == 0))\n {\n if (channels != 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/%s\\n\",device);\n else\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[ /Indexed /%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors-\n 1,(double) object+3);\n (void) WriteBlobString(image,buffer);\n }\n else\n {\n const unsigned char\n *p;", " /*\n Write ICC profile. \n */\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"[/ICCBased %.20g 0 R]\\n\",(double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n/N %.20g\\n\"\n \"/Filter /ASCII85Decode\\n/Length %.20g 0 R\\n/Alternate /%s\\n>>\\n\"\n \"stream\\n\",(double) channels,(double) object+1,device);\n (void) WriteBlobString(image,buffer);\n offset=TellBlob(image);\n Ascii85Initialize(image);\n p=GetStringInfoDatum(profile);\n for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++)\n Ascii85Encode(image,(unsigned char) *p++);\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"endstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",\n (double) object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Thumb object.\n */\n SetGeometry(image,&geometry);\n (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y,\n &geometry.width,&geometry.height);\n tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception);\n if (tile_image == (Image *) NULL)\n return(MagickFalse);\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case JPEGCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case JPEG2000Compression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\");\n if (image->colorspace != CMYKColorspace)\n break;\n (void) WriteBlobString(image,buffer);\n (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\",\n MagickPathExtent);\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n case FaxCompression:\n case Group4Compression:\n {\n (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\",\n MagickPathExtent);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \"\n \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam,\n (double) tile_image->columns,(double) tile_image->rows);\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double)\n tile_image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double)\n tile_image->rows);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\",\n (double) object-(has_icc_profile != MagickFalse ? 3 : 1));\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\",\n (compression == FaxCompression) || (compression == Group4Compression) ?\n 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows;\n if ((compression == FaxCompression) ||\n (compression == Group4Compression) ||\n ((image_info->type != TrueColorType) &&\n (SetImageGray(tile_image,exception) != MagickFalse)))\n {\n switch (compression)\n {\n case FaxCompression:\n case Group4Compression:\n {\n if (LocaleCompare(CCITTParam,\"0\") == 0)\n {\n (void) HuffmanEncodeImage(image_info,image,tile_image,\n exception);\n break;\n }\n (void) Huffman2DEncodeImage(image_info,image,tile_image,exception);\n break;\n }\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(\n tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n GetPixelLuma(tile_image,p))));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n else\n if ((tile_image->storage_class == DirectClass) ||\n (tile_image->colors > 256) || (compression == JPEGCompression) ||\n (compression == JPEG2000Compression))\n switch (compression)\n {\n case JPEGCompression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jpeg\",\n exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case JPEG2000Compression:\n {\n status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p));\n *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p));\n if (tile_image->colorspace == CMYKColorspace)\n *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p));\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed DirectColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelRed(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelGreen(tile_image,p)));\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlue(tile_image,p)));\n if (image->colorspace == CMYKColorspace)\n Ascii85Encode(image,ScaleQuantumToChar(\n GetPixelBlack(tile_image,p)));\n p+=GetPixelChannels(tile_image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n else\n {\n /*\n Dump number of colors and colormap.\n */\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n tile_image=DestroyImage(tile_image);\n ThrowPDFException(ResourceLimitError,\n \"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n *q++=(unsigned char) GetPixelIndex(tile_image,p);\n p+=GetPixelChannels(tile_image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) tile_image->rows; y++)\n {\n p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1,\n exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) tile_image->columns; x++)\n {\n Ascii85Encode(image,(unsigned char)\n GetPixelIndex(tile_image,p));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n }\n tile_image=DestroyImage(tile_image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if ((image->storage_class == DirectClass) || (image->colors > 256) ||\n (compression == FaxCompression) || (compression == Group4Compression))\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n /*\n Write Colormap object.\n */\n if (compression == NoCompression)\n (void) WriteBlobString(image,\"/Filter [ /ASCII85Decode ]\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n if (compression == NoCompression)\n Ascii85Initialize(image);\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n if (compression == NoCompression)\n {\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].red)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].green)));\n Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum(\n image->colormap[i].blue)));\n continue;\n }\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].red)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].green)));\n (void) WriteBlobByte(image,ScaleQuantumToChar(\n ClampToQuantum(image->colormap[i].blue)));\n }\n if (compression == NoCompression)\n Ascii85Flush(image);\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write softmask object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (image->alpha_trait == UndefinedPixelTrait)\n (void) WriteBlobString(image,\">>\\n\");\n else\n {\n (void) WriteBlobString(image,\"/Type /XObject\\n\");\n (void) WriteBlobString(image,\"/Subtype /Image\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Ma%.20g\\n\",\n (double) image->scene);\n (void) WriteBlobString(image,buffer);\n switch (compression)\n {\n case NoCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"ASCII85Decode\");\n break;\n }\n case LZWCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"LZWDecode\");\n break;\n }\n case ZipCompression:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"FlateDecode\");\n break;\n }\n default:\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\n \"RunLengthDecode\");\n break;\n }\n }\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",\n (double) image->columns);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",\n (double) image->rows);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"/ColorSpace /DeviceGray\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\n \"/BitsPerComponent %d\\n\",(compression == FaxCompression) ||\n (compression == Group4Compression) ? 1 : 8);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\",\n (double) object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"stream\\n\");\n offset=TellBlob(image);\n number_pixels=(MagickSizeType) image->columns*image->rows;\n switch (compression)\n {\n case RLECompression:\n default:\n {\n MemoryInfo\n *pixel_info;", " /*\n Allocate pixel array.\n */\n length=(size_t) number_pixels;\n pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels));\n if (pixel_info == (MemoryInfo *) NULL)\n {\n image=DestroyImage(image);\n ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\");\n }\n pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);\n /*\n Dump Runlength encoded pixels.\n */\n q=pixels;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n *q++=ScaleQuantumToChar(GetPixelAlpha(image,p));\n p+=GetPixelChannels(image);\n }\n }\n#if defined(MAGICKCORE_ZLIB_DELEGATE)\n if (compression == ZipCompression)\n status=ZLIBEncodeImage(image,length,pixels,exception);\n else\n#endif\n if (compression == LZWCompression)\n status=LZWEncodeImage(image,length,pixels,exception);\n else\n status=PackbitsEncodeImage(image,length,pixels,exception);\n pixel_info=RelinquishVirtualMemory(pixel_info);\n if (status == MagickFalse)\n {", " xref=(MagickOffsetType *) RelinquishMagickMemory(xref);", " (void) CloseBlob(image);\n return(MagickFalse);\n }\n break;\n }\n case NoCompression:\n {\n /*\n Dump uncompressed PseudoColor packets.\n */\n Ascii85Initialize(image);\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n p=GetVirtualPixels(image,0,y,image->columns,1,exception);\n if (p == (const Quantum *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p)));\n p+=GetPixelChannels(image);\n }\n }\n Ascii85Flush(image);\n break;\n }\n }\n offset=TellBlob(image)-offset;\n (void) WriteBlobString(image,\"\\nendstream\\n\");\n }\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Length object.\n */\n xref[object++]=TellBlob(image);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double)\n offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"endobj\\n\");\n if (GetNextImageInList(image) == (Image *) NULL)\n break;\n image=SyncNextImageInList(image);\n status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);\n if (status == MagickFalse)\n break;\n } while (image_info->adjoin != MagickFalse);\n /*\n Write Metadata object.\n */\n xref[object++]=TellBlob(image);\n info_id=object;\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double)\n object);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"<<\\n\");\n if (LocaleCompare(image_info->magick,\"PDFA\") == 0)\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (%s)\\n\",\n EscapeParenthesis(basename));\n else\n {\n wchar_t\n *utf16;", " utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length);\n if (utf16 != (wchar_t *) NULL)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (\\xfe\\xff\");\n (void) WriteBlobString(image,buffer);\n for (i=0; i < (ssize_t) length; i++)\n (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]);\n (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\");\n utf16=(wchar_t *) RelinquishMagickMemory(utf16);\n }\n }\n (void) WriteBlobString(image,buffer);\n seconds=time((time_t *) NULL);\n#if defined(MAGICKCORE_HAVE_LOCALTIME_R)\n (void) localtime_r(&seconds,&local_time);\n#else\n (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time));\n#endif\n (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\",\n local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday,\n local_time.tm_hour,local_time.tm_min,local_time.tm_sec);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/CreationDate (%s)\\n\",\n date);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ModDate (%s)\\n\",date);\n (void) WriteBlobString(image,buffer);\n url=(char *) MagickAuthoritativeURL;\n escape=EscapeParenthesis(url);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Producer (%s)\\n\",escape);\n escape=DestroyString(escape);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"endobj\\n\");\n /*\n Write Xref object.\n */\n offset=TellBlob(image)-xref[0]+\n (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10;\n (void) WriteBlobString(image,\"xref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"0000000000 65535 f \\n\");\n for (i=0; i < (ssize_t) object; i++)\n {\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\",\n (unsigned long) xref[i]);\n (void) WriteBlobString(image,buffer);\n }\n (void) WriteBlobString(image,\"trailer\\n\");\n (void) WriteBlobString(image,\"<<\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Size %.20g\\n\",(double)\n object+1);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Info %.20g 0 R\\n\",(double)\n info_id);\n (void) WriteBlobString(image,buffer);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/Root %.20g 0 R\\n\",(double)\n root_id);\n (void) WriteBlobString(image,buffer);\n (void) SignatureImage(image,exception);\n (void) FormatLocaleString(buffer,MagickPathExtent,\"/ID [<%s> <%s>]\\n\",\n GetImageProperty(image,\"signature\",exception),\n GetImageProperty(image,\"signature\",exception));\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\">>\\n\");\n (void) WriteBlobString(image,\"startxref\\n\");\n (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset);\n (void) WriteBlobString(image,buffer);\n (void) WriteBlobString(image,\"%%EOF\\n\");\n xref=(MagickOffsetType *) RelinquishMagickMemory(xref);\n (void) CloseBlob(image);\n return(MagickTrue);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [2904], "buggy_code_start_loc": [1912], "filenames": ["coders/pdf.c"], "fixing_code_end_loc": [2913], "fixing_code_start_loc": [1913], "message": "In ImageMagick before 7.0.8-25 and GraphicsMagick through 1.3.31, several memory leaks exist in WritePDFImage in coders/pdf.c.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "E982CE9C-89F7-4A5D-B036-A9A483493D5B", "versionEndExcluding": "6.9.10-25", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:a:imagemagick:imagemagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F7DF2A1-ADDE-48C4-BD39-CCA15D0D767A", "versionEndExcluding": "7.0.8-25", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": "7.0.0-0", "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:graphicsmagick:graphicsmagick:*:*:*:*:*:*:*:*", "matchCriteriaId": "DA564A9F-4001-4846-A8BB-EAD95674C890", "versionEndExcluding": null, "versionEndIncluding": "1.3.31", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:opensuse:leap:15.0:*:*:*:*:*:*:*", "matchCriteriaId": "F1E78106-58E6-4D59-990F-75DA575BFAD9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:10.0:*:*:*:*:*:*:*", "matchCriteriaId": "07B237A9-69A3-4A9C-9DA0-4E06BD37AE73", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.04:*:*:*:lts:*:*:*", "matchCriteriaId": "23A7C53F-B80F-4E6A-AFA9-58EEA84BE11D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:18.10:*:*:*:*:*:*:*", "matchCriteriaId": "07C312A0-CD2C-4B9C-B064-6409B25C278F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:19.04:*:*:*:*:*:*:*", "matchCriteriaId": "CD783B0C-9246-47D9-A937-6144FE8BFF0F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In ImageMagick before 7.0.8-25 and GraphicsMagick through 1.3.31, several memory leaks exist in WritePDFImage in coders/pdf.c."}, {"lang": "es", "value": "En ImageMagick, en versiones anteriores a la 7.0.8-25, y GraphicsMagick, hasta la versi\u00f3n 1.3.31, existen varias vulnerabilidades de fuga de memoria en WritePDFImage en coders/pdf.c."}], "evaluatorComment": null, "id": "CVE-2019-7397", "lastModified": "2021-04-28T17:30:09.007", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:N/I:N/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.5, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2019-02-05T00:29:00.510", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "http://hg.graphicsmagick.org/hg/GraphicsMagick/rev/11ad3aeb8ab1"}, {"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-04/msg00034.html"}, {"source": "cve@mitre.org", "tags": ["Broken Link"], "url": "http://lists.opensuse.org/opensuse-security-announce/2019-05/msg00006.html"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/106847"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/commit/306c1f0fa5754ca78efd16ab752f0e981d4f6b82"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://github.com/ImageMagick/ImageMagick/issues/1454"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/4034-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2020/dsa-4712"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-401"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/ImageMagick/ImageMagick/commit/306c1f0fa5754ca78efd16ab752f0e981d4f6b82"}, "type": "CWE-401"}
30
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007 Oracle. All rights reserved.\n *\n * This software is available to you under a choice of one of two\n * licenses. You may choose to be licensed under the terms of the GNU\n * General Public License (GPL) Version 2, available from the file\n * COPYING in the main directory of this source tree, or the\n * OpenIB.org BSD license below:\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * - Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the following\n * disclaimer.\n *\n * - Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n */\n#include <linux/pagemap.h>\n#include <linux/slab.h>\n#include <linux/rbtree.h>\n#include <linux/dma-mapping.h> /* for DMA_*_DEVICE */", "#include \"rds.h\"", "/*\n * XXX\n * - build with sparse\n * - should we detect duplicate keys on a socket? hmm.\n * - an rdma is an mlock, apply rlimit?\n */", "/*\n * get the number of pages by looking at the page indices that the start and\n * end addresses fall in.\n *\n * Returns 0 if the vec is invalid. It is invalid if the number of bytes\n * causes the address to wrap or overflows an unsigned int. This comes\n * from being stored in the 'length' member of 'struct scatterlist'.\n */\nstatic unsigned int rds_pages_in_vec(struct rds_iovec *vec)\n{\n\tif ((vec->addr + vec->bytes <= vec->addr) ||\n\t (vec->bytes > (u64)UINT_MAX))\n\t\treturn 0;", "\treturn ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) -\n\t\t(vec->addr >> PAGE_SHIFT);\n}", "static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key,\n\t\t\t\t struct rds_mr *insert)\n{\n\tstruct rb_node **p = &root->rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct rds_mr *mr;", "\twhile (*p) {\n\t\tparent = *p;\n\t\tmr = rb_entry(parent, struct rds_mr, r_rb_node);", "\t\tif (key < mr->r_key)\n\t\t\tp = &(*p)->rb_left;\n\t\telse if (key > mr->r_key)\n\t\t\tp = &(*p)->rb_right;\n\t\telse\n\t\t\treturn mr;\n\t}", "\tif (insert) {\n\t\trb_link_node(&insert->r_rb_node, parent, p);\n\t\trb_insert_color(&insert->r_rb_node, root);\n\t\trefcount_inc(&insert->r_refcount);\n\t}\n\treturn NULL;\n}", "/*\n * Destroy the transport-specific part of a MR.\n */\nstatic void rds_destroy_mr(struct rds_mr *mr)\n{\n\tstruct rds_sock *rs = mr->r_sock;\n\tvoid *trans_private = NULL;\n\tunsigned long flags;", "\trdsdebug(\"RDS: destroy mr key is %x refcnt %u\\n\",\n\t\t\tmr->r_key, refcount_read(&mr->r_refcount));", "\tif (test_and_set_bit(RDS_MR_DEAD, &mr->r_state))\n\t\treturn;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tif (!RB_EMPTY_NODE(&mr->r_rb_node))\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\ttrans_private = mr->r_trans_private;\n\tmr->r_trans_private = NULL;\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (trans_private)\n\t\tmr->r_trans->free_mr(trans_private, mr->r_invalidate);\n}", "void __rds_put_mr_final(struct rds_mr *mr)\n{\n\trds_destroy_mr(mr);\n\tkfree(mr);\n}", "/*\n * By the time this is called we can't have any more ioctls called on\n * the socket so we don't need to worry about racing with others.\n */\nvoid rds_rdma_drop_keys(struct rds_sock *rs)\n{\n\tstruct rds_mr *mr;\n\tstruct rb_node *node;\n\tunsigned long flags;", "\t/* Release any MRs associated with this socket */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\twhile ((node = rb_first(&rs->rs_rdma_keys))) {\n\t\tmr = rb_entry(node, struct rds_mr, r_rb_node);\n\t\tif (mr->r_trans == rs->rs_transport)\n\t\t\tmr->r_invalidate = 0;\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (rs->rs_transport && rs->rs_transport->flush_mrs)\n\t\trs->rs_transport->flush_mrs();\n}", "/*\n * Helper function to pin user pages.\n */\nstatic int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages,\n\t\t\tstruct page **pages, int write)\n{\n\tint ret;", "\tret = get_user_pages_fast(user_addr, nr_pages, write, pages);", "\tif (ret >= 0 && ret < nr_pages) {\n\t\twhile (ret--)\n\t\t\tput_page(pages[ret]);\n\t\tret = -EFAULT;\n\t}", "\treturn ret;\n}", "static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;\n", "\tif (rs->rs_bound_addr == 0) {", "\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}", "\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}", "\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);", "\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;", "\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;", "\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;", "\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);", "\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);", "\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);", "\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);", "\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}", "\tmr->r_trans_private = trans_private;", "\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);", "\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing <R_Key, offset> and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;", "\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tBUG_ON(found && found != mr);", "\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}", "\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n}", "int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_args args;", "\tif (optlen != sizeof(struct rds_get_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_args)))\n\t\treturn -EFAULT;", "\treturn __rds_rdma_map(rs, &args, NULL, NULL);\n}", "int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_for_dest_args args;\n\tstruct rds_get_mr_args new_args;", "\tif (optlen != sizeof(struct rds_get_mr_for_dest_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_for_dest_args)))\n\t\treturn -EFAULT;", "\t/*\n\t * Initially, just behave like get_mr().\n\t * TODO: Implement get_mr as wrapper around this\n\t *\t and deprecate it.\n\t */\n\tnew_args.vec = args.vec;\n\tnew_args.cookie_addr = args.cookie_addr;\n\tnew_args.flags = args.flags;", "\treturn __rds_rdma_map(rs, &new_args, NULL, NULL);\n}", "/*\n * Free the MR indicated by the given R_Key\n */\nint rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_free_mr_args args;\n\tstruct rds_mr *mr;\n\tunsigned long flags;", "\tif (optlen != sizeof(struct rds_free_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_free_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_free_mr_args)))\n\t\treturn -EFAULT;", "\t/* Special case - a null cookie means flush all unused MRs */\n\tif (args.cookie == 0) {\n\t\tif (!rs->rs_transport || !rs->rs_transport->flush_mrs)\n\t\t\treturn -EINVAL;\n\t\trs->rs_transport->flush_mrs();\n\t\treturn 0;\n\t}", "\t/* Look up the MR given its R_key and remove it from the rbtree\n\t * so nobody else finds it.\n\t * This should also prevent races with rds_rdma_unuse.\n\t */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL);\n\tif (mr) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tif (args.flags & RDS_RDMA_INVALIDATE)\n\t\t\tmr->r_invalidate = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (!mr)\n\t\treturn -EINVAL;", "\t/*\n\t * call rds_destroy_mr() ourselves so that we're sure it's done by the time\n\t * we return. If we let rds_mr_put() do it it might not happen until\n\t * someone else drops their ref.\n\t */\n\trds_destroy_mr(mr);\n\trds_mr_put(mr);\n\treturn 0;\n}", "/*\n * This is called when we receive an extension header that\n * tells us this MR was used. It allows us to implement\n * use_once semantics\n */\nvoid rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force)\n{\n\tstruct rds_mr *mr;\n\tunsigned long flags;\n\tint zot_me = 0;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr) {\n\t\tpr_debug(\"rds: trying to unuse MR with unknown r_key %u!\\n\",\n\t\t\t r_key);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\treturn;\n\t}", "\tif (mr->r_use_once || force) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tzot_me = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\t/* May have to issue a dma_sync on this memory region.\n\t * Note we could avoid this if the operation was a RDMA READ,\n\t * but at this point we can't tell. */\n\tif (mr->r_trans->sync_mr)\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE);", "\t/* If the MR was marked as invalidate, this will\n\t * trigger an async flush. */\n\tif (zot_me) {\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t}\n}", "void rds_rdma_free_op(struct rm_rdma_op *ro)\n{\n\tunsigned int i;", "\tfor (i = 0; i < ro->op_nents; i++) {\n\t\tstruct page *page = sg_page(&ro->op_sg[i]);", "\t\t/* Mark page dirty if it was possibly modified, which\n\t\t * is the case for a RDMA_READ which copies from remote\n\t\t * to local memory */\n\t\tif (!ro->op_write) {\n\t\t\tWARN_ON(!page->mapping && irqs_disabled());\n\t\t\tset_page_dirty(page);\n\t\t}\n\t\tput_page(page);\n\t}", "\tkfree(ro->op_notifier);\n\tro->op_notifier = NULL;\n\tro->op_active = 0;\n}", "void rds_atomic_free_op(struct rm_atomic_op *ao)\n{\n\tstruct page *page = sg_page(ao->op_sg);", "\t/* Mark page dirty if it was possibly modified, which\n\t * is the case for a RDMA_READ which copies from remote\n\t * to local memory */\n\tset_page_dirty(page);\n\tput_page(page);", "\tkfree(ao->op_notifier);\n\tao->op_notifier = NULL;\n\tao->op_active = 0;\n}", "\n/*\n * Count the number of pages needed to describe an incoming iovec array.\n */\nstatic int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs)\n{\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < nr_iovecs; i++) {\n\t\tnr_pages = rds_pages_in_vec(&iov[i]);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages;\n}", "int rds_rdma_extra_size(struct rds_rdma_args *args)\n{\n\tstruct rds_iovec vec;\n\tstruct rds_iovec __user *local_vec;\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\tlocal_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < args->nr_local; i++) {\n\t\tif (copy_from_user(&vec, &local_vec[i],\n\t\t\t\t sizeof(struct rds_iovec)))\n\t\t\treturn -EFAULT;", "\t\tnr_pages = rds_pages_in_vec(&vec);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages * sizeof(struct scatterlist);\n}", "/*\n * The application asks for a RDMA transfer.\n * Extract all arguments and set up the rdma_op\n */\nint rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tstruct rds_rdma_args *args;\n\tstruct rm_rdma_op *op = &rm->rdma;\n\tint nr_pages;\n\tunsigned int nr_bytes;\n\tstruct page **pages = NULL;\n\tstruct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack;\n\tint iov_size;\n\tunsigned int i, j;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args))\n\t || rm->rdma.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\tif (rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out_ret;\n\t}", "\tif (args->nr_local > UIO_MAXIOV) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out_ret;\n\t}", "\t/* Check whether to allocate the iovec area */\n\tiov_size = args->nr_local * sizeof(struct rds_iovec);\n\tif (args->nr_local > UIO_FASTIOV) {\n\t\tiovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL);\n\t\tif (!iovs) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out_ret;\n\t\t}\n\t}", "\tif (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_rdma_pages(iovs, args->nr_local);\n\tif (nr_pages < 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\top->op_write = !!(args->flags & RDS_RDMA_READWRITE);\n\top->op_fence = !!(args->flags & RDS_RDMA_FENCE);\n\top->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\top->op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\top->op_active = 1;\n\top->op_recverr = rs->rs_recverr;\n\tWARN_ON(!nr_pages);\n\top->op_sg = rds_message_alloc_sgs(rm, nr_pages);\n\tif (!op->op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tif (op->op_notify || op->op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\top->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL);\n\t\tif (!op->op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\top->op_notifier->n_user_token = args->user_token;\n\t\top->op_notifier->n_status = RDS_RDMA_SUCCESS;", "\t\t/* Enable rmda notification on data operation for composite\n\t\t * rds messages and make sure notification is enabled only\n\t\t * for the data operation which follows it so that application\n\t\t * gets notified only after full message gets delivered.\n\t\t */\n\t\tif (rm->data.op_sg) {\n\t\t\trm->rdma.op_notify = 0;\n\t\t\trm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\t\t}\n\t}", "\t/* The cookie contains the R_Key of the remote memory region, and\n\t * optionally an offset into it. This is how we implement RDMA into\n\t * unaligned memory.\n\t * When setting up the RDMA, we need to add that offset to the\n\t * destination address (which is really an offset into the MR)\n\t * FIXME: We may want to move this into ib_rdma.c\n\t */\n\top->op_rkey = rds_rdma_cookie_key(args->cookie);\n\top->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie);", "\tnr_bytes = 0;", "\trdsdebug(\"RDS: rdma prepare nr_local %llu rva %llx rkey %x\\n\",\n\t (unsigned long long)args->nr_local,\n\t (unsigned long long)args->remote_vec.addr,\n\t op->op_rkey);", "\tfor (i = 0; i < args->nr_local; i++) {\n\t\tstruct rds_iovec *iov = &iovs[i];\n\t\t/* don't need to check, rds_rdma_pages() verified nr will be +nonzero */\n\t\tunsigned int nr = rds_pages_in_vec(iov);", "\t\trs->rs_user_addr = iov->addr;\n\t\trs->rs_user_bytes = iov->bytes;", "\t\t/* If it's a WRITE operation, we want to pin the pages for reading.\n\t\t * If it's a READ operation, we need to pin the pages for writing.\n\t\t */\n\t\tret = rds_pin_pages(iov->addr, nr, pages, !op->op_write);\n\t\tif (ret < 0)\n\t\t\tgoto out;\n\t\telse\n\t\t\tret = 0;", "\t\trdsdebug(\"RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\\n\",\n\t\t\t nr_bytes, nr, iov->bytes, iov->addr);", "\t\tnr_bytes += iov->bytes;", "\t\tfor (j = 0; j < nr; j++) {\n\t\t\tunsigned int offset = iov->addr & ~PAGE_MASK;\n\t\t\tstruct scatterlist *sg;", "\t\t\tsg = &op->op_sg[op->op_nents + j];\n\t\t\tsg_set_page(sg, pages[j],\n\t\t\t\t\tmin_t(unsigned int, iov->bytes, PAGE_SIZE - offset),\n\t\t\t\t\toffset);", "\t\t\trdsdebug(\"RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\\n\",\n\t\t\t sg->offset, sg->length, iov->addr, iov->bytes);", "\t\t\tiov->addr += sg->length;\n\t\t\tiov->bytes -= sg->length;\n\t\t}", "\t\top->op_nents += nr;\n\t}", "\tif (nr_bytes > args->remote_vec.bytes) {\n\t\trdsdebug(\"RDS nr_bytes %u remote_bytes %u do not match\\n\",\n\t\t\t\tnr_bytes,\n\t\t\t\t(unsigned int) args->remote_vec.bytes);\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\top->op_bytes = nr_bytes;", "out:\n\tif (iovs != iovstack)\n\t\tsock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size);\n\tkfree(pages);\nout_ret:\n\tif (ret)\n\t\trds_rdma_free_op(op);\n\telse\n\t\trds_stats_inc(s_send_rdma);", "\treturn ret;\n}", "/*\n * The application wants us to pass an RDMA destination (aka MR)\n * to the remote\n */\nint rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tunsigned long flags;\n\tstruct rds_mr *mr;\n\tu32 r_key;\n\tint err = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\tmemcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie));", "\t/* We are reusing a previously mapped MR here. Most likely, the\n\t * application has written to the buffer, so we need to explicitly\n\t * flush those writes to RAM. Otherwise the HCA may not see them\n\t * when doing a DMA from that buffer.\n\t */\n\tr_key = rds_rdma_cookie_key(rm->m_rdma_cookie);", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr)\n\t\terr = -EINVAL;\t/* invalid r_key */\n\telse\n\t\trefcount_inc(&mr->r_refcount);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (mr) {\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE);\n\t\trm->rdma.op_rdma_mr = mr;\n\t}\n\treturn err;\n}", "/*\n * The application passes us an address range it wants to enable RDMA\n * to/from. We map the area, and save the <R_Key,offset> pair\n * in rm->m_rdma_cookie. This causes it to be sent along to the peer\n * in an extension header.\n */\nint rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\treturn __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr);\n}", "/*\n * Fill in rds_message for an atomic request.\n */\nint rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n\t\t struct cmsghdr *cmsg)\n{\n\tstruct page *page = NULL;\n\tstruct rds_atomic_args *args;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))\n\t || rm->atomic.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\t/* Nonmasked & masked cmsg ops converted to masked hw ops */\n\tswitch (cmsg->cmsg_type) {\n\tcase RDS_CMSG_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = 0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->m_fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;\n\t\tbreak;\n\tcase RDS_CMSG_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = ~0;\n\t\trm->atomic.op_m_cswp.swap_mask = ~0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->m_cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->m_cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;\n\t\trm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;\n\t\tbreak;\n\tdefault:\n\t\tBUG(); /* should never happen */\n\t}", "\trm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\trm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\trm->atomic.op_active = 1;\n\trm->atomic.op_recverr = rs->rs_recverr;\n\trm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);\n\tif (!rm->atomic.op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}", "\t/* verify 8 byte-aligned */\n\tif (args->local_addr & 0x7) {\n\t\tret = -EFAULT;\n\t\tgoto err;\n\t}", "\tret = rds_pin_pages(args->local_addr, 1, &page, 1);\n\tif (ret != 1)\n\t\tgoto err;\n\tret = 0;", "\tsg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));", "\tif (rm->atomic.op_notify || rm->atomic.op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\trm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);\n\t\tif (!rm->atomic.op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}", "\t\trm->atomic.op_notifier->n_user_token = args->user_token;\n\t\trm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;\n\t}", "\trm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);\n\trm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);", "\treturn ret;\nerr:\n\tif (page)\n\t\tput_page(page);\n\tkfree(rm->atomic.op_notifier);", "\treturn ret;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [187], "buggy_code_start_loc": [186], "filenames": ["net/rds/rdma.c"], "fixing_code_end_loc": [187], "fixing_code_start_loc": [186], "message": "A NULL pointer dereference was found in the net/rds/rdma.c __rds_rdma_map() function in the Linux kernel before 4.14.7 allowing local attackers to cause a system panic and a denial-of-service, related to RDS_GET_MR and RDS_GET_MR_FOR_DEST.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C8B635DD-2AEF-43F3-BBED-2622811F1809", "versionEndExcluding": "4.14.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A NULL pointer dereference was found in the net/rds/rdma.c __rds_rdma_map() function in the Linux kernel before 4.14.7 allowing local attackers to cause a system panic and a denial-of-service, related to RDS_GET_MR and RDS_GET_MR_FOR_DEST."}, {"lang": "es", "value": "Se ha encontrado una desreferencia de puntero NULL en la funci\u00f3n net/rds/rdma.c __rds_rdma_map() en el kernel de Linux, en versiones anteriores a la 4.14.7, que permite que atacantes locales provoquen un error en el sistema y una denegaci\u00f3n de servicio (DoS). Esto se relaciona con RDS_GET_MR y RDS_GET_MR_FOR_DEST."}], "evaluatorComment": null, "id": "CVE-2018-7492", "lastModified": "2019-03-26T18:46:57.203", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-26T20:29:00.333", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=f3069c6d33f6ae63a1668737bc78aaaa51bff7ca"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/103185"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1527393"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/f3069c6d33f6ae63a1668737bc78aaaa51bff7ca"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/05/msg00000.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://patchwork.kernel.org/patch/10096441/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3674-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3674-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3677-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3677-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2018/dsa-4187"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://www.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.14.7"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://xorl.wordpress.com/2017/12/18/linux-kernel-rdma-null-pointer-dereference/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/f3069c6d33f6ae63a1668737bc78aaaa51bff7ca"}, "type": "CWE-476"}
31
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2007 Oracle. All rights reserved.\n *\n * This software is available to you under a choice of one of two\n * licenses. You may choose to be licensed under the terms of the GNU\n * General Public License (GPL) Version 2, available from the file\n * COPYING in the main directory of this source tree, or the\n * OpenIB.org BSD license below:\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * - Redistributions of source code must retain the above\n * copyright notice, this list of conditions and the following\n * disclaimer.\n *\n * - Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n */\n#include <linux/pagemap.h>\n#include <linux/slab.h>\n#include <linux/rbtree.h>\n#include <linux/dma-mapping.h> /* for DMA_*_DEVICE */", "#include \"rds.h\"", "/*\n * XXX\n * - build with sparse\n * - should we detect duplicate keys on a socket? hmm.\n * - an rdma is an mlock, apply rlimit?\n */", "/*\n * get the number of pages by looking at the page indices that the start and\n * end addresses fall in.\n *\n * Returns 0 if the vec is invalid. It is invalid if the number of bytes\n * causes the address to wrap or overflows an unsigned int. This comes\n * from being stored in the 'length' member of 'struct scatterlist'.\n */\nstatic unsigned int rds_pages_in_vec(struct rds_iovec *vec)\n{\n\tif ((vec->addr + vec->bytes <= vec->addr) ||\n\t (vec->bytes > (u64)UINT_MAX))\n\t\treturn 0;", "\treturn ((vec->addr + vec->bytes + PAGE_SIZE - 1) >> PAGE_SHIFT) -\n\t\t(vec->addr >> PAGE_SHIFT);\n}", "static struct rds_mr *rds_mr_tree_walk(struct rb_root *root, u64 key,\n\t\t\t\t struct rds_mr *insert)\n{\n\tstruct rb_node **p = &root->rb_node;\n\tstruct rb_node *parent = NULL;\n\tstruct rds_mr *mr;", "\twhile (*p) {\n\t\tparent = *p;\n\t\tmr = rb_entry(parent, struct rds_mr, r_rb_node);", "\t\tif (key < mr->r_key)\n\t\t\tp = &(*p)->rb_left;\n\t\telse if (key > mr->r_key)\n\t\t\tp = &(*p)->rb_right;\n\t\telse\n\t\t\treturn mr;\n\t}", "\tif (insert) {\n\t\trb_link_node(&insert->r_rb_node, parent, p);\n\t\trb_insert_color(&insert->r_rb_node, root);\n\t\trefcount_inc(&insert->r_refcount);\n\t}\n\treturn NULL;\n}", "/*\n * Destroy the transport-specific part of a MR.\n */\nstatic void rds_destroy_mr(struct rds_mr *mr)\n{\n\tstruct rds_sock *rs = mr->r_sock;\n\tvoid *trans_private = NULL;\n\tunsigned long flags;", "\trdsdebug(\"RDS: destroy mr key is %x refcnt %u\\n\",\n\t\t\tmr->r_key, refcount_read(&mr->r_refcount));", "\tif (test_and_set_bit(RDS_MR_DEAD, &mr->r_state))\n\t\treturn;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tif (!RB_EMPTY_NODE(&mr->r_rb_node))\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\ttrans_private = mr->r_trans_private;\n\tmr->r_trans_private = NULL;\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (trans_private)\n\t\tmr->r_trans->free_mr(trans_private, mr->r_invalidate);\n}", "void __rds_put_mr_final(struct rds_mr *mr)\n{\n\trds_destroy_mr(mr);\n\tkfree(mr);\n}", "/*\n * By the time this is called we can't have any more ioctls called on\n * the socket so we don't need to worry about racing with others.\n */\nvoid rds_rdma_drop_keys(struct rds_sock *rs)\n{\n\tstruct rds_mr *mr;\n\tstruct rb_node *node;\n\tunsigned long flags;", "\t/* Release any MRs associated with this socket */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\twhile ((node = rb_first(&rs->rs_rdma_keys))) {\n\t\tmr = rb_entry(node, struct rds_mr, r_rb_node);\n\t\tif (mr->r_trans == rs->rs_transport)\n\t\t\tmr->r_invalidate = 0;\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (rs->rs_transport && rs->rs_transport->flush_mrs)\n\t\trs->rs_transport->flush_mrs();\n}", "/*\n * Helper function to pin user pages.\n */\nstatic int rds_pin_pages(unsigned long user_addr, unsigned int nr_pages,\n\t\t\tstruct page **pages, int write)\n{\n\tint ret;", "\tret = get_user_pages_fast(user_addr, nr_pages, write, pages);", "\tif (ret >= 0 && ret < nr_pages) {\n\t\twhile (ret--)\n\t\t\tput_page(pages[ret]);\n\t\tret = -EFAULT;\n\t}", "\treturn ret;\n}", "static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,\n\t\t\t\tu64 *cookie_ret, struct rds_mr **mr_ret)\n{\n\tstruct rds_mr *mr = NULL, *found;\n\tunsigned int nr_pages;\n\tstruct page **pages = NULL;\n\tstruct scatterlist *sg;\n\tvoid *trans_private;\n\tunsigned long flags;\n\trds_rdma_cookie_t cookie;\n\tunsigned int nents;\n\tlong i;\n\tint ret;\n", "\tif (rs->rs_bound_addr == 0 || !rs->rs_transport) {", "\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out;\n\t}", "\tif (!rs->rs_transport->get_mr) {\n\t\tret = -EOPNOTSUPP;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_pages_in_vec(&args->vec);\n\tif (nr_pages == 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\t/* Restrict the size of mr irrespective of underlying transport\n\t * To account for unaligned mr regions, subtract one from nr_pages\n\t */\n\tif ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out;\n\t}", "\trdsdebug(\"RDS: get_mr addr %llx len %llu nr_pages %u\\n\",\n\t\targs->vec.addr, args->vec.bytes, nr_pages);", "\t/* XXX clamp nr_pages to limit the size of this alloc? */\n\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tmr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);\n\tif (!mr) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\trefcount_set(&mr->r_refcount, 1);\n\tRB_CLEAR_NODE(&mr->r_rb_node);\n\tmr->r_trans = rs->rs_transport;\n\tmr->r_sock = rs;", "\tif (args->flags & RDS_RDMA_USE_ONCE)\n\t\tmr->r_use_once = 1;\n\tif (args->flags & RDS_RDMA_INVALIDATE)\n\t\tmr->r_invalidate = 1;\n\tif (args->flags & RDS_RDMA_READWRITE)\n\t\tmr->r_write = 1;", "\t/*\n\t * Pin the pages that make up the user buffer and transfer the page\n\t * pointers to the mr's sg array. We check to see if we've mapped\n\t * the whole region after transferring the partial page references\n\t * to the sg array so that we can have one page ref cleanup path.\n\t *\n\t * For now we have no flag that tells us whether the mapping is\n\t * r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to\n\t * the zero page.\n\t */\n\tret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);\n\tif (ret < 0)\n\t\tgoto out;", "\tnents = ret;\n\tsg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);\n\tif (!sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}\n\tWARN_ON(!nents);\n\tsg_init_table(sg, nents);", "\t/* Stick all pages into the scatterlist */\n\tfor (i = 0 ; i < nents; i++)\n\t\tsg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);", "\trdsdebug(\"RDS: trans_private nents is %u\\n\", nents);", "\t/* Obtain a transport specific MR. If this succeeds, the\n\t * s/g list is now owned by the MR.\n\t * Note that dma_map() implies that pending writes are\n\t * flushed to RAM, so no dma_sync is needed here. */\n\ttrans_private = rs->rs_transport->get_mr(sg, nents, rs,\n\t\t\t\t\t\t &mr->r_key);", "\tif (IS_ERR(trans_private)) {\n\t\tfor (i = 0 ; i < nents; i++)\n\t\t\tput_page(sg_page(&sg[i]));\n\t\tkfree(sg);\n\t\tret = PTR_ERR(trans_private);\n\t\tgoto out;\n\t}", "\tmr->r_trans_private = trans_private;", "\trdsdebug(\"RDS: get_mr put_user key is %x cookie_addr %p\\n\",\n\t mr->r_key, (void *)(unsigned long) args->cookie_addr);", "\t/* The user may pass us an unaligned address, but we can only\n\t * map page aligned regions. So we keep the offset, and build\n\t * a 64bit cookie containing <R_Key, offset> and pass that\n\t * around. */\n\tcookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);\n\tif (cookie_ret)\n\t\t*cookie_ret = cookie;", "\tif (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\t/* Inserting the new MR into the rbtree bumps its\n\t * reference count. */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tfound = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tBUG_ON(found && found != mr);", "\trdsdebug(\"RDS: get_mr key is %x\\n\", mr->r_key);\n\tif (mr_ret) {\n\t\trefcount_inc(&mr->r_refcount);\n\t\t*mr_ret = mr;\n\t}", "\tret = 0;\nout:\n\tkfree(pages);\n\tif (mr)\n\t\trds_mr_put(mr);\n\treturn ret;\n}", "int rds_get_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_args args;", "\tif (optlen != sizeof(struct rds_get_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_args)))\n\t\treturn -EFAULT;", "\treturn __rds_rdma_map(rs, &args, NULL, NULL);\n}", "int rds_get_mr_for_dest(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_get_mr_for_dest_args args;\n\tstruct rds_get_mr_args new_args;", "\tif (optlen != sizeof(struct rds_get_mr_for_dest_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_get_mr_for_dest_args __user *)optval,\n\t\t\t sizeof(struct rds_get_mr_for_dest_args)))\n\t\treturn -EFAULT;", "\t/*\n\t * Initially, just behave like get_mr().\n\t * TODO: Implement get_mr as wrapper around this\n\t *\t and deprecate it.\n\t */\n\tnew_args.vec = args.vec;\n\tnew_args.cookie_addr = args.cookie_addr;\n\tnew_args.flags = args.flags;", "\treturn __rds_rdma_map(rs, &new_args, NULL, NULL);\n}", "/*\n * Free the MR indicated by the given R_Key\n */\nint rds_free_mr(struct rds_sock *rs, char __user *optval, int optlen)\n{\n\tstruct rds_free_mr_args args;\n\tstruct rds_mr *mr;\n\tunsigned long flags;", "\tif (optlen != sizeof(struct rds_free_mr_args))\n\t\treturn -EINVAL;", "\tif (copy_from_user(&args, (struct rds_free_mr_args __user *)optval,\n\t\t\t sizeof(struct rds_free_mr_args)))\n\t\treturn -EFAULT;", "\t/* Special case - a null cookie means flush all unused MRs */\n\tif (args.cookie == 0) {\n\t\tif (!rs->rs_transport || !rs->rs_transport->flush_mrs)\n\t\t\treturn -EINVAL;\n\t\trs->rs_transport->flush_mrs();\n\t\treturn 0;\n\t}", "\t/* Look up the MR given its R_key and remove it from the rbtree\n\t * so nobody else finds it.\n\t * This should also prevent races with rds_rdma_unuse.\n\t */\n\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, rds_rdma_cookie_key(args.cookie), NULL);\n\tif (mr) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tif (args.flags & RDS_RDMA_INVALIDATE)\n\t\t\tmr->r_invalidate = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (!mr)\n\t\treturn -EINVAL;", "\t/*\n\t * call rds_destroy_mr() ourselves so that we're sure it's done by the time\n\t * we return. If we let rds_mr_put() do it it might not happen until\n\t * someone else drops their ref.\n\t */\n\trds_destroy_mr(mr);\n\trds_mr_put(mr);\n\treturn 0;\n}", "/*\n * This is called when we receive an extension header that\n * tells us this MR was used. It allows us to implement\n * use_once semantics\n */\nvoid rds_rdma_unuse(struct rds_sock *rs, u32 r_key, int force)\n{\n\tstruct rds_mr *mr;\n\tunsigned long flags;\n\tint zot_me = 0;", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr) {\n\t\tpr_debug(\"rds: trying to unuse MR with unknown r_key %u!\\n\",\n\t\t\t r_key);\n\t\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);\n\t\treturn;\n\t}", "\tif (mr->r_use_once || force) {\n\t\trb_erase(&mr->r_rb_node, &rs->rs_rdma_keys);\n\t\tRB_CLEAR_NODE(&mr->r_rb_node);\n\t\tzot_me = 1;\n\t}\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\t/* May have to issue a dma_sync on this memory region.\n\t * Note we could avoid this if the operation was a RDMA READ,\n\t * but at this point we can't tell. */\n\tif (mr->r_trans->sync_mr)\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_FROM_DEVICE);", "\t/* If the MR was marked as invalidate, this will\n\t * trigger an async flush. */\n\tif (zot_me) {\n\t\trds_destroy_mr(mr);\n\t\trds_mr_put(mr);\n\t}\n}", "void rds_rdma_free_op(struct rm_rdma_op *ro)\n{\n\tunsigned int i;", "\tfor (i = 0; i < ro->op_nents; i++) {\n\t\tstruct page *page = sg_page(&ro->op_sg[i]);", "\t\t/* Mark page dirty if it was possibly modified, which\n\t\t * is the case for a RDMA_READ which copies from remote\n\t\t * to local memory */\n\t\tif (!ro->op_write) {\n\t\t\tWARN_ON(!page->mapping && irqs_disabled());\n\t\t\tset_page_dirty(page);\n\t\t}\n\t\tput_page(page);\n\t}", "\tkfree(ro->op_notifier);\n\tro->op_notifier = NULL;\n\tro->op_active = 0;\n}", "void rds_atomic_free_op(struct rm_atomic_op *ao)\n{\n\tstruct page *page = sg_page(ao->op_sg);", "\t/* Mark page dirty if it was possibly modified, which\n\t * is the case for a RDMA_READ which copies from remote\n\t * to local memory */\n\tset_page_dirty(page);\n\tput_page(page);", "\tkfree(ao->op_notifier);\n\tao->op_notifier = NULL;\n\tao->op_active = 0;\n}", "\n/*\n * Count the number of pages needed to describe an incoming iovec array.\n */\nstatic int rds_rdma_pages(struct rds_iovec iov[], int nr_iovecs)\n{\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < nr_iovecs; i++) {\n\t\tnr_pages = rds_pages_in_vec(&iov[i]);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages;\n}", "int rds_rdma_extra_size(struct rds_rdma_args *args)\n{\n\tstruct rds_iovec vec;\n\tstruct rds_iovec __user *local_vec;\n\tint tot_pages = 0;\n\tunsigned int nr_pages;\n\tunsigned int i;", "\tlocal_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;", "\t/* figure out the number of pages in the vector */\n\tfor (i = 0; i < args->nr_local; i++) {\n\t\tif (copy_from_user(&vec, &local_vec[i],\n\t\t\t\t sizeof(struct rds_iovec)))\n\t\t\treturn -EFAULT;", "\t\tnr_pages = rds_pages_in_vec(&vec);\n\t\tif (nr_pages == 0)\n\t\t\treturn -EINVAL;", "\t\ttot_pages += nr_pages;", "\t\t/*\n\t\t * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,\n\t\t * so tot_pages cannot overflow without first going negative.\n\t\t */\n\t\tif (tot_pages < 0)\n\t\t\treturn -EINVAL;\n\t}", "\treturn tot_pages * sizeof(struct scatterlist);\n}", "/*\n * The application asks for a RDMA transfer.\n * Extract all arguments and set up the rdma_op\n */\nint rds_cmsg_rdma_args(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tstruct rds_rdma_args *args;\n\tstruct rm_rdma_op *op = &rm->rdma;\n\tint nr_pages;\n\tunsigned int nr_bytes;\n\tstruct page **pages = NULL;\n\tstruct rds_iovec iovstack[UIO_FASTIOV], *iovs = iovstack;\n\tint iov_size;\n\tunsigned int i, j;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_rdma_args))\n\t || rm->rdma.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\tif (rs->rs_bound_addr == 0) {\n\t\tret = -ENOTCONN; /* XXX not a great errno */\n\t\tgoto out_ret;\n\t}", "\tif (args->nr_local > UIO_MAXIOV) {\n\t\tret = -EMSGSIZE;\n\t\tgoto out_ret;\n\t}", "\t/* Check whether to allocate the iovec area */\n\tiov_size = args->nr_local * sizeof(struct rds_iovec);\n\tif (args->nr_local > UIO_FASTIOV) {\n\t\tiovs = sock_kmalloc(rds_rs_to_sk(rs), iov_size, GFP_KERNEL);\n\t\tif (!iovs) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out_ret;\n\t\t}\n\t}", "\tif (copy_from_user(iovs, (struct rds_iovec __user *)(unsigned long) args->local_vec_addr, iov_size)) {\n\t\tret = -EFAULT;\n\t\tgoto out;\n\t}", "\tnr_pages = rds_rdma_pages(iovs, args->nr_local);\n\tif (nr_pages < 0) {\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}", "\tpages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);\n\tif (!pages) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\top->op_write = !!(args->flags & RDS_RDMA_READWRITE);\n\top->op_fence = !!(args->flags & RDS_RDMA_FENCE);\n\top->op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\top->op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\top->op_active = 1;\n\top->op_recverr = rs->rs_recverr;\n\tWARN_ON(!nr_pages);\n\top->op_sg = rds_message_alloc_sgs(rm, nr_pages);\n\tif (!op->op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto out;\n\t}", "\tif (op->op_notify || op->op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\top->op_notifier = kmalloc(sizeof(struct rds_notifier), GFP_KERNEL);\n\t\tif (!op->op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto out;\n\t\t}\n\t\top->op_notifier->n_user_token = args->user_token;\n\t\top->op_notifier->n_status = RDS_RDMA_SUCCESS;", "\t\t/* Enable rmda notification on data operation for composite\n\t\t * rds messages and make sure notification is enabled only\n\t\t * for the data operation which follows it so that application\n\t\t * gets notified only after full message gets delivered.\n\t\t */\n\t\tif (rm->data.op_sg) {\n\t\t\trm->rdma.op_notify = 0;\n\t\t\trm->data.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\t\t}\n\t}", "\t/* The cookie contains the R_Key of the remote memory region, and\n\t * optionally an offset into it. This is how we implement RDMA into\n\t * unaligned memory.\n\t * When setting up the RDMA, we need to add that offset to the\n\t * destination address (which is really an offset into the MR)\n\t * FIXME: We may want to move this into ib_rdma.c\n\t */\n\top->op_rkey = rds_rdma_cookie_key(args->cookie);\n\top->op_remote_addr = args->remote_vec.addr + rds_rdma_cookie_offset(args->cookie);", "\tnr_bytes = 0;", "\trdsdebug(\"RDS: rdma prepare nr_local %llu rva %llx rkey %x\\n\",\n\t (unsigned long long)args->nr_local,\n\t (unsigned long long)args->remote_vec.addr,\n\t op->op_rkey);", "\tfor (i = 0; i < args->nr_local; i++) {\n\t\tstruct rds_iovec *iov = &iovs[i];\n\t\t/* don't need to check, rds_rdma_pages() verified nr will be +nonzero */\n\t\tunsigned int nr = rds_pages_in_vec(iov);", "\t\trs->rs_user_addr = iov->addr;\n\t\trs->rs_user_bytes = iov->bytes;", "\t\t/* If it's a WRITE operation, we want to pin the pages for reading.\n\t\t * If it's a READ operation, we need to pin the pages for writing.\n\t\t */\n\t\tret = rds_pin_pages(iov->addr, nr, pages, !op->op_write);\n\t\tif (ret < 0)\n\t\t\tgoto out;\n\t\telse\n\t\t\tret = 0;", "\t\trdsdebug(\"RDS: nr_bytes %u nr %u iov->bytes %llu iov->addr %llx\\n\",\n\t\t\t nr_bytes, nr, iov->bytes, iov->addr);", "\t\tnr_bytes += iov->bytes;", "\t\tfor (j = 0; j < nr; j++) {\n\t\t\tunsigned int offset = iov->addr & ~PAGE_MASK;\n\t\t\tstruct scatterlist *sg;", "\t\t\tsg = &op->op_sg[op->op_nents + j];\n\t\t\tsg_set_page(sg, pages[j],\n\t\t\t\t\tmin_t(unsigned int, iov->bytes, PAGE_SIZE - offset),\n\t\t\t\t\toffset);", "\t\t\trdsdebug(\"RDS: sg->offset %x sg->len %x iov->addr %llx iov->bytes %llu\\n\",\n\t\t\t sg->offset, sg->length, iov->addr, iov->bytes);", "\t\t\tiov->addr += sg->length;\n\t\t\tiov->bytes -= sg->length;\n\t\t}", "\t\top->op_nents += nr;\n\t}", "\tif (nr_bytes > args->remote_vec.bytes) {\n\t\trdsdebug(\"RDS nr_bytes %u remote_bytes %u do not match\\n\",\n\t\t\t\tnr_bytes,\n\t\t\t\t(unsigned int) args->remote_vec.bytes);\n\t\tret = -EINVAL;\n\t\tgoto out;\n\t}\n\top->op_bytes = nr_bytes;", "out:\n\tif (iovs != iovstack)\n\t\tsock_kfree_s(rds_rs_to_sk(rs), iovs, iov_size);\n\tkfree(pages);\nout_ret:\n\tif (ret)\n\t\trds_rdma_free_op(op);\n\telse\n\t\trds_stats_inc(s_send_rdma);", "\treturn ret;\n}", "/*\n * The application wants us to pass an RDMA destination (aka MR)\n * to the remote\n */\nint rds_cmsg_rdma_dest(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tunsigned long flags;\n\tstruct rds_mr *mr;\n\tu32 r_key;\n\tint err = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(rds_rdma_cookie_t)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\tmemcpy(&rm->m_rdma_cookie, CMSG_DATA(cmsg), sizeof(rm->m_rdma_cookie));", "\t/* We are reusing a previously mapped MR here. Most likely, the\n\t * application has written to the buffer, so we need to explicitly\n\t * flush those writes to RAM. Otherwise the HCA may not see them\n\t * when doing a DMA from that buffer.\n\t */\n\tr_key = rds_rdma_cookie_key(rm->m_rdma_cookie);", "\tspin_lock_irqsave(&rs->rs_rdma_lock, flags);\n\tmr = rds_mr_tree_walk(&rs->rs_rdma_keys, r_key, NULL);\n\tif (!mr)\n\t\terr = -EINVAL;\t/* invalid r_key */\n\telse\n\t\trefcount_inc(&mr->r_refcount);\n\tspin_unlock_irqrestore(&rs->rs_rdma_lock, flags);", "\tif (mr) {\n\t\tmr->r_trans->sync_mr(mr->r_trans_private, DMA_TO_DEVICE);\n\t\trm->rdma.op_rdma_mr = mr;\n\t}\n\treturn err;\n}", "/*\n * The application passes us an address range it wants to enable RDMA\n * to/from. We map the area, and save the <R_Key,offset> pair\n * in rm->m_rdma_cookie. This causes it to be sent along to the peer\n * in an extension header.\n */\nint rds_cmsg_rdma_map(struct rds_sock *rs, struct rds_message *rm,\n\t\t\t struct cmsghdr *cmsg)\n{\n\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_get_mr_args)) ||\n\t rm->m_rdma_cookie != 0)\n\t\treturn -EINVAL;", "\treturn __rds_rdma_map(rs, CMSG_DATA(cmsg), &rm->m_rdma_cookie, &rm->rdma.op_rdma_mr);\n}", "/*\n * Fill in rds_message for an atomic request.\n */\nint rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,\n\t\t struct cmsghdr *cmsg)\n{\n\tstruct page *page = NULL;\n\tstruct rds_atomic_args *args;\n\tint ret = 0;", "\tif (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))\n\t || rm->atomic.op_active)\n\t\treturn -EINVAL;", "\targs = CMSG_DATA(cmsg);", "\t/* Nonmasked & masked cmsg ops converted to masked hw ops */\n\tswitch (cmsg->cmsg_type) {\n\tcase RDS_CMSG_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = 0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_FADD:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;\n\t\trm->atomic.op_m_fadd.add = args->m_fadd.add;\n\t\trm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;\n\t\tbreak;\n\tcase RDS_CMSG_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = ~0;\n\t\trm->atomic.op_m_cswp.swap_mask = ~0;\n\t\tbreak;\n\tcase RDS_CMSG_MASKED_ATOMIC_CSWP:\n\t\trm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;\n\t\trm->atomic.op_m_cswp.compare = args->m_cswp.compare;\n\t\trm->atomic.op_m_cswp.swap = args->m_cswp.swap;\n\t\trm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;\n\t\trm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;\n\t\tbreak;\n\tdefault:\n\t\tBUG(); /* should never happen */\n\t}", "\trm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);\n\trm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);\n\trm->atomic.op_active = 1;\n\trm->atomic.op_recverr = rs->rs_recverr;\n\trm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);\n\tif (!rm->atomic.op_sg) {\n\t\tret = -ENOMEM;\n\t\tgoto err;\n\t}", "\t/* verify 8 byte-aligned */\n\tif (args->local_addr & 0x7) {\n\t\tret = -EFAULT;\n\t\tgoto err;\n\t}", "\tret = rds_pin_pages(args->local_addr, 1, &page, 1);\n\tif (ret != 1)\n\t\tgoto err;\n\tret = 0;", "\tsg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));", "\tif (rm->atomic.op_notify || rm->atomic.op_recverr) {\n\t\t/* We allocate an uninitialized notifier here, because\n\t\t * we don't want to do that in the completion handler. We\n\t\t * would have to use GFP_ATOMIC there, and don't want to deal\n\t\t * with failed allocations.\n\t\t */\n\t\trm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);\n\t\tif (!rm->atomic.op_notifier) {\n\t\t\tret = -ENOMEM;\n\t\t\tgoto err;\n\t\t}", "\t\trm->atomic.op_notifier->n_user_token = args->user_token;\n\t\trm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;\n\t}", "\trm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);\n\trm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);", "\treturn ret;\nerr:\n\tif (page)\n\t\tput_page(page);\n\tkfree(rm->atomic.op_notifier);", "\treturn ret;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [187], "buggy_code_start_loc": [186], "filenames": ["net/rds/rdma.c"], "fixing_code_end_loc": [187], "fixing_code_start_loc": [186], "message": "A NULL pointer dereference was found in the net/rds/rdma.c __rds_rdma_map() function in the Linux kernel before 4.14.7 allowing local attackers to cause a system panic and a denial-of-service, related to RDS_GET_MR and RDS_GET_MR_FOR_DEST.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "C8B635DD-2AEF-43F3-BBED-2622811F1809", "versionEndExcluding": "4.14.7", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:8.0:*:*:*:*:*:*:*", "matchCriteriaId": "C11E6FB0-C8C0-4527-9AA0-CB9B316F8F43", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:canonical:ubuntu_linux:12.04:*:*:*:esm:*:*:*", "matchCriteriaId": "8D305F7A-D159-4716-AB26-5E38BB5CD991", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:14.04:*:*:*:lts:*:*:*", "matchCriteriaId": "B5A6F2F3-4894-4392-8296-3B8DD2679084", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:16.04:*:*:*:lts:*:*:*", "matchCriteriaId": "F7016A2A-8365-4F1A-89A2-7A19F2BCAE5B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:canonical:ubuntu_linux:17.10:*:*:*:*:*:*:*", "matchCriteriaId": "9070C9D8-A14A-467F-8253-33B966C16886", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A NULL pointer dereference was found in the net/rds/rdma.c __rds_rdma_map() function in the Linux kernel before 4.14.7 allowing local attackers to cause a system panic and a denial-of-service, related to RDS_GET_MR and RDS_GET_MR_FOR_DEST."}, {"lang": "es", "value": "Se ha encontrado una desreferencia de puntero NULL en la funci\u00f3n net/rds/rdma.c __rds_rdma_map() en el kernel de Linux, en versiones anteriores a la 4.14.7, que permite que atacantes locales provoquen un error en el sistema y una denegaci\u00f3n de servicio (DoS). Esto se relaciona con RDS_GET_MR y RDS_GET_MR_FOR_DEST."}], "evaluatorComment": null, "id": "CVE-2018-7492", "lastModified": "2019-03-26T18:46:57.203", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "COMPLETE", "baseScore": 4.9, "confidentialityImpact": "NONE", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:N/I:N/A:C", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 6.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "LOCAL", "availabilityImpact": "HIGH", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "NONE", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "version": "3.0"}, "exploitabilityScore": 1.8, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-02-26T20:29:00.333", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=f3069c6d33f6ae63a1668737bc78aaaa51bff7ca"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/103185"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1527393"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/f3069c6d33f6ae63a1668737bc78aaaa51bff7ca"}, {"source": "cve@mitre.org", "tags": ["Mailing List", "Third Party Advisory"], "url": "https://lists.debian.org/debian-lts-announce/2018/05/msg00000.html"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://patchwork.kernel.org/patch/10096441/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3619-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3674-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3674-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3677-1/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://usn.ubuntu.com/3677-2/"}, {"source": "cve@mitre.org", "tags": ["Third Party Advisory"], "url": "https://www.debian.org/security/2018/dsa-4187"}, {"source": "cve@mitre.org", "tags": ["Patch", "Vendor Advisory"], "url": "https://www.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.14.7"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://xorl.wordpress.com/2017/12/18/linux-kernel-rdma-null-pointer-dereference/"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-476"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/f3069c6d33f6ae63a1668737bc78aaaa51bff7ca"}, "type": "CWE-476"}
31
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * linux/drivers/block/floppy.c\n *\n * Copyright (C) 1991, 1992 Linus Torvalds\n * Copyright (C) 1993, 1994 Alain Knaff\n * Copyright (C) 1998 Alan Cox\n */", "/*\n * 02.12.91 - Changed to static variables to indicate need for reset\n * and recalibrate. This makes some things easier (output_byte reset\n * checking etc), and means less interrupt jumping in case of errors,\n * so the code is hopefully easier to understand.\n */", "/*\n * This file is certainly a mess. I've tried my best to get it working,\n * but I don't like programming floppies, and I have only one anyway.\n * Urgel. I should check for more errors, and do more graceful error\n * recovery. Seems there are problems with several drives. I've tried to\n * correct them. No promises.\n */", "/*\n * As with hd.c, all routines within this file can (and will) be called\n * by interrupts, so extreme caution is needed. A hardware interrupt\n * handler may not sleep, or a kernel panic will happen. Thus I cannot\n * call \"floppy-on\" directly, but have to set a special timer interrupt\n * etc.\n */", "/*\n * 28.02.92 - made track-buffering routines, based on the routines written\n * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus.\n */", "/*\n * Automatic floppy-detection and formatting written by Werner Almesberger\n * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with\n * the floppy-change signal detection.\n */", "/*\n * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed\n * FDC data overrun bug, added some preliminary stuff for vertical\n * recording support.\n *\n * 1992/9/17: Added DMA allocation & DMA functions. -- hhb.\n *\n * TODO: Errors are still not counted properly.\n */", "/* 1992/9/20\n * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl)\n * modeled after the freeware MS-DOS program fdformat/88 V1.8 by\n * Christoph H. Hochst\\\"atter.\n * I have fixed the shift values to the ones I always use. Maybe a new\n * ioctl() should be created to be able to modify them.\n * There is a bug in the driver that makes it impossible to format a\n * floppy as the first thing after bootup.\n */", "/*\n * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and\n * this helped the floppy driver as well. Much cleaner, and still seems to\n * work.\n */", "/* 1994/6/24 --bbroad-- added the floppy table entries and made\n * minor modifications to allow 2.88 floppies to be run.\n */", "/* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more\n * disk types.\n */", "/*\n * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger\n * format bug fixes, but unfortunately some new bugs too...\n */", "/* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write\n * errors to allow safe writing by specialized programs.\n */", "/* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5\" disks\n * by defining bit 1 of the \"stretch\" parameter to mean put sectors on the\n * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's\n * drives are \"upside-down\").\n */", "/*\n * 1995/8/26 -- Andreas Busse -- added Mips support.\n */", "/*\n * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent\n * features to asm/floppy.h.\n */", "/*\n * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support\n */", "/*\n * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of\n * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting &\n * use of '0' for NULL.\n */", "/*\n * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation\n * failures.\n */", "/*\n * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives.\n */", "/*\n * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24\n * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were\n * being used to store jiffies, which are unsigned longs).\n */", "/*\n * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br>\n * - get rid of check_region\n * - s/suser/capable/\n */", "/*\n * 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no\n * floppy controller (lingering task on list after module is gone... boom.)\n */", "/*\n * 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range\n * (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix\n * requires many non-obvious changes in arch dependent code.\n */", "/* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>.\n * Better audit of register_blkdev.\n */", "#undef FLOPPY_SILENT_DCL_CLEAR", "#define REALLY_SLOW_IO", "#define DEBUGT 2", "#define DPRINT(format, args...) \\\n\tpr_info(\"floppy%d: \" format, current_drive, ##args)", "#define DCL_DEBUG\t\t/* debug disk change line */\n#ifdef DCL_DEBUG\n#define debug_dcl(test, fmt, args...) \\\n\tdo { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0)\n#else\n#define debug_dcl(test, fmt, args...) \\\n\tdo { if (0) DPRINT(fmt, ##args); } while (0)\n#endif", "/* do print messages for unexpected interrupts */\nstatic int print_unex = 1;\n#include <linux/module.h>\n#include <linux/sched.h>\n#include <linux/fs.h>\n#include <linux/kernel.h>\n#include <linux/timer.h>\n#include <linux/workqueue.h>\n#define FDPATCHES\n#include <linux/fdreg.h>\n#include <linux/fd.h>\n#include <linux/hdreg.h>\n#include <linux/errno.h>\n#include <linux/slab.h>\n#include <linux/mm.h>\n#include <linux/bio.h>\n#include <linux/string.h>\n#include <linux/jiffies.h>\n#include <linux/fcntl.h>\n#include <linux/delay.h>\n#include <linux/mc146818rtc.h>\t/* CMOS defines */\n#include <linux/ioport.h>\n#include <linux/interrupt.h>\n#include <linux/init.h>\n#include <linux/platform_device.h>\n#include <linux/mod_devicetable.h>\n#include <linux/mutex.h>\n#include <linux/io.h>\n#include <linux/uaccess.h>\n#include <linux/async.h>", "/*\n * PS/2 floppies have much slower step rates than regular floppies.\n * It's been recommended that take about 1/4 of the default speed\n * in some more extreme cases.\n */\nstatic DEFINE_MUTEX(floppy_mutex);\nstatic int slow_floppy;", "#include <asm/dma.h>\n#include <asm/irq.h>", "static int FLOPPY_IRQ = 6;\nstatic int FLOPPY_DMA = 2;\nstatic int can_use_virtual_dma = 2;\n/* =======\n * can use virtual DMA:\n * 0 = use of virtual DMA disallowed by config\n * 1 = use of virtual DMA prescribed by config\n * 2 = no virtual DMA preference configured. By default try hard DMA,\n * but fall back on virtual DMA when not enough memory available\n */", "static int use_virtual_dma;\n/* =======\n * use virtual DMA\n * 0 using hard DMA\n * 1 using virtual DMA\n * This variable is set to virtual when a DMA mem problem arises, and\n * reset back in floppy_grab_irq_and_dma.\n * It is not safe to reset it in other circumstances, because the floppy\n * driver may have several buffers in use at once, and we do currently not\n * record each buffers capabilities\n */", "static DEFINE_SPINLOCK(floppy_lock);", "static unsigned short virtual_dma_port = 0x3f0;\nirqreturn_t floppy_interrupt(int irq, void *dev_id);\nstatic int set_dor(int fdc, char mask, char data);", "#define K_64\t0x10000\t\t/* 64KB */", "/* the following is the mask of allowed drives. By default units 2 and\n * 3 of both floppy controllers are disabled, because switching on the\n * motor of these drives causes system hangs on some PCI computers. drive\n * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if\n * a drive is allowed.\n *\n * NOTE: This must come before we include the arch floppy header because\n * some ports reference this variable from there. -DaveM\n */", "static int allowed_drive_mask = 0x33;", "#include <asm/floppy.h>", "static int irqdma_allocated;", "#include <linux/blkdev.h>\n#include <linux/blkpg.h>\n#include <linux/cdrom.h>\t/* for the compatibility eject ioctl */\n#include <linux/completion.h>", "static struct request *current_req;\nstatic void do_fd_request(struct request_queue *q);\nstatic int set_next_request(void);", "#ifndef fd_get_dma_residue\n#define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)\n#endif", "/* Dma Memory related stuff */", "#ifndef fd_dma_mem_free\n#define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))\n#endif", "#ifndef fd_dma_mem_alloc\n#define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size))\n#endif", "static inline void fallback_on_nodma_alloc(char **addr, size_t l)\n{\n#ifdef FLOPPY_CAN_FALLBACK_ON_NODMA\n\tif (*addr)\n\t\treturn;\t\t/* we have the memory */\n\tif (can_use_virtual_dma != 2)\n\t\treturn;\t\t/* no fallback allowed */\n\tpr_info(\"DMA memory shortage. Temporarily falling back on virtual DMA\\n\");\n\t*addr = (char *)nodma_mem_alloc(l);\n#else\n\treturn;\n#endif\n}", "/* End dma memory related stuff */", "static unsigned long fake_change;\nstatic bool initialized;", "#define ITYPE(x)\t(((x) >> 2) & 0x1f)\n#define TOMINOR(x)\t((x & 3) | ((x & 4) << 5))\n#define UNIT(x)\t\t((x) & 0x03)\t\t/* drive on fdc */\n#define FDC(x)\t\t(((x) & 0x04) >> 2)\t/* fdc of drive */\n\t/* reverse mapping from unit and fdc to drive */\n#define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))", "#define DP\t(&drive_params[current_drive])\n#define DRS\t(&drive_state[current_drive])\n#define DRWE\t(&write_errors[current_drive])\n#define FDCS\t(&fdc_state[fdc])", "#define UDP\t(&drive_params[drive])\n#define UDRS\t(&drive_state[drive])\n#define UDRWE\t(&write_errors[drive])\n#define UFDCS\t(&fdc_state[FDC(drive)])", "#define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2)\n#define STRETCH(floppy)\t((floppy)->stretch & FD_STRETCH)", "/* read/write */\n#define COMMAND\t\t(raw_cmd->cmd[0])\n#define DR_SELECT\t(raw_cmd->cmd[1])\n#define TRACK\t\t(raw_cmd->cmd[2])\n#define HEAD\t\t(raw_cmd->cmd[3])\n#define SECTOR\t\t(raw_cmd->cmd[4])\n#define SIZECODE\t(raw_cmd->cmd[5])\n#define SECT_PER_TRACK\t(raw_cmd->cmd[6])\n#define GAP\t\t(raw_cmd->cmd[7])\n#define SIZECODE2\t(raw_cmd->cmd[8])\n#define NR_RW 9", "/* format */\n#define F_SIZECODE\t(raw_cmd->cmd[2])\n#define F_SECT_PER_TRACK (raw_cmd->cmd[3])\n#define F_GAP\t\t(raw_cmd->cmd[4])\n#define F_FILL\t\t(raw_cmd->cmd[5])\n#define NR_F 6", "/*\n * Maximum disk size (in kilobytes).\n * This default is used whenever the current disk size is unknown.\n * [Now it is rather a minimum]\n */\n#define MAX_DISK_SIZE 4\t\t/* 3984 */", "/*\n * globals used by 'result()'\n */\n#define MAX_REPLIES 16\nstatic unsigned char reply_buffer[MAX_REPLIES];\nstatic int inr;\t\t/* size of reply buffer, when called from interrupt */\n#define ST0\t\t(reply_buffer[0])\n#define ST1\t\t(reply_buffer[1])\n#define ST2\t\t(reply_buffer[2])\n#define ST3\t\t(reply_buffer[0])\t/* result of GETSTATUS */\n#define R_TRACK\t\t(reply_buffer[3])\n#define R_HEAD\t\t(reply_buffer[4])\n#define R_SECTOR\t(reply_buffer[5])\n#define R_SIZECODE\t(reply_buffer[6])", "#define SEL_DLY\t\t(2 * HZ / 100)", "/*\n * this struct defines the different floppy drive types.\n */\nstatic struct {\n\tstruct floppy_drive_params params;\n\tconst char *name;\t/* name printed while booting */\n} default_drive_params[] = {\n/* NOTE: the time values in jiffies should be in msec!\n CMOS drive type\n | Maximum data rate supported by drive type\n | | Head load time, msec\n | | | Head unload time, msec (not used)\n | | | | Step rate interval, usec\n | | | | | Time needed for spinup time (jiffies)\n | | | | | | Timeout for spinning down (jiffies)\n | | | | | | | Spindown offset (where disk stops)\n | | | | | | | | Select delay\n | | | | | | | | | RPS\n | | | | | | | | | | Max number of tracks\n | | | | | | | | | | | Interrupt timeout\n | | | | | | | | | | | | Max nonintlv. sectors\n | | | | | | | | | | | | | -Max Errors- flags */\n{{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0,\n 0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, \"unknown\" },", "{{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0,\n 0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, \"360K PC\" }, /*5 1/4 360 KB PC*/", "{{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0,\n 0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, \"1.2M\" }, /*5 1/4 HD AT*/", "{{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,\n 0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, \"720k\" }, /*3 1/2 DD*/", "{{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,\n 0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, \"1.44M\" }, /*3 1/2 HD*/", "{{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,\n 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, \"2.88M AMI BIOS\" }, /*3 1/2 ED*/", "{{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,\n 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, \"2.88M\" } /*3 1/2 ED*/\n/* | --autodetected formats--- | | |\n * read_track | | Name printed when booting\n *\t\t\t\t | Native format\n *\t Frequency of disk change checks */\n};", "static struct floppy_drive_params drive_params[N_DRIVE];\nstatic struct floppy_drive_struct drive_state[N_DRIVE];\nstatic struct floppy_write_errors write_errors[N_DRIVE];\nstatic struct timer_list motor_off_timer[N_DRIVE];\nstatic struct gendisk *disks[N_DRIVE];\nstatic struct block_device *opened_bdev[N_DRIVE];\nstatic DEFINE_MUTEX(open_lock);\nstatic struct floppy_raw_cmd *raw_cmd, default_raw_cmd;\nstatic int fdc_queue;", "/*\n * This struct defines the different floppy types.\n *\n * Bit 0 of 'stretch' tells if the tracks need to be doubled for some\n * types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch'\n * tells if the disk is in Commodore 1581 format, which means side 0 sectors\n * are located on side 1 of the disk but with a side 0 ID, and vice-versa.\n * This is the same as the Sharp MZ-80 5.25\" CP/M disk format, except that the\n * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical\n * side 0 is on physical side 0 (but with the misnamed sector IDs).\n * 'stretch' should probably be renamed to something more general, like\n * 'options'.\n *\n * Bits 2 through 9 of 'stretch' tell the number of the first sector.\n * The LSB (bit 2) is flipped. For most disks, the first sector\n * is 1 (represented by 0x00<<2). For some CP/M and music sampler\n * disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2).\n * For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2).\n *\n * Other parameters should be self-explanatory (see also setfdprm(8)).\n */\n/*\n\t Size\n\t | Sectors per track\n\t | | Head\n\t | | | Tracks\n\t | | | | Stretch\n\t | | | | | Gap 1 size\n\t | | | | | | Data rate, | 0x40 for perp\n\t | | | | | | | Spec1 (stepping rate, head unload\n\t | | | | | | | | /fmt gap (gap2) */\nstatic struct floppy_struct floppy_type[32] = {\n\t{ 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL },\t/* 0 no testing */\n\t{ 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,\"d360\" }, /* 1 360KB PC */\n\t{ 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,\"h1200\" },\t/* 2 1.2MB AT */\n\t{ 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,\"D360\" },\t/* 3 360KB SS 3.5\" */\n\t{ 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,\"D720\" },\t/* 4 720KB 3.5\" */\n\t{ 720, 9,2,40,1,0x23,0x01,0xDF,0x50,\"h360\" },\t/* 5 360KB AT */\n\t{ 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,\"h720\" },\t/* 6 720KB AT */\n\t{ 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,\"H1440\" },\t/* 7 1.44MB 3.5\" */\n\t{ 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,\"E2880\" },\t/* 8 2.88MB 3.5\" */\n\t{ 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,\"E3120\" },\t/* 9 3.12MB 3.5\" */", "\t{ 2880,18,2,80,0,0x25,0x00,0xDF,0x02,\"h1440\" }, /* 10 1.44MB 5.25\" */\n\t{ 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,\"H1680\" }, /* 11 1.68MB 3.5\" */\n\t{ 820,10,2,41,1,0x25,0x01,0xDF,0x2E,\"h410\" },\t/* 12 410KB 5.25\" */\n\t{ 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,\"H820\" },\t/* 13 820KB 3.5\" */\n\t{ 2952,18,2,82,0,0x25,0x00,0xDF,0x02,\"h1476\" },\t/* 14 1.48MB 5.25\" */\n\t{ 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,\"H1722\" },\t/* 15 1.72MB 3.5\" */\n\t{ 840,10,2,42,1,0x25,0x01,0xDF,0x2E,\"h420\" },\t/* 16 420KB 5.25\" */\n\t{ 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,\"H830\" },\t/* 17 830KB 3.5\" */\n\t{ 2988,18,2,83,0,0x25,0x00,0xDF,0x02,\"h1494\" },\t/* 18 1.49MB 5.25\" */\n\t{ 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,\"H1743\" }, /* 19 1.74 MB 3.5\" */", "\t{ 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,\"h880\" }, /* 20 880KB 5.25\" */\n\t{ 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,\"D1040\" }, /* 21 1.04MB 3.5\" */\n\t{ 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,\"D1120\" }, /* 22 1.12MB 3.5\" */\n\t{ 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,\"h1600\" }, /* 23 1.6MB 5.25\" */\n\t{ 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,\"H1760\" }, /* 24 1.76MB 3.5\" */\n\t{ 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,\"H1920\" }, /* 25 1.92MB 3.5\" */\n\t{ 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,\"E3200\" }, /* 26 3.20MB 3.5\" */\n\t{ 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,\"E3520\" }, /* 27 3.52MB 3.5\" */\n\t{ 7680,48,2,80,0,0x25,0x63,0xCF,0x00,\"E3840\" }, /* 28 3.84MB 3.5\" */\n\t{ 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,\"H1840\" }, /* 29 1.84MB 3.5\" */", "\t{ 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,\"D800\" },\t/* 30 800KB 3.5\" */\n\t{ 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,\"H1600\" }, /* 31 1.6MB 3.5\" */\n};", "#define SECTSIZE (_FD_SECTSIZE(*floppy))", "/* Auto-detection: Disk type used until the next media change occurs. */\nstatic struct floppy_struct *current_type[N_DRIVE];", "/*\n * User-provided type information. current_type points to\n * the respective entry of this array.\n */\nstatic struct floppy_struct user_params[N_DRIVE];", "static sector_t floppy_sizes[256];", "static char floppy_device_name[] = \"floppy\";", "/*\n * The driver is trying to determine the correct media format\n * while probing is set. rw_interrupt() clears it after a\n * successful access.\n */\nstatic int probing;", "/* Synchronization of FDC access. */\n#define FD_COMMAND_NONE\t\t-1\n#define FD_COMMAND_ERROR\t2\n#define FD_COMMAND_OKAY\t\t3", "static volatile int command_status = FD_COMMAND_NONE;\nstatic unsigned long fdc_busy;\nstatic DECLARE_WAIT_QUEUE_HEAD(fdc_wait);\nstatic DECLARE_WAIT_QUEUE_HEAD(command_done);", "/* Errors during formatting are counted here. */\nstatic int format_errors;", "/* Format request descriptor. */\nstatic struct format_descr format_req;", "/*\n * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps\n * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),\n * H is head unload time (1=16ms, 2=32ms, etc)\n */", "/*\n * Track buffer\n * Because these are written to by the DMA controller, they must\n * not contain a 64k byte boundary crossing, or data will be\n * corrupted/lost.\n */\nstatic char *floppy_track_buffer;\nstatic int max_buffer_sectors;", "static int *errors;\ntypedef void (*done_f)(int);\nstatic const struct cont_t {\n\tvoid (*interrupt)(void);\n\t\t\t\t/* this is called after the interrupt of the\n\t\t\t\t * main command */\n\tvoid (*redo)(void);\t/* this is called to retry the operation */\n\tvoid (*error)(void);\t/* this is called to tally an error */\n\tdone_f done;\t\t/* this is called to say if the operation has\n\t\t\t\t * succeeded/failed */\n} *cont;", "static void floppy_ready(void);\nstatic void floppy_start(void);\nstatic void process_fd_request(void);\nstatic void recalibrate_floppy(void);\nstatic void floppy_shutdown(struct work_struct *);", "static int floppy_request_regions(int);\nstatic void floppy_release_regions(int);\nstatic int floppy_grab_irq_and_dma(void);\nstatic void floppy_release_irq_and_dma(void);", "/*\n * The \"reset\" variable should be tested whenever an interrupt is scheduled,\n * after the commands have been sent. This is to ensure that the driver doesn't\n * get wedged when the interrupt doesn't come because of a failed command.\n * reset doesn't need to be tested before sending commands, because\n * output_byte is automatically disabled when reset is set.\n */\nstatic void reset_fdc(void);", "/*\n * These are global variables, as that's the easiest way to give\n * information to interrupts. They are the data used for the current\n * request.\n */\n#define NO_TRACK\t-1\n#define NEED_1_RECAL\t-2\n#define NEED_2_RECAL\t-3", "static atomic_t usage_count = ATOMIC_INIT(0);", "/* buffer related variables */\nstatic int buffer_track = -1;\nstatic int buffer_drive = -1;\nstatic int buffer_min = -1;\nstatic int buffer_max = -1;", "/* fdc related variables, should end up in a struct */\nstatic struct floppy_fdc_state fdc_state[N_FDC];\nstatic int fdc;\t\t\t/* current fdc */", "static struct workqueue_struct *floppy_wq;", "static struct floppy_struct *_floppy = floppy_type;\nstatic unsigned char current_drive;\nstatic long current_count_sectors;\nstatic unsigned char fsector_t;\t/* sector in track */\nstatic unsigned char in_sector_offset;\t/* offset within physical sector,\n\t\t\t\t\t * expressed in units of 512 bytes */", "static inline bool drive_no_geom(int drive)\n{\n\treturn !current_type[drive] && !ITYPE(UDRS->fd_device);\n}", "#ifndef fd_eject\nstatic inline int fd_eject(int drive)\n{\n\treturn -EINVAL;\n}\n#endif", "/*\n * Debugging\n * =========\n */\n#ifdef DEBUGT\nstatic long unsigned debugtimer;", "static inline void set_debugt(void)\n{\n\tdebugtimer = jiffies;\n}", "static inline void debugt(const char *func, const char *msg)\n{\n\tif (DP->flags & DEBUGT)\n\t\tpr_info(\"%s:%s dtime=%lu\\n\", func, msg, jiffies - debugtimer);\n}\n#else\nstatic inline void set_debugt(void) { }\nstatic inline void debugt(const char *func, const char *msg) { }\n#endif /* DEBUGT */", "\nstatic DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown);\nstatic const char *timeout_message;", "static void is_alive(const char *func, const char *message)\n{\n\t/* this routine checks whether the floppy driver is \"alive\" */\n\tif (test_bit(0, &fdc_busy) && command_status < 2 &&\n\t !delayed_work_pending(&fd_timeout)) {\n\t\tDPRINT(\"%s: timeout handler died. %s\\n\", func, message);\n\t}\n}", "static void (*do_floppy)(void) = NULL;", "#define OLOGSIZE 20", "static void (*lasthandler)(void);\nstatic unsigned long interruptjiffies;\nstatic unsigned long resultjiffies;\nstatic int resultsize;\nstatic unsigned long lastredo;", "static struct output_log {\n\tunsigned char data;\n\tunsigned char status;\n\tunsigned long jiffies;\n} output_log[OLOGSIZE];", "static int output_log_pos;", "#define current_reqD -1\n#define MAXTIMEOUT -2", "static void __reschedule_timeout(int drive, const char *message)\n{\n\tunsigned long delay;", "\tif (drive == current_reqD)\n\t\tdrive = current_drive;", "\tif (drive < 0 || drive >= N_DRIVE) {\n\t\tdelay = 20UL * HZ;\n\t\tdrive = 0;\n\t} else\n\t\tdelay = UDP->timeout;", "\tmod_delayed_work(floppy_wq, &fd_timeout, delay);\n\tif (UDP->flags & FD_DEBUG)\n\t\tDPRINT(\"reschedule timeout %s\\n\", message);\n\ttimeout_message = message;\n}", "static void reschedule_timeout(int drive, const char *message)\n{\n\tunsigned long flags;", "\tspin_lock_irqsave(&floppy_lock, flags);\n\t__reschedule_timeout(drive, message);\n\tspin_unlock_irqrestore(&floppy_lock, flags);\n}", "#define INFBOUND(a, b) (a) = max_t(int, a, b)\n#define SUPBOUND(a, b) (a) = min_t(int, a, b)", "/*\n * Bottom half floppy driver.\n * ==========================\n *\n * This part of the file contains the code talking directly to the hardware,\n * and also the main service loop (seek-configure-spinup-command)\n */", "/*\n * disk change.\n * This routine is responsible for maintaining the FD_DISK_CHANGE flag,\n * and the last_checked date.\n *\n * last_checked is the date of the last check which showed 'no disk change'\n * FD_DISK_CHANGE is set under two conditions:\n * 1. The floppy has been changed after some i/o to that floppy already\n * took place.\n * 2. No floppy disk is in the drive. This is done in order to ensure that\n * requests are quickly flushed in case there is no disk in the drive. It\n * follows that FD_DISK_CHANGE can only be cleared if there is a disk in\n * the drive.\n *\n * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.\n * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on\n * each seek. If a disk is present, the disk change line should also be\n * cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk\n * change line is set, this means either that no disk is in the drive, or\n * that it has been removed since the last seek.\n *\n * This means that we really have a third possibility too:\n * The floppy has been changed after the last seek.\n */", "static int disk_change(int drive)\n{\n\tint fdc = FDC(drive);", "\tif (time_before(jiffies, UDRS->select_date + UDP->select_delay))\n\t\tDPRINT(\"WARNING disk change called early\\n\");\n\tif (!(FDCS->dor & (0x10 << UNIT(drive))) ||\n\t (FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) {\n\t\tDPRINT(\"probing disk change on unselected drive\\n\");\n\t\tDPRINT(\"drive=%d fdc=%d dor=%x\\n\", drive, FDC(drive),\n\t\t (unsigned int)FDCS->dor);\n\t}", "\tdebug_dcl(UDP->flags,\n\t\t \"checking disk change line for drive %d\\n\", drive);\n\tdebug_dcl(UDP->flags, \"jiffies=%lu\\n\", jiffies);\n\tdebug_dcl(UDP->flags, \"disk change line=%x\\n\", fd_inb(FD_DIR) & 0x80);\n\tdebug_dcl(UDP->flags, \"flags=%lx\\n\", UDRS->flags);", "\tif (UDP->flags & FD_BROKEN_DCL)\n\t\treturn test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\tif ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) {\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t\t\t\t\t/* verify write protection */", "\t\tif (UDRS->maxblock)\t/* mark it changed */\n\t\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);", "\t\t/* invalidate its geometry */\n\t\tif (UDRS->keep_data >= 0) {\n\t\t\tif ((UDP->flags & FTD_MSG) &&\n\t\t\t current_type[drive] != NULL)\n\t\t\t\tDPRINT(\"Disk type is undefined after disk change\\n\");\n\t\t\tcurrent_type[drive] = NULL;\n\t\t\tfloppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1;\n\t\t}", "\t\treturn 1;\n\t} else {\n\t\tUDRS->last_checked = jiffies;\n\t\tclear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);\n\t}\n\treturn 0;\n}", "static inline int is_selected(int dor, int unit)\n{\n\treturn ((dor & (0x10 << unit)) && (dor & 3) == unit);\n}", "static bool is_ready_state(int status)\n{\n\tint state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA);\n\treturn state == STATUS_READY;\n}", "static int set_dor(int fdc, char mask, char data)\n{\n\tunsigned char unit;\n\tunsigned char drive;\n\tunsigned char newdor;\n\tunsigned char olddor;", "\tif (FDCS->address == -1)\n\t\treturn -1;", "\tolddor = FDCS->dor;\n\tnewdor = (olddor & mask) | data;\n\tif (newdor != olddor) {\n\t\tunit = olddor & 0x3;\n\t\tif (is_selected(olddor, unit) && !is_selected(newdor, unit)) {\n\t\t\tdrive = REVDRIVE(fdc, unit);\n\t\t\tdebug_dcl(UDP->flags,\n\t\t\t\t \"calling disk change from set_dor\\n\");\n\t\t\tdisk_change(drive);\n\t\t}\n\t\tFDCS->dor = newdor;\n\t\tfd_outb(newdor, FD_DOR);", "\t\tunit = newdor & 0x3;\n\t\tif (!is_selected(olddor, unit) && is_selected(newdor, unit)) {\n\t\t\tdrive = REVDRIVE(fdc, unit);\n\t\t\tUDRS->select_date = jiffies;\n\t\t}\n\t}\n\treturn olddor;\n}", "static void twaddle(void)\n{\n\tif (DP->select_delay)\n\t\treturn;\n\tfd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR);\n\tfd_outb(FDCS->dor, FD_DOR);\n\tDRS->select_date = jiffies;\n}", "/*\n * Reset all driver information about the current fdc.\n * This is needed after a reset, and after a raw command.\n */\nstatic void reset_fdc_info(int mode)\n{\n\tint drive;", "\tFDCS->spec1 = FDCS->spec2 = -1;\n\tFDCS->need_configure = 1;\n\tFDCS->perp_mode = 1;\n\tFDCS->rawcmd = 0;\n\tfor (drive = 0; drive < N_DRIVE; drive++)\n\t\tif (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL))\n\t\t\tUDRS->track = NEED_2_RECAL;\n}", "/* selects the fdc and drive, and enables the fdc's input/dma. */\nstatic void set_fdc(int drive)\n{\n\tif (drive >= 0 && drive < N_DRIVE) {\n\t\tfdc = FDC(drive);\n\t\tcurrent_drive = drive;\n\t}\n\tif (fdc != 1 && fdc != 0) {\n\t\tpr_info(\"bad fdc value\\n\");\n\t\treturn;\n\t}\n\tset_dor(fdc, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1 - fdc, ~8, 0);\n#endif\n\tif (FDCS->rawcmd == 2)\n\t\treset_fdc_info(1);\n\tif (fd_inb(FD_STATUS) != STATUS_READY)\n\t\tFDCS->reset = 1;\n}", "/* locks the driver */\nstatic int lock_fdc(int drive, bool interruptible)\n{\n\tif (WARN(atomic_read(&usage_count) == 0,\n\t\t \"Trying to lock fdc while usage count=0\\n\"))\n\t\treturn -1;", "\tif (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy)))\n\t\treturn -EINTR;", "\tcommand_status = FD_COMMAND_NONE;", "\treschedule_timeout(drive, \"lock fdc\");\n\tset_fdc(drive);\n\treturn 0;\n}", "/* unlocks the driver */\nstatic void unlock_fdc(void)\n{\n\tif (!test_bit(0, &fdc_busy))\n\t\tDPRINT(\"FDC access conflict!\\n\");", "\traw_cmd = NULL;\n\tcommand_status = FD_COMMAND_NONE;\n\tcancel_delayed_work(&fd_timeout);\n\tdo_floppy = NULL;\n\tcont = NULL;\n\tclear_bit(0, &fdc_busy);\n\twake_up(&fdc_wait);\n}", "/* switches the motor off after a given timeout */\nstatic void motor_off_callback(unsigned long nr)\n{\n\tunsigned char mask = ~(0x10 << UNIT(nr));", "\tset_dor(FDC(nr), mask, 0);\n}", "/* schedules motor off */\nstatic void floppy_off(unsigned int drive)\n{\n\tunsigned long volatile delta;\n\tint fdc = FDC(drive);", "\tif (!(FDCS->dor & (0x10 << UNIT(drive))))\n\t\treturn;", "\tdel_timer(motor_off_timer + drive);", "\t/* make spindle stop in a position which minimizes spinup time\n\t * next time */\n\tif (UDP->rps) {\n\t\tdelta = jiffies - UDRS->first_read_date + HZ -\n\t\t UDP->spindown_offset;\n\t\tdelta = ((delta * UDP->rps) % HZ) / UDP->rps;\n\t\tmotor_off_timer[drive].expires =\n\t\t jiffies + UDP->spindown - delta;\n\t}\n\tadd_timer(motor_off_timer + drive);\n}", "/*\n * cycle through all N_DRIVE floppy drives, for disk change testing.\n * stopping at current drive. This is done before any long operation, to\n * be sure to have up to date disk change information.\n */\nstatic void scandrives(void)\n{\n\tint i;\n\tint drive;\n\tint saved_drive;", "\tif (DP->select_delay)\n\t\treturn;", "\tsaved_drive = current_drive;\n\tfor (i = 0; i < N_DRIVE; i++) {\n\t\tdrive = (saved_drive + i + 1) % N_DRIVE;\n\t\tif (UDRS->fd_ref == 0 || UDP->select_delay != 0)\n\t\t\tcontinue;\t/* skip closed drives */\n\t\tset_fdc(drive);\n\t\tif (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) &\n\t\t (0x10 << UNIT(drive))))\n\t\t\t/* switch the motor off again, if it was off to\n\t\t\t * begin with */\n\t\t\tset_dor(fdc, ~(0x10 << UNIT(drive)), 0);\n\t}\n\tset_fdc(saved_drive);\n}", "static void empty(void)\n{\n}", "static void (*floppy_work_fn)(void);", "static void floppy_work_workfn(struct work_struct *work)\n{\n\tfloppy_work_fn();\n}", "static DECLARE_WORK(floppy_work, floppy_work_workfn);", "static void schedule_bh(void (*handler)(void))\n{\n\tWARN_ON(work_pending(&floppy_work));", "\tfloppy_work_fn = handler;\n\tqueue_work(floppy_wq, &floppy_work);\n}", "static void (*fd_timer_fn)(void) = NULL;", "static void fd_timer_workfn(struct work_struct *work)\n{\n\tfd_timer_fn();\n}", "static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn);", "static void cancel_activity(void)\n{\n\tdo_floppy = NULL;\n\tcancel_delayed_work_sync(&fd_timer);\n\tcancel_work_sync(&floppy_work);\n}", "/* this function makes sure that the disk stays in the drive during the\n * transfer */\nstatic void fd_watchdog(void)\n{\n\tdebug_dcl(DP->flags, \"calling disk change from watchdog\\n\");", "\tif (disk_change(current_drive)) {\n\t\tDPRINT(\"disk removed during i/o\\n\");\n\t\tcancel_activity();\n\t\tcont->done(0);\n\t\treset_fdc();\n\t} else {\n\t\tcancel_delayed_work(&fd_timer);\n\t\tfd_timer_fn = fd_watchdog;\n\t\tqueue_delayed_work(floppy_wq, &fd_timer, HZ / 10);\n\t}\n}", "static void main_command_interrupt(void)\n{\n\tcancel_delayed_work(&fd_timer);\n\tcont->interrupt();\n}", "/* waits for a delay (spinup or select) to pass */\nstatic int fd_wait_for_completion(unsigned long expires,\n\t\t\t\t void (*function)(void))\n{\n\tif (FDCS->reset) {\n\t\treset_fdc();\t/* do the reset during sleep to win time\n\t\t\t\t * if we don't need to sleep, it's a good\n\t\t\t\t * occasion anyways */\n\t\treturn 1;\n\t}", "\tif (time_before(jiffies, expires)) {\n\t\tcancel_delayed_work(&fd_timer);\n\t\tfd_timer_fn = function;\n\t\tqueue_delayed_work(floppy_wq, &fd_timer, expires - jiffies);\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static void setup_DMA(void)\n{\n\tunsigned long f;", "\tif (raw_cmd->length == 0) {\n\t\tint i;", "\t\tpr_info(\"zero dma transfer size:\");\n\t\tfor (i = 0; i < raw_cmd->cmd_count; i++)\n\t\t\tpr_cont(\"%x,\", raw_cmd->cmd[i]);\n\t\tpr_cont(\"\\n\");\n\t\tcont->done(0);\n\t\tFDCS->reset = 1;\n\t\treturn;\n\t}\n\tif (((unsigned long)raw_cmd->kernel_data) % 512) {\n\t\tpr_info(\"non aligned address: %p\\n\", raw_cmd->kernel_data);\n\t\tcont->done(0);\n\t\tFDCS->reset = 1;\n\t\treturn;\n\t}\n\tf = claim_dma_lock();\n\tfd_disable_dma();\n#ifdef fd_dma_setup\n\tif (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length,\n\t\t\t (raw_cmd->flags & FD_RAW_READ) ?\n\t\t\t DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) {\n\t\trelease_dma_lock(f);\n\t\tcont->done(0);\n\t\tFDCS->reset = 1;\n\t\treturn;\n\t}\n\trelease_dma_lock(f);\n#else\n\tfd_clear_dma_ff();\n\tfd_cacheflush(raw_cmd->kernel_data, raw_cmd->length);\n\tfd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ?\n\t\t\tDMA_MODE_READ : DMA_MODE_WRITE);\n\tfd_set_dma_addr(raw_cmd->kernel_data);\n\tfd_set_dma_count(raw_cmd->length);\n\tvirtual_dma_port = FDCS->address;\n\tfd_enable_dma();\n\trelease_dma_lock(f);\n#endif\n}", "static void show_floppy(void);", "/* waits until the fdc becomes ready */\nstatic int wait_til_ready(void)\n{\n\tint status;\n\tint counter;", "\tif (FDCS->reset)\n\t\treturn -1;\n\tfor (counter = 0; counter < 10000; counter++) {\n\t\tstatus = fd_inb(FD_STATUS);\n\t\tif (status & STATUS_READY)\n\t\t\treturn status;\n\t}\n\tif (initialized) {\n\t\tDPRINT(\"Getstatus times out (%x) on fdc %d\\n\", status, fdc);\n\t\tshow_floppy();\n\t}\n\tFDCS->reset = 1;\n\treturn -1;\n}", "/* sends a command byte to the fdc */\nstatic int output_byte(char byte)\n{\n\tint status = wait_til_ready();", "\tif (status < 0)\n\t\treturn -1;", "\tif (is_ready_state(status)) {\n\t\tfd_outb(byte, FD_DATA);\n\t\toutput_log[output_log_pos].data = byte;\n\t\toutput_log[output_log_pos].status = status;\n\t\toutput_log[output_log_pos].jiffies = jiffies;\n\t\toutput_log_pos = (output_log_pos + 1) % OLOGSIZE;\n\t\treturn 0;\n\t}\n\tFDCS->reset = 1;\n\tif (initialized) {\n\t\tDPRINT(\"Unable to send byte %x to FDC. Fdc=%x Status=%x\\n\",\n\t\t byte, fdc, status);\n\t\tshow_floppy();\n\t}\n\treturn -1;\n}", "/* gets the response from the fdc */\nstatic int result(void)\n{\n\tint i;\n\tint status = 0;", "\tfor (i = 0; i < MAX_REPLIES; i++) {\n\t\tstatus = wait_til_ready();\n\t\tif (status < 0)\n\t\t\tbreak;\n\t\tstatus &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA;\n\t\tif ((status & ~STATUS_BUSY) == STATUS_READY) {\n\t\t\tresultjiffies = jiffies;\n\t\t\tresultsize = i;\n\t\t\treturn i;\n\t\t}\n\t\tif (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY))\n\t\t\treply_buffer[i] = fd_inb(FD_DATA);\n\t\telse\n\t\t\tbreak;\n\t}\n\tif (initialized) {\n\t\tDPRINT(\"get result error. Fdc=%d Last status=%x Read bytes=%d\\n\",\n\t\t fdc, status, i);\n\t\tshow_floppy();\n\t}\n\tFDCS->reset = 1;\n\treturn -1;\n}", "#define MORE_OUTPUT -2\n/* does the fdc need more output? */\nstatic int need_more_output(void)\n{\n\tint status = wait_til_ready();", "\tif (status < 0)\n\t\treturn -1;", "\tif (is_ready_state(status))\n\t\treturn MORE_OUTPUT;", "\treturn result();\n}", "/* Set perpendicular mode as required, based on data rate, if supported.\n * 82077 Now tested. 1Mbps data rate only possible with 82077-1.\n */\nstatic void perpendicular_mode(void)\n{\n\tunsigned char perp_mode;", "\tif (raw_cmd->rate & 0x40) {\n\t\tswitch (raw_cmd->rate & 3) {\n\t\tcase 0:\n\t\t\tperp_mode = 2;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tperp_mode = 3;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDPRINT(\"Invalid data rate for perpendicular mode!\\n\");\n\t\t\tcont->done(0);\n\t\t\tFDCS->reset = 1;\n\t\t\t\t\t/*\n\t\t\t\t\t * convenient way to return to\n\t\t\t\t\t * redo without too much hassle\n\t\t\t\t\t * (deep stack et al.)\n\t\t\t\t\t */\n\t\t\treturn;\n\t\t}\n\t} else\n\t\tperp_mode = 0;", "\tif (FDCS->perp_mode == perp_mode)\n\t\treturn;\n\tif (FDCS->version >= FDC_82077_ORIG) {\n\t\toutput_byte(FD_PERPENDICULAR);\n\t\toutput_byte(perp_mode);\n\t\tFDCS->perp_mode = perp_mode;\n\t} else if (perp_mode) {\n\t\tDPRINT(\"perpendicular mode not supported by this FDC.\\n\");\n\t}\n}\t\t\t\t/* perpendicular_mode */", "static int fifo_depth = 0xa;\nstatic int no_fifo;", "static int fdc_configure(void)\n{\n\t/* Turn on FIFO */\n\toutput_byte(FD_CONFIGURE);\n\tif (need_more_output() != MORE_OUTPUT)\n\t\treturn 0;\n\toutput_byte(0);\n\toutput_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf));\n\toutput_byte(0);\t\t/* pre-compensation from track\n\t\t\t\t 0 upwards */\n\treturn 1;\n}", "#define NOMINAL_DTR 500", "/* Issue a \"SPECIFY\" command to set the step rate time, head unload time,\n * head load time, and DMA disable flag to values needed by floppy.\n *\n * The value \"dtr\" is the data transfer rate in Kbps. It is needed\n * to account for the data rate-based scaling done by the 82072 and 82077\n * FDC types. This parameter is ignored for other types of FDCs (i.e.\n * 8272a).\n *\n * Note that changing the data transfer rate has a (probably deleterious)\n * effect on the parameters subject to scaling for 82072/82077 FDCs, so\n * fdc_specify is called again after each data transfer rate\n * change.\n *\n * srt: 1000 to 16000 in microseconds\n * hut: 16 to 240 milliseconds\n * hlt: 2 to 254 milliseconds\n *\n * These values are rounded up to the next highest available delay time.\n */\nstatic void fdc_specify(void)\n{\n\tunsigned char spec1;\n\tunsigned char spec2;\n\tunsigned long srt;\n\tunsigned long hlt;\n\tunsigned long hut;\n\tunsigned long dtr = NOMINAL_DTR;\n\tunsigned long scale_dtr = NOMINAL_DTR;\n\tint hlt_max_code = 0x7f;\n\tint hut_max_code = 0xf;", "\tif (FDCS->need_configure && FDCS->version >= FDC_82072A) {\n\t\tfdc_configure();\n\t\tFDCS->need_configure = 0;\n\t}", "\tswitch (raw_cmd->rate & 0x03) {\n\tcase 3:\n\t\tdtr = 1000;\n\t\tbreak;\n\tcase 1:\n\t\tdtr = 300;\n\t\tif (FDCS->version >= FDC_82078) {\n\t\t\t/* chose the default rate table, not the one\n\t\t\t * where 1 = 2 Mbps */\n\t\t\toutput_byte(FD_DRIVESPEC);\n\t\t\tif (need_more_output() == MORE_OUTPUT) {\n\t\t\t\toutput_byte(UNIT(current_drive));\n\t\t\t\toutput_byte(0xc0);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 2:\n\t\tdtr = 250;\n\t\tbreak;\n\t}", "\tif (FDCS->version >= FDC_82072) {\n\t\tscale_dtr = dtr;\n\t\thlt_max_code = 0x00;\t/* 0==256msec*dtr0/dtr (not linear!) */\n\t\thut_max_code = 0x0;\t/* 0==256msec*dtr0/dtr (not linear!) */\n\t}", "\t/* Convert step rate from microseconds to milliseconds and 4 bits */\n\tsrt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR);\n\tif (slow_floppy)\n\t\tsrt = srt / 4;", "\tSUPBOUND(srt, 0xf);\n\tINFBOUND(srt, 0);", "\thlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR);\n\tif (hlt < 0x01)\n\t\thlt = 0x01;\n\telse if (hlt > 0x7f)\n\t\thlt = hlt_max_code;", "\thut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR);\n\tif (hut < 0x1)\n\t\thut = 0x1;\n\telse if (hut > 0xf)\n\t\thut = hut_max_code;", "\tspec1 = (srt << 4) | hut;\n\tspec2 = (hlt << 1) | (use_virtual_dma & 1);", "\t/* If these parameters did not change, just return with success */\n\tif (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) {\n\t\t/* Go ahead and set spec1 and spec2 */\n\t\toutput_byte(FD_SPECIFY);\n\t\toutput_byte(FDCS->spec1 = spec1);\n\t\toutput_byte(FDCS->spec2 = spec2);\n\t}\n}\t\t\t\t/* fdc_specify */", "/* Set the FDC's data transfer rate on behalf of the specified drive.\n * NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue\n * of the specify command (i.e. using the fdc_specify function).\n */\nstatic int fdc_dtr(void)\n{\n\t/* If data rate not already set to desired value, set it. */\n\tif ((raw_cmd->rate & 3) == FDCS->dtr)\n\t\treturn 0;", "\t/* Set dtr */\n\tfd_outb(raw_cmd->rate & 3, FD_DCR);", "\t/* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB)\n\t * need a stabilization period of several milliseconds to be\n\t * enforced after data rate changes before R/W operations.\n\t * Pause 5 msec to avoid trouble. (Needs to be 2 jiffies)\n\t */\n\tFDCS->dtr = raw_cmd->rate & 3;\n\treturn fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready);\n}\t\t\t\t/* fdc_dtr */", "static void tell_sector(void)\n{\n\tpr_cont(\": track %d, head %d, sector %d, size %d\",\n\t\tR_TRACK, R_HEAD, R_SECTOR, R_SIZECODE);\n}\t\t\t\t/* tell_sector */", "static void print_errors(void)\n{\n\tDPRINT(\"\");\n\tif (ST0 & ST0_ECE) {\n\t\tpr_cont(\"Recalibrate failed!\");\n\t} else if (ST2 & ST2_CRC) {\n\t\tpr_cont(\"data CRC error\");\n\t\ttell_sector();\n\t} else if (ST1 & ST1_CRC) {\n\t\tpr_cont(\"CRC error\");\n\t\ttell_sector();\n\t} else if ((ST1 & (ST1_MAM | ST1_ND)) ||\n\t\t (ST2 & ST2_MAM)) {\n\t\tif (!probing) {\n\t\t\tpr_cont(\"sector not found\");\n\t\t\ttell_sector();\n\t\t} else\n\t\t\tpr_cont(\"probe failed...\");\n\t} else if (ST2 & ST2_WC) {\t/* seek error */\n\t\tpr_cont(\"wrong cylinder\");\n\t} else if (ST2 & ST2_BC) {\t/* cylinder marked as bad */\n\t\tpr_cont(\"bad cylinder\");\n\t} else {\n\t\tpr_cont(\"unknown error. ST[0..2] are: 0x%x 0x%x 0x%x\",\n\t\t\tST0, ST1, ST2);\n\t\ttell_sector();\n\t}\n\tpr_cont(\"\\n\");\n}", "/*\n * OK, this error interpreting routine is called after a\n * DMA read/write has succeeded\n * or failed, so we check the results, and copy any buffers.\n * hhb: Added better error reporting.\n * ak: Made this into a separate routine.\n */\nstatic int interpret_errors(void)\n{\n\tchar bad;", "\tif (inr != 7) {\n\t\tDPRINT(\"-- FDC reply error\\n\");\n\t\tFDCS->reset = 1;\n\t\treturn 1;\n\t}", "\t/* check IC to find cause of interrupt */\n\tswitch (ST0 & ST0_INTR) {\n\tcase 0x40:\t\t/* error occurred during command execution */\n\t\tif (ST1 & ST1_EOC)\n\t\t\treturn 0;\t/* occurs with pseudo-DMA */\n\t\tbad = 1;\n\t\tif (ST1 & ST1_WP) {\n\t\t\tDPRINT(\"Drive is write protected\\n\");\n\t\t\tclear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);\n\t\t\tcont->done(0);\n\t\t\tbad = 2;\n\t\t} else if (ST1 & ST1_ND) {\n\t\t\tset_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);\n\t\t} else if (ST1 & ST1_OR) {\n\t\t\tif (DP->flags & FTD_MSG)\n\t\t\t\tDPRINT(\"Over/Underrun - retrying\\n\");\n\t\t\tbad = 0;\n\t\t} else if (*errors >= DP->max_errors.reporting) {\n\t\t\tprint_errors();\n\t\t}\n\t\tif (ST2 & ST2_WC || ST2 & ST2_BC)\n\t\t\t/* wrong cylinder => recal */\n\t\t\tDRS->track = NEED_2_RECAL;\n\t\treturn bad;\n\tcase 0x80:\t\t/* invalid command given */\n\t\tDPRINT(\"Invalid FDC command given!\\n\");\n\t\tcont->done(0);\n\t\treturn 2;\n\tcase 0xc0:\n\t\tDPRINT(\"Abnormal termination caused by polling\\n\");\n\t\tcont->error();\n\t\treturn 2;\n\tdefault:\t\t/* (0) Normal command termination */\n\t\treturn 0;\n\t}\n}", "/*\n * This routine is called when everything should be correctly set up\n * for the transfer (i.e. floppy motor is on, the correct floppy is\n * selected, and the head is sitting on the right track).\n */\nstatic void setup_rw_floppy(void)\n{\n\tint i;\n\tint r;\n\tint flags;\n\tint dflags;\n\tunsigned long ready_date;\n\tvoid (*function)(void);", "\tflags = raw_cmd->flags;\n\tif (flags & (FD_RAW_READ | FD_RAW_WRITE))\n\t\tflags |= FD_RAW_INTR;", "\tif ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) {\n\t\tready_date = DRS->spinup_date + DP->spinup;\n\t\t/* If spinup will take a long time, rerun scandrives\n\t\t * again just before spinup completion. Beware that\n\t\t * after scandrives, we must again wait for selection.\n\t\t */\n\t\tif (time_after(ready_date, jiffies + DP->select_delay)) {\n\t\t\tready_date -= DP->select_delay;\n\t\t\tfunction = floppy_start;\n\t\t} else\n\t\t\tfunction = setup_rw_floppy;", "\t\t/* wait until the floppy is spinning fast enough */\n\t\tif (fd_wait_for_completion(ready_date, function))\n\t\t\treturn;\n\t}\n\tdflags = DRS->flags;", "\tif ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE))\n\t\tsetup_DMA();", "\tif (flags & FD_RAW_INTR)\n\t\tdo_floppy = main_command_interrupt;", "\tr = 0;\n\tfor (i = 0; i < raw_cmd->cmd_count; i++)\n\t\tr |= output_byte(raw_cmd->cmd[i]);", "\tdebugt(__func__, \"rw_command\");", "\tif (r) {\n\t\tcont->error();\n\t\treset_fdc();\n\t\treturn;\n\t}", "\tif (!(flags & FD_RAW_INTR)) {\n\t\tinr = result();\n\t\tcont->interrupt();\n\t} else if (flags & FD_RAW_NEED_DISK)\n\t\tfd_watchdog();\n}", "static int blind_seek;", "/*\n * This is the routine called after every seek (or recalibrate) interrupt\n * from the floppy controller.\n */\nstatic void seek_interrupt(void)\n{\n\tdebugt(__func__, \"\");\n\tif (inr != 2 || (ST0 & 0xF8) != 0x20) {\n\t\tDPRINT(\"seek failed\\n\");\n\t\tDRS->track = NEED_2_RECAL;\n\t\tcont->error();\n\t\tcont->redo();\n\t\treturn;\n\t}\n\tif (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) {\n\t\tdebug_dcl(DP->flags,\n\t\t\t \"clearing NEWCHANGE flag because of effective seek\\n\");\n\t\tdebug_dcl(DP->flags, \"jiffies=%lu\\n\", jiffies);\n\t\tclear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);\n\t\t\t\t\t/* effective seek */\n\t\tDRS->select_date = jiffies;\n\t}\n\tDRS->track = ST1;\n\tfloppy_ready();\n}", "static void check_wp(void)\n{\n\tif (test_bit(FD_VERIFY_BIT, &DRS->flags)) {\n\t\t\t\t\t/* check write protection */\n\t\toutput_byte(FD_GETSTATUS);\n\t\toutput_byte(UNIT(current_drive));\n\t\tif (result() != 1) {\n\t\t\tFDCS->reset = 1;\n\t\t\treturn;\n\t\t}\n\t\tclear_bit(FD_VERIFY_BIT, &DRS->flags);\n\t\tclear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);\n\t\tdebug_dcl(DP->flags,\n\t\t\t \"checking whether disk is write protected\\n\");\n\t\tdebug_dcl(DP->flags, \"wp=%x\\n\", ST3 & 0x40);\n\t\tif (!(ST3 & 0x40))\n\t\t\tset_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);\n\t\telse\n\t\t\tclear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);\n\t}\n}", "static void seek_floppy(void)\n{\n\tint track;", "\tblind_seek = 0;", "\tdebug_dcl(DP->flags, \"calling disk change from %s\\n\", __func__);", "\tif (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&\n\t disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) {\n\t\t/* the media changed flag should be cleared after the seek.\n\t\t * If it isn't, this means that there is really no disk in\n\t\t * the drive.\n\t\t */\n\t\tset_bit(FD_DISK_CHANGED_BIT, &DRS->flags);\n\t\tcont->done(0);\n\t\tcont->redo();\n\t\treturn;\n\t}\n\tif (DRS->track <= NEED_1_RECAL) {\n\t\trecalibrate_floppy();\n\t\treturn;\n\t} else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&\n\t\t (raw_cmd->flags & FD_RAW_NEED_DISK) &&\n\t\t (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) {\n\t\t/* we seek to clear the media-changed condition. Does anybody\n\t\t * know a more elegant way, which works on all drives? */\n\t\tif (raw_cmd->track)\n\t\t\ttrack = raw_cmd->track - 1;\n\t\telse {\n\t\t\tif (DP->flags & FD_SILENT_DCL_CLEAR) {\n\t\t\t\tset_dor(fdc, ~(0x10 << UNIT(current_drive)), 0);\n\t\t\t\tblind_seek = 1;\n\t\t\t\traw_cmd->flags |= FD_RAW_NEED_SEEK;\n\t\t\t}\n\t\t\ttrack = 1;\n\t\t}\n\t} else {\n\t\tcheck_wp();\n\t\tif (raw_cmd->track != DRS->track &&\n\t\t (raw_cmd->flags & FD_RAW_NEED_SEEK))\n\t\t\ttrack = raw_cmd->track;\n\t\telse {\n\t\t\tsetup_rw_floppy();\n\t\t\treturn;\n\t\t}\n\t}", "\tdo_floppy = seek_interrupt;\n\toutput_byte(FD_SEEK);\n\toutput_byte(UNIT(current_drive));\n\tif (output_byte(track) < 0) {\n\t\treset_fdc();\n\t\treturn;\n\t}\n\tdebugt(__func__, \"\");\n}", "static void recal_interrupt(void)\n{\n\tdebugt(__func__, \"\");\n\tif (inr != 2)\n\t\tFDCS->reset = 1;\n\telse if (ST0 & ST0_ECE) {\n\t\tswitch (DRS->track) {\n\t\tcase NEED_1_RECAL:\n\t\t\tdebugt(__func__, \"need 1 recal\");\n\t\t\t/* after a second recalibrate, we still haven't\n\t\t\t * reached track 0. Probably no drive. Raise an\n\t\t\t * error, as failing immediately might upset\n\t\t\t * computers possessed by the Devil :-) */\n\t\t\tcont->error();\n\t\t\tcont->redo();\n\t\t\treturn;\n\t\tcase NEED_2_RECAL:\n\t\t\tdebugt(__func__, \"need 2 recal\");\n\t\t\t/* If we already did a recalibrate,\n\t\t\t * and we are not at track 0, this\n\t\t\t * means we have moved. (The only way\n\t\t\t * not to move at recalibration is to\n\t\t\t * be already at track 0.) Clear the\n\t\t\t * new change flag */\n\t\t\tdebug_dcl(DP->flags,\n\t\t\t\t \"clearing NEWCHANGE flag because of second recalibrate\\n\");", "\t\t\tclear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);\n\t\t\tDRS->select_date = jiffies;\n\t\t\t/* fall through */\n\t\tdefault:\n\t\t\tdebugt(__func__, \"default\");\n\t\t\t/* Recalibrate moves the head by at\n\t\t\t * most 80 steps. If after one\n\t\t\t * recalibrate we don't have reached\n\t\t\t * track 0, this might mean that we\n\t\t\t * started beyond track 80. Try\n\t\t\t * again. */\n\t\t\tDRS->track = NEED_1_RECAL;\n\t\t\tbreak;\n\t\t}\n\t} else\n\t\tDRS->track = ST1;\n\tfloppy_ready();\n}", "static void print_result(char *message, int inr)\n{\n\tint i;", "\tDPRINT(\"%s \", message);\n\tif (inr >= 0)\n\t\tfor (i = 0; i < inr; i++)\n\t\t\tpr_cont(\"repl[%d]=%x \", i, reply_buffer[i]);\n\tpr_cont(\"\\n\");\n}", "/* interrupt handler. Note that this can be called externally on the Sparc */\nirqreturn_t floppy_interrupt(int irq, void *dev_id)\n{\n\tint do_print;\n\tunsigned long f;\n\tvoid (*handler)(void) = do_floppy;", "\tlasthandler = handler;\n\tinterruptjiffies = jiffies;", "\tf = claim_dma_lock();\n\tfd_disable_dma();\n\trelease_dma_lock(f);", "\tdo_floppy = NULL;\n\tif (fdc >= N_FDC || FDCS->address == -1) {\n\t\t/* we don't even know which FDC is the culprit */\n\t\tpr_info(\"DOR0=%x\\n\", fdc_state[0].dor);\n\t\tpr_info(\"floppy interrupt on bizarre fdc %d\\n\", fdc);\n\t\tpr_info(\"handler=%pf\\n\", handler);\n\t\tis_alive(__func__, \"bizarre fdc\");\n\t\treturn IRQ_NONE;\n\t}", "\tFDCS->reset = 0;\n\t/* We have to clear the reset flag here, because apparently on boxes\n\t * with level triggered interrupts (PS/2, Sparc, ...), it is needed to\n\t * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the\n\t * emission of the SENSEI's.\n\t * It is OK to emit floppy commands because we are in an interrupt\n\t * handler here, and thus we have to fear no interference of other\n\t * activity.\n\t */", "\tdo_print = !handler && print_unex && initialized;", "\tinr = result();\n\tif (do_print)\n\t\tprint_result(\"unexpected interrupt\", inr);\n\tif (inr == 0) {\n\t\tint max_sensei = 4;\n\t\tdo {\n\t\t\toutput_byte(FD_SENSEI);\n\t\t\tinr = result();\n\t\t\tif (do_print)\n\t\t\t\tprint_result(\"sensei\", inr);\n\t\t\tmax_sensei--;\n\t\t} while ((ST0 & 0x83) != UNIT(current_drive) &&\n\t\t\t inr == 2 && max_sensei);\n\t}\n\tif (!handler) {\n\t\tFDCS->reset = 1;\n\t\treturn IRQ_NONE;\n\t}\n\tschedule_bh(handler);\n\tis_alive(__func__, \"normal interrupt end\");", "\t/* FIXME! Was it really for us? */\n\treturn IRQ_HANDLED;\n}", "static void recalibrate_floppy(void)\n{\n\tdebugt(__func__, \"\");\n\tdo_floppy = recal_interrupt;\n\toutput_byte(FD_RECALIBRATE);\n\tif (output_byte(UNIT(current_drive)) < 0)\n\t\treset_fdc();\n}", "/*\n * Must do 4 FD_SENSEIs after reset because of ``drive polling''.\n */\nstatic void reset_interrupt(void)\n{\n\tdebugt(__func__, \"\");\n\tresult();\t\t/* get the status ready for set_fdc */\n\tif (FDCS->reset) {\n\t\tpr_info(\"reset set in interrupt, calling %pf\\n\", cont->error);\n\t\tcont->error();\t/* a reset just after a reset. BAD! */\n\t}\n\tcont->redo();\n}", "/*\n * reset is done by pulling bit 2 of DOR low for a while (old FDCs),\n * or by setting the self clearing bit 7 of STATUS (newer FDCs)\n */\nstatic void reset_fdc(void)\n{\n\tunsigned long flags;", "\tdo_floppy = reset_interrupt;\n\tFDCS->reset = 0;\n\treset_fdc_info(0);", "\t/* Pseudo-DMA may intercept 'reset finished' interrupt. */\n\t/* Irrelevant for systems with true DMA (i386). */", "\tflags = claim_dma_lock();\n\tfd_disable_dma();\n\trelease_dma_lock(flags);", "\tif (FDCS->version >= FDC_82072A)\n\t\tfd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS);\n\telse {\n\t\tfd_outb(FDCS->dor & ~0x04, FD_DOR);\n\t\tudelay(FD_RESET_DELAY);\n\t\tfd_outb(FDCS->dor, FD_DOR);\n\t}\n}", "static void show_floppy(void)\n{\n\tint i;", "\tpr_info(\"\\n\");\n\tpr_info(\"floppy driver state\\n\");\n\tpr_info(\"-------------------\\n\");\n\tpr_info(\"now=%lu last interrupt=%lu diff=%lu last called handler=%pf\\n\",\n\t\tjiffies, interruptjiffies, jiffies - interruptjiffies,\n\t\tlasthandler);", "\tpr_info(\"timeout_message=%s\\n\", timeout_message);\n\tpr_info(\"last output bytes:\\n\");\n\tfor (i = 0; i < OLOGSIZE; i++)\n\t\tpr_info(\"%2x %2x %lu\\n\",\n\t\t\toutput_log[(i + output_log_pos) % OLOGSIZE].data,\n\t\t\toutput_log[(i + output_log_pos) % OLOGSIZE].status,\n\t\t\toutput_log[(i + output_log_pos) % OLOGSIZE].jiffies);\n\tpr_info(\"last result at %lu\\n\", resultjiffies);\n\tpr_info(\"last redo_fd_request at %lu\\n\", lastredo);\n\tprint_hex_dump(KERN_INFO, \"\", DUMP_PREFIX_NONE, 16, 1,\n\t\t reply_buffer, resultsize, true);", "\tpr_info(\"status=%x\\n\", fd_inb(FD_STATUS));\n\tpr_info(\"fdc_busy=%lu\\n\", fdc_busy);\n\tif (do_floppy)\n\t\tpr_info(\"do_floppy=%pf\\n\", do_floppy);\n\tif (work_pending(&floppy_work))\n\t\tpr_info(\"floppy_work.func=%pf\\n\", floppy_work.func);\n\tif (delayed_work_pending(&fd_timer))\n\t\tpr_info(\"delayed work.function=%p expires=%ld\\n\",\n\t\t fd_timer.work.func,\n\t\t fd_timer.timer.expires - jiffies);\n\tif (delayed_work_pending(&fd_timeout))\n\t\tpr_info(\"timer_function=%p expires=%ld\\n\",\n\t\t fd_timeout.work.func,\n\t\t fd_timeout.timer.expires - jiffies);", "\tpr_info(\"cont=%p\\n\", cont);\n\tpr_info(\"current_req=%p\\n\", current_req);\n\tpr_info(\"command_status=%d\\n\", command_status);\n\tpr_info(\"\\n\");\n}", "static void floppy_shutdown(struct work_struct *arg)\n{\n\tunsigned long flags;", "\tif (initialized)\n\t\tshow_floppy();\n\tcancel_activity();", "\tflags = claim_dma_lock();\n\tfd_disable_dma();\n\trelease_dma_lock(flags);", "\t/* avoid dma going to a random drive after shutdown */", "\tif (initialized)\n\t\tDPRINT(\"floppy timeout called\\n\");\n\tFDCS->reset = 1;\n\tif (cont) {\n\t\tcont->done(0);\n\t\tcont->redo();\t/* this will recall reset when needed */\n\t} else {\n\t\tpr_info(\"no cont in shutdown!\\n\");\n\t\tprocess_fd_request();\n\t}\n\tis_alive(__func__, \"\");\n}", "/* start motor, check media-changed condition and write protection */\nstatic int start_motor(void (*function)(void))\n{\n\tint mask;\n\tint data;", "\tmask = 0xfc;\n\tdata = UNIT(current_drive);\n\tif (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) {\n\t\tif (!(FDCS->dor & (0x10 << UNIT(current_drive)))) {\n\t\t\tset_debugt();\n\t\t\t/* no read since this drive is running */\n\t\t\tDRS->first_read_date = 0;\n\t\t\t/* note motor start time if motor is not yet running */\n\t\t\tDRS->spinup_date = jiffies;\n\t\t\tdata |= (0x10 << UNIT(current_drive));\n\t\t}\n\t} else if (FDCS->dor & (0x10 << UNIT(current_drive)))\n\t\tmask &= ~(0x10 << UNIT(current_drive));", "\t/* starts motor and selects floppy */\n\tdel_timer(motor_off_timer + current_drive);\n\tset_dor(fdc, mask, data);", "\t/* wait_for_completion also schedules reset if needed. */\n\treturn fd_wait_for_completion(DRS->select_date + DP->select_delay,\n\t\t\t\t function);\n}", "static void floppy_ready(void)\n{\n\tif (FDCS->reset) {\n\t\treset_fdc();\n\t\treturn;\n\t}\n\tif (start_motor(floppy_ready))\n\t\treturn;\n\tif (fdc_dtr())\n\t\treturn;", "\tdebug_dcl(DP->flags, \"calling disk change from floppy_ready\\n\");\n\tif (!(raw_cmd->flags & FD_RAW_NO_MOTOR) &&\n\t disk_change(current_drive) && !DP->select_delay)\n\t\ttwaddle();\t/* this clears the dcl on certain\n\t\t\t\t * drive/controller combinations */", "#ifdef fd_chose_dma_mode\n\tif ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) {\n\t\tunsigned long flags = claim_dma_lock();\n\t\tfd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length);\n\t\trelease_dma_lock(flags);\n\t}\n#endif", "\tif (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) {\n\t\tperpendicular_mode();\n\t\tfdc_specify();\t/* must be done here because of hut, hlt ... */\n\t\tseek_floppy();\n\t} else {\n\t\tif ((raw_cmd->flags & FD_RAW_READ) ||\n\t\t (raw_cmd->flags & FD_RAW_WRITE))\n\t\t\tfdc_specify();\n\t\tsetup_rw_floppy();\n\t}\n}", "static void floppy_start(void)\n{\n\treschedule_timeout(current_reqD, \"floppy start\");", "\tscandrives();\n\tdebug_dcl(DP->flags, \"setting NEWCHANGE in floppy_start\\n\");\n\tset_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);\n\tfloppy_ready();\n}", "/*\n * ========================================================================\n * here ends the bottom half. Exported routines are:\n * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc,\n * start_motor, reset_fdc, reset_fdc_info, interpret_errors.\n * Initialization also uses output_byte, result, set_dor, floppy_interrupt\n * and set_dor.\n * ========================================================================\n */\n/*\n * General purpose continuations.\n * ==============================\n */", "static void do_wakeup(void)\n{\n\treschedule_timeout(MAXTIMEOUT, \"do wakeup\");\n\tcont = NULL;\n\tcommand_status += 2;\n\twake_up(&command_done);\n}", "static const struct cont_t wakeup_cont = {\n\t.interrupt\t= empty,\n\t.redo\t\t= do_wakeup,\n\t.error\t\t= empty,\n\t.done\t\t= (done_f)empty\n};", "static const struct cont_t intr_cont = {\n\t.interrupt\t= empty,\n\t.redo\t\t= process_fd_request,\n\t.error\t\t= empty,\n\t.done\t\t= (done_f)empty\n};", "static int wait_til_done(void (*handler)(void), bool interruptible)\n{\n\tint ret;", "\tschedule_bh(handler);", "\tif (interruptible)\n\t\twait_event_interruptible(command_done, command_status >= 2);\n\telse\n\t\twait_event(command_done, command_status >= 2);", "\tif (command_status < 2) {\n\t\tcancel_activity();\n\t\tcont = &intr_cont;\n\t\treset_fdc();\n\t\treturn -EINTR;\n\t}", "\tif (FDCS->reset)\n\t\tcommand_status = FD_COMMAND_ERROR;\n\tif (command_status == FD_COMMAND_OKAY)\n\t\tret = 0;\n\telse\n\t\tret = -EIO;\n\tcommand_status = FD_COMMAND_NONE;\n\treturn ret;\n}", "static void generic_done(int result)\n{\n\tcommand_status = result;\n\tcont = &wakeup_cont;\n}", "static void generic_success(void)\n{\n\tcont->done(1);\n}", "static void generic_failure(void)\n{\n\tcont->done(0);\n}", "static void success_and_wakeup(void)\n{\n\tgeneric_success();\n\tcont->redo();\n}", "/*\n * formatting and rw support.\n * ==========================\n */", "static int next_valid_format(void)\n{\n\tint probed_format;", "\tprobed_format = DRS->probed_format;\n\twhile (1) {\n\t\tif (probed_format >= 8 || !DP->autodetect[probed_format]) {\n\t\t\tDRS->probed_format = 0;\n\t\t\treturn 1;\n\t\t}\n\t\tif (floppy_type[DP->autodetect[probed_format]].sect) {\n\t\t\tDRS->probed_format = probed_format;\n\t\t\treturn 0;\n\t\t}\n\t\tprobed_format++;\n\t}\n}", "static void bad_flp_intr(void)\n{\n\tint err_count;", "\tif (probing) {\n\t\tDRS->probed_format++;\n\t\tif (!next_valid_format())\n\t\t\treturn;\n\t}\n\terr_count = ++(*errors);\n\tINFBOUND(DRWE->badness, err_count);\n\tif (err_count > DP->max_errors.abort)\n\t\tcont->done(0);\n\tif (err_count > DP->max_errors.reset)\n\t\tFDCS->reset = 1;\n\telse if (err_count > DP->max_errors.recal)\n\t\tDRS->track = NEED_2_RECAL;\n}", "static void set_floppy(int drive)\n{\n\tint type = ITYPE(UDRS->fd_device);", "\tif (type)\n\t\t_floppy = floppy_type + type;\n\telse\n\t\t_floppy = current_type[drive];\n}", "/*\n * formatting support.\n * ===================\n */\nstatic void format_interrupt(void)\n{\n\tswitch (interpret_errors()) {\n\tcase 1:\n\t\tcont->error();\n\tcase 2:\n\t\tbreak;\n\tcase 0:\n\t\tcont->done(1);\n\t}\n\tcont->redo();\n}", "#define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1))\n#define CT(x) ((x) | 0xc0)", "static void setup_format_params(int track)\n{\n\tint n;\n\tint il;\n\tint count;\n\tint head_shift;\n\tint track_shift;\n\tstruct fparm {\n\t\tunsigned char track, head, sect, size;\n\t} *here = (struct fparm *)floppy_track_buffer;", "\traw_cmd = &default_raw_cmd;\n\traw_cmd->track = track;", "\traw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |\n\t\t\t FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);\n\traw_cmd->rate = _floppy->rate & 0x43;\n\traw_cmd->cmd_count = NR_F;\n\tCOMMAND = FM_MODE(_floppy, FD_FORMAT);\n\tDR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);\n\tF_SIZECODE = FD_SIZECODE(_floppy);\n\tF_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;\n\tF_GAP = _floppy->fmt_gap;\n\tF_FILL = FD_FILL_BYTE;", "\traw_cmd->kernel_data = floppy_track_buffer;\n\traw_cmd->length = 4 * F_SECT_PER_TRACK;", "\t/* allow for about 30ms for data transport per track */\n\thead_shift = (F_SECT_PER_TRACK + 5) / 6;", "\t/* a ``cylinder'' is two tracks plus a little stepping time */\n\ttrack_shift = 2 * head_shift + 3;", "\t/* position of logical sector 1 on this track */\n\tn = (track_shift * format_req.track + head_shift * format_req.head)\n\t % F_SECT_PER_TRACK;", "\t/* determine interleave */\n\til = 1;\n\tif (_floppy->fmt_gap < 0x22)\n\t\til++;", "\t/* initialize field */\n\tfor (count = 0; count < F_SECT_PER_TRACK; ++count) {\n\t\there[count].track = format_req.track;\n\t\there[count].head = format_req.head;\n\t\there[count].sect = 0;\n\t\there[count].size = F_SIZECODE;\n\t}\n\t/* place logical sectors */\n\tfor (count = 1; count <= F_SECT_PER_TRACK; ++count) {\n\t\there[n].sect = count;\n\t\tn = (n + il) % F_SECT_PER_TRACK;\n\t\tif (here[n].sect) {\t/* sector busy, find next free sector */\n\t\t\t++n;\n\t\t\tif (n >= F_SECT_PER_TRACK) {\n\t\t\t\tn -= F_SECT_PER_TRACK;\n\t\t\t\twhile (here[n].sect)\n\t\t\t\t\t++n;\n\t\t\t}\n\t\t}\n\t}\n\tif (_floppy->stretch & FD_SECTBASEMASK) {\n\t\tfor (count = 0; count < F_SECT_PER_TRACK; count++)\n\t\t\there[count].sect += FD_SECTBASE(_floppy) - 1;\n\t}\n}", "static void redo_format(void)\n{\n\tbuffer_track = -1;\n\tsetup_format_params(format_req.track << STRETCH(_floppy));\n\tfloppy_start();\n\tdebugt(__func__, \"queue format request\");\n}", "static const struct cont_t format_cont = {\n\t.interrupt\t= format_interrupt,\n\t.redo\t\t= redo_format,\n\t.error\t\t= bad_flp_intr,\n\t.done\t\t= generic_done\n};", "static int do_format(int drive, struct format_descr *tmp_format_req)\n{\n\tint ret;", "\tif (lock_fdc(drive, true))\n\t\treturn -EINTR;", "\tset_floppy(drive);\n\tif (!_floppy ||\n\t _floppy->track > DP->tracks ||\n\t tmp_format_req->track >= _floppy->track ||\n\t tmp_format_req->head >= _floppy->head ||\n\t (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) ||\n\t !_floppy->fmt_gap) {\n\t\tprocess_fd_request();\n\t\treturn -EINVAL;\n\t}\n\tformat_req = *tmp_format_req;\n\tformat_errors = 0;\n\tcont = &format_cont;\n\terrors = &format_errors;\n\tret = wait_til_done(redo_format, true);\n\tif (ret == -EINTR)\n\t\treturn -EINTR;\n\tprocess_fd_request();\n\treturn ret;\n}", "/*\n * Buffer read/write and support\n * =============================\n */", "static void floppy_end_request(struct request *req, int error)\n{\n\tunsigned int nr_sectors = current_count_sectors;\n\tunsigned int drive = (unsigned long)req->rq_disk->private_data;", "\t/* current_count_sectors can be zero if transfer failed */\n\tif (error)\n\t\tnr_sectors = blk_rq_cur_sectors(req);\n\tif (__blk_end_request(req, error, nr_sectors << 9))\n\t\treturn;", "\t/* We're done with the request */\n\tfloppy_off(drive);\n\tcurrent_req = NULL;\n}", "/* new request_done. Can handle physical sectors which are smaller than a\n * logical buffer */\nstatic void request_done(int uptodate)\n{\n\tstruct request *req = current_req;\n\tstruct request_queue *q;\n\tunsigned long flags;\n\tint block;\n\tchar msg[sizeof(\"request done \") + sizeof(int) * 3];", "\tprobing = 0;\n\tsnprintf(msg, sizeof(msg), \"request done %d\", uptodate);\n\treschedule_timeout(MAXTIMEOUT, msg);", "\tif (!req) {\n\t\tpr_info(\"floppy.c: no request in request_done\\n\");\n\t\treturn;\n\t}", "\tq = req->q;", "\tif (uptodate) {\n\t\t/* maintain values for invalidation on geometry\n\t\t * change */\n\t\tblock = current_count_sectors + blk_rq_pos(req);\n\t\tINFBOUND(DRS->maxblock, block);\n\t\tif (block > _floppy->sect)\n\t\t\tDRS->maxtrack = 1;", "\t\t/* unlock chained buffers */\n\t\tspin_lock_irqsave(q->queue_lock, flags);\n\t\tfloppy_end_request(req, 0);\n\t\tspin_unlock_irqrestore(q->queue_lock, flags);\n\t} else {\n\t\tif (rq_data_dir(req) == WRITE) {\n\t\t\t/* record write error information */\n\t\t\tDRWE->write_errors++;\n\t\t\tif (DRWE->write_errors == 1) {\n\t\t\t\tDRWE->first_error_sector = blk_rq_pos(req);\n\t\t\t\tDRWE->first_error_generation = DRS->generation;\n\t\t\t}\n\t\t\tDRWE->last_error_sector = blk_rq_pos(req);\n\t\t\tDRWE->last_error_generation = DRS->generation;\n\t\t}\n\t\tspin_lock_irqsave(q->queue_lock, flags);\n\t\tfloppy_end_request(req, -EIO);\n\t\tspin_unlock_irqrestore(q->queue_lock, flags);\n\t}\n}", "/* Interrupt handler evaluating the result of the r/w operation */\nstatic void rw_interrupt(void)\n{\n\tint eoc;\n\tint ssize;\n\tint heads;\n\tint nr_sectors;", "\tif (R_HEAD >= 2) {\n\t\t/* some Toshiba floppy controllers occasionnally seem to\n\t\t * return bogus interrupts after read/write operations, which\n\t\t * can be recognized by a bad head number (>= 2) */\n\t\treturn;\n\t}", "\tif (!DRS->first_read_date)\n\t\tDRS->first_read_date = jiffies;", "\tnr_sectors = 0;\n\tssize = DIV_ROUND_UP(1 << SIZECODE, 4);", "\tif (ST1 & ST1_EOC)\n\t\teoc = 1;\n\telse\n\t\teoc = 0;", "\tif (COMMAND & 0x80)\n\t\theads = 2;\n\telse\n\t\theads = 1;", "\tnr_sectors = (((R_TRACK - TRACK) * heads +\n\t\t R_HEAD - HEAD) * SECT_PER_TRACK +\n\t\t R_SECTOR - SECTOR + eoc) << SIZECODE >> 2;", "\tif (nr_sectors / ssize >\n\t DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) {\n\t\tDPRINT(\"long rw: %x instead of %lx\\n\",\n\t\t nr_sectors, current_count_sectors);\n\t\tpr_info(\"rs=%d s=%d\\n\", R_SECTOR, SECTOR);\n\t\tpr_info(\"rh=%d h=%d\\n\", R_HEAD, HEAD);\n\t\tpr_info(\"rt=%d t=%d\\n\", R_TRACK, TRACK);\n\t\tpr_info(\"heads=%d eoc=%d\\n\", heads, eoc);\n\t\tpr_info(\"spt=%d st=%d ss=%d\\n\",\n\t\t\tSECT_PER_TRACK, fsector_t, ssize);\n\t\tpr_info(\"in_sector_offset=%d\\n\", in_sector_offset);\n\t}", "\tnr_sectors -= in_sector_offset;\n\tINFBOUND(nr_sectors, 0);\n\tSUPBOUND(current_count_sectors, nr_sectors);", "\tswitch (interpret_errors()) {\n\tcase 2:\n\t\tcont->redo();\n\t\treturn;\n\tcase 1:\n\t\tif (!current_count_sectors) {\n\t\t\tcont->error();\n\t\t\tcont->redo();\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\tcase 0:\n\t\tif (!current_count_sectors) {\n\t\t\tcont->redo();\n\t\t\treturn;\n\t\t}\n\t\tcurrent_type[current_drive] = _floppy;\n\t\tfloppy_sizes[TOMINOR(current_drive)] = _floppy->size;\n\t\tbreak;\n\t}", "\tif (probing) {\n\t\tif (DP->flags & FTD_MSG)\n\t\t\tDPRINT(\"Auto-detected floppy type %s in fd%d\\n\",\n\t\t\t _floppy->name, current_drive);\n\t\tcurrent_type[current_drive] = _floppy;\n\t\tfloppy_sizes[TOMINOR(current_drive)] = _floppy->size;\n\t\tprobing = 0;\n\t}", "\tif (CT(COMMAND) != FD_READ ||\n\t raw_cmd->kernel_data == current_req->buffer) {\n\t\t/* transfer directly from buffer */\n\t\tcont->done(1);\n\t} else if (CT(COMMAND) == FD_READ) {\n\t\tbuffer_track = raw_cmd->track;\n\t\tbuffer_drive = current_drive;\n\t\tINFBOUND(buffer_max, nr_sectors + fsector_t);\n\t}\n\tcont->redo();\n}", "/* Compute maximal contiguous buffer size. */\nstatic int buffer_chain_size(void)\n{\n\tstruct bio_vec bv;\n\tint size;\n\tstruct req_iterator iter;\n\tchar *base;", "\tbase = bio_data(current_req->bio);\n\tsize = 0;", "\trq_for_each_segment(bv, current_req, iter) {\n\t\tif (page_address(bv.bv_page) + bv.bv_offset != base + size)\n\t\t\tbreak;", "\t\tsize += bv.bv_len;\n\t}", "\treturn size >> 9;\n}", "/* Compute the maximal transfer size */\nstatic int transfer_size(int ssize, int max_sector, int max_size)\n{\n\tSUPBOUND(max_sector, fsector_t + max_size);", "\t/* alignment */\n\tmax_sector -= (max_sector % _floppy->sect) % ssize;", "\t/* transfer size, beginning not aligned */\n\tcurrent_count_sectors = max_sector - fsector_t;", "\treturn max_sector;\n}", "/*\n * Move data from/to the track buffer to/from the buffer cache.\n */\nstatic void copy_buffer(int ssize, int max_sector, int max_sector_2)\n{\n\tint remaining;\t\t/* number of transferred 512-byte sectors */\n\tstruct bio_vec bv;\n\tchar *buffer;\n\tchar *dma_buffer;\n\tint size;\n\tstruct req_iterator iter;", "\tmax_sector = transfer_size(ssize,\n\t\t\t\t min(max_sector, max_sector_2),\n\t\t\t\t blk_rq_sectors(current_req));", "\tif (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&\n\t buffer_max > fsector_t + blk_rq_sectors(current_req))\n\t\tcurrent_count_sectors = min_t(int, buffer_max - fsector_t,\n\t\t\t\t\t blk_rq_sectors(current_req));", "\tremaining = current_count_sectors << 9;\n\tif (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) {\n\t\tDPRINT(\"in copy buffer\\n\");\n\t\tpr_info(\"current_count_sectors=%ld\\n\", current_count_sectors);\n\t\tpr_info(\"remaining=%d\\n\", remaining >> 9);\n\t\tpr_info(\"current_req->nr_sectors=%u\\n\",\n\t\t\tblk_rq_sectors(current_req));\n\t\tpr_info(\"current_req->current_nr_sectors=%u\\n\",\n\t\t\tblk_rq_cur_sectors(current_req));\n\t\tpr_info(\"max_sector=%d\\n\", max_sector);\n\t\tpr_info(\"ssize=%d\\n\", ssize);\n\t}", "\tbuffer_max = max(max_sector, buffer_max);", "\tdma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9);", "\tsize = blk_rq_cur_bytes(current_req);", "\trq_for_each_segment(bv, current_req, iter) {\n\t\tif (!remaining)\n\t\t\tbreak;", "\t\tsize = bv.bv_len;\n\t\tSUPBOUND(size, remaining);", "\t\tbuffer = page_address(bv.bv_page) + bv.bv_offset;\n\t\tif (dma_buffer + size >\n\t\t floppy_track_buffer + (max_buffer_sectors << 10) ||\n\t\t dma_buffer < floppy_track_buffer) {\n\t\t\tDPRINT(\"buffer overrun in copy buffer %d\\n\",\n\t\t\t (int)((floppy_track_buffer - dma_buffer) >> 9));\n\t\t\tpr_info(\"fsector_t=%d buffer_min=%d\\n\",\n\t\t\t\tfsector_t, buffer_min);\n\t\t\tpr_info(\"current_count_sectors=%ld\\n\",\n\t\t\t\tcurrent_count_sectors);\n\t\t\tif (CT(COMMAND) == FD_READ)\n\t\t\t\tpr_info(\"read\\n\");\n\t\t\tif (CT(COMMAND) == FD_WRITE)\n\t\t\t\tpr_info(\"write\\n\");\n\t\t\tbreak;\n\t\t}\n\t\tif (((unsigned long)buffer) % 512)\n\t\t\tDPRINT(\"%p buffer not aligned\\n\", buffer);", "\t\tif (CT(COMMAND) == FD_READ)\n\t\t\tmemcpy(buffer, dma_buffer, size);\n\t\telse\n\t\t\tmemcpy(dma_buffer, buffer, size);", "\t\tremaining -= size;\n\t\tdma_buffer += size;\n\t}\n\tif (remaining) {\n\t\tif (remaining > 0)\n\t\t\tmax_sector -= remaining >> 9;\n\t\tDPRINT(\"weirdness: remaining %d\\n\", remaining >> 9);\n\t}\n}", "/* work around a bug in pseudo DMA\n * (on some FDCs) pseudo DMA does not stop when the CPU stops\n * sending data. Hence we need a different way to signal the\n * transfer length: We use SECT_PER_TRACK. Unfortunately, this\n * does not work with MT, hence we can only transfer one head at\n * a time\n */\nstatic void virtualdmabug_workaround(void)\n{\n\tint hard_sectors;\n\tint end_sector;", "\tif (CT(COMMAND) == FD_WRITE) {\n\t\tCOMMAND &= ~0x80;\t/* switch off multiple track mode */", "\t\thard_sectors = raw_cmd->length >> (7 + SIZECODE);\n\t\tend_sector = SECTOR + hard_sectors - 1;\n\t\tif (end_sector > SECT_PER_TRACK) {\n\t\t\tpr_info(\"too many sectors %d > %d\\n\",\n\t\t\t\tend_sector, SECT_PER_TRACK);\n\t\t\treturn;\n\t\t}\n\t\tSECT_PER_TRACK = end_sector;\n\t\t\t\t\t/* make sure SECT_PER_TRACK\n\t\t\t\t\t * points to end of transfer */\n\t}\n}", "/*\n * Formulate a read/write request.\n * this routine decides where to load the data (directly to buffer, or to\n * tmp floppy area), how much data to load (the size of the buffer, the whole\n * track, or a single sector)\n * All floppy_track_buffer handling goes in here. If we ever add track buffer\n * allocation on the fly, it should be done here. No other part should need\n * modification.\n */", "static int make_raw_rw_request(void)\n{\n\tint aligned_sector_t;\n\tint max_sector;\n\tint max_size;\n\tint tracksize;\n\tint ssize;", "\tif (WARN(max_buffer_sectors == 0, \"VFS: Block I/O scheduled on unopened device\\n\"))\n\t\treturn 0;", "\tset_fdc((long)current_req->rq_disk->private_data);", "\traw_cmd = &default_raw_cmd;\n\traw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK;\n\traw_cmd->cmd_count = NR_RW;\n\tif (rq_data_dir(current_req) == READ) {\n\t\traw_cmd->flags |= FD_RAW_READ;\n\t\tCOMMAND = FM_MODE(_floppy, FD_READ);\n\t} else if (rq_data_dir(current_req) == WRITE) {\n\t\traw_cmd->flags |= FD_RAW_WRITE;\n\t\tCOMMAND = FM_MODE(_floppy, FD_WRITE);\n\t} else {\n\t\tDPRINT(\"%s: unknown command\\n\", __func__);\n\t\treturn 0;\n\t}", "\tmax_sector = _floppy->sect * _floppy->head;", "\tTRACK = (int)blk_rq_pos(current_req) / max_sector;\n\tfsector_t = (int)blk_rq_pos(current_req) % max_sector;\n\tif (_floppy->track && TRACK >= _floppy->track) {\n\t\tif (blk_rq_cur_sectors(current_req) & 1) {\n\t\t\tcurrent_count_sectors = 1;\n\t\t\treturn 1;\n\t\t} else\n\t\t\treturn 0;\n\t}\n\tHEAD = fsector_t / _floppy->sect;", "\tif (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) ||\n\t test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) &&\n\t fsector_t < _floppy->sect)\n\t\tmax_sector = _floppy->sect;", "\t/* 2M disks have phantom sectors on the first track */\n\tif ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) {\n\t\tmax_sector = 2 * _floppy->sect / 3;\n\t\tif (fsector_t >= max_sector) {\n\t\t\tcurrent_count_sectors =\n\t\t\t min_t(int, _floppy->sect - fsector_t,\n\t\t\t\t blk_rq_sectors(current_req));\n\t\t\treturn 1;\n\t\t}\n\t\tSIZECODE = 2;\n\t} else\n\t\tSIZECODE = FD_SIZECODE(_floppy);\n\traw_cmd->rate = _floppy->rate & 0x43;\n\tif ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2)\n\t\traw_cmd->rate = 1;", "\tif (SIZECODE)\n\t\tSIZECODE2 = 0xff;\n\telse\n\t\tSIZECODE2 = 0x80;\n\traw_cmd->track = TRACK << STRETCH(_floppy);\n\tDR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD);\n\tGAP = _floppy->gap;\n\tssize = DIV_ROUND_UP(1 << SIZECODE, 4);\n\tSECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;\n\tSECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) +\n\t FD_SECTBASE(_floppy);", "\t/* tracksize describes the size which can be filled up with sectors\n\t * of size ssize.\n\t */\n\ttracksize = _floppy->sect - _floppy->sect % ssize;\n\tif (tracksize < _floppy->sect) {\n\t\tSECT_PER_TRACK++;\n\t\tif (tracksize <= fsector_t % _floppy->sect)\n\t\t\tSECTOR--;", "\t\t/* if we are beyond tracksize, fill up using smaller sectors */\n\t\twhile (tracksize <= fsector_t % _floppy->sect) {\n\t\t\twhile (tracksize + ssize > _floppy->sect) {\n\t\t\t\tSIZECODE--;\n\t\t\t\tssize >>= 1;\n\t\t\t}\n\t\t\tSECTOR++;\n\t\t\tSECT_PER_TRACK++;\n\t\t\ttracksize += ssize;\n\t\t}\n\t\tmax_sector = HEAD * _floppy->sect + tracksize;\n\t} else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {\n\t\tmax_sector = _floppy->sect;\n\t} else if (!HEAD && CT(COMMAND) == FD_WRITE) {\n\t\t/* for virtual DMA bug workaround */\n\t\tmax_sector = _floppy->sect;\n\t}", "\tin_sector_offset = (fsector_t % _floppy->sect) % ssize;\n\taligned_sector_t = fsector_t - in_sector_offset;\n\tmax_size = blk_rq_sectors(current_req);\n\tif ((raw_cmd->track == buffer_track) &&\n\t (current_drive == buffer_drive) &&\n\t (fsector_t >= buffer_min) && (fsector_t < buffer_max)) {\n\t\t/* data already in track buffer */\n\t\tif (CT(COMMAND) == FD_READ) {\n\t\t\tcopy_buffer(1, max_sector, buffer_max);\n\t\t\treturn 1;\n\t\t}\n\t} else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) {\n\t\tif (CT(COMMAND) == FD_WRITE) {\n\t\t\tunsigned int sectors;", "\t\t\tsectors = fsector_t + blk_rq_sectors(current_req);\n\t\t\tif (sectors > ssize && sectors < ssize + ssize)\n\t\t\t\tmax_size = ssize + ssize;\n\t\t\telse\n\t\t\t\tmax_size = ssize;\n\t\t}\n\t\traw_cmd->flags &= ~FD_RAW_WRITE;\n\t\traw_cmd->flags |= FD_RAW_READ;\n\t\tCOMMAND = FM_MODE(_floppy, FD_READ);\n\t} else if ((unsigned long)current_req->buffer < MAX_DMA_ADDRESS) {\n\t\tunsigned long dma_limit;\n\t\tint direct, indirect;", "\t\tindirect =\n\t\t transfer_size(ssize, max_sector,\n\t\t\t\t max_buffer_sectors * 2) - fsector_t;", "\t\t/*\n\t\t * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide\n\t\t * on a 64 bit machine!\n\t\t */\n\t\tmax_size = buffer_chain_size();\n\t\tdma_limit = (MAX_DMA_ADDRESS -\n\t\t\t ((unsigned long)current_req->buffer)) >> 9;\n\t\tif ((unsigned long)max_size > dma_limit)\n\t\t\tmax_size = dma_limit;\n\t\t/* 64 kb boundaries */\n\t\tif (CROSS_64KB(current_req->buffer, max_size << 9))\n\t\t\tmax_size = (K_64 -\n\t\t\t\t ((unsigned long)current_req->buffer) %\n\t\t\t\t K_64) >> 9;\n\t\tdirect = transfer_size(ssize, max_sector, max_size) - fsector_t;\n\t\t/*\n\t\t * We try to read tracks, but if we get too many errors, we\n\t\t * go back to reading just one sector at a time.\n\t\t *\n\t\t * This means we should be able to read a sector even if there\n\t\t * are other bad sectors on this track.\n\t\t */\n\t\tif (!direct ||\n\t\t (indirect * 2 > direct * 3 &&\n\t\t *errors < DP->max_errors.read_track &&\n\t\t ((!probing ||\n\t\t (DP->read_track & (1 << DRS->probed_format)))))) {\n\t\t\tmax_size = blk_rq_sectors(current_req);\n\t\t} else {\n\t\t\traw_cmd->kernel_data = current_req->buffer;\n\t\t\traw_cmd->length = current_count_sectors << 9;\n\t\t\tif (raw_cmd->length == 0) {\n\t\t\t\tDPRINT(\"%s: zero dma transfer attempted\\n\", __func__);\n\t\t\t\tDPRINT(\"indirect=%d direct=%d fsector_t=%d\\n\",\n\t\t\t\t indirect, direct, fsector_t);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tvirtualdmabug_workaround();\n\t\t\treturn 2;\n\t\t}\n\t}", "\tif (CT(COMMAND) == FD_READ)\n\t\tmax_size = max_sector;\t/* unbounded */", "\t/* claim buffer track if needed */\n\tif (buffer_track != raw_cmd->track ||\t/* bad track */\n\t buffer_drive != current_drive ||\t/* bad drive */\n\t fsector_t > buffer_max ||\n\t fsector_t < buffer_min ||\n\t ((CT(COMMAND) == FD_READ ||\n\t (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) &&\n\t max_sector > 2 * max_buffer_sectors + buffer_min &&\n\t max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) {\n\t\t/* not enough space */\n\t\tbuffer_track = -1;\n\t\tbuffer_drive = current_drive;\n\t\tbuffer_max = buffer_min = aligned_sector_t;\n\t}\n\traw_cmd->kernel_data = floppy_track_buffer +\n\t\t((aligned_sector_t - buffer_min) << 9);", "\tif (CT(COMMAND) == FD_WRITE) {\n\t\t/* copy write buffer to track buffer.\n\t\t * if we get here, we know that the write\n\t\t * is either aligned or the data already in the buffer\n\t\t * (buffer will be overwritten) */\n\t\tif (in_sector_offset && buffer_track == -1)\n\t\t\tDPRINT(\"internal error offset !=0 on write\\n\");\n\t\tbuffer_track = raw_cmd->track;\n\t\tbuffer_drive = current_drive;\n\t\tcopy_buffer(ssize, max_sector,\n\t\t\t 2 * max_buffer_sectors + buffer_min);\n\t} else\n\t\ttransfer_size(ssize, max_sector,\n\t\t\t 2 * max_buffer_sectors + buffer_min -\n\t\t\t aligned_sector_t);", "\t/* round up current_count_sectors to get dma xfer size */\n\traw_cmd->length = in_sector_offset + current_count_sectors;\n\traw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1;\n\traw_cmd->length <<= 9;\n\tif ((raw_cmd->length < current_count_sectors << 9) ||\n\t (raw_cmd->kernel_data != current_req->buffer &&\n\t CT(COMMAND) == FD_WRITE &&\n\t (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||\n\t aligned_sector_t < buffer_min)) ||\n\t raw_cmd->length % (128 << SIZECODE) ||\n\t raw_cmd->length <= 0 || current_count_sectors <= 0) {\n\t\tDPRINT(\"fractionary current count b=%lx s=%lx\\n\",\n\t\t raw_cmd->length, current_count_sectors);\n\t\tif (raw_cmd->kernel_data != current_req->buffer)\n\t\t\tpr_info(\"addr=%d, length=%ld\\n\",\n\t\t\t\t(int)((raw_cmd->kernel_data -\n\t\t\t\t floppy_track_buffer) >> 9),\n\t\t\t\tcurrent_count_sectors);\n\t\tpr_info(\"st=%d ast=%d mse=%d msi=%d\\n\",\n\t\t\tfsector_t, aligned_sector_t, max_sector, max_size);\n\t\tpr_info(\"ssize=%x SIZECODE=%d\\n\", ssize, SIZECODE);\n\t\tpr_info(\"command=%x SECTOR=%d HEAD=%d, TRACK=%d\\n\",\n\t\t\tCOMMAND, SECTOR, HEAD, TRACK);\n\t\tpr_info(\"buffer drive=%d\\n\", buffer_drive);\n\t\tpr_info(\"buffer track=%d\\n\", buffer_track);\n\t\tpr_info(\"buffer_min=%d\\n\", buffer_min);\n\t\tpr_info(\"buffer_max=%d\\n\", buffer_max);\n\t\treturn 0;\n\t}", "\tif (raw_cmd->kernel_data != current_req->buffer) {\n\t\tif (raw_cmd->kernel_data < floppy_track_buffer ||\n\t\t current_count_sectors < 0 ||\n\t\t raw_cmd->length < 0 ||\n\t\t raw_cmd->kernel_data + raw_cmd->length >\n\t\t floppy_track_buffer + (max_buffer_sectors << 10)) {\n\t\t\tDPRINT(\"buffer overrun in schedule dma\\n\");\n\t\t\tpr_info(\"fsector_t=%d buffer_min=%d current_count=%ld\\n\",\n\t\t\t\tfsector_t, buffer_min, raw_cmd->length >> 9);\n\t\t\tpr_info(\"current_count_sectors=%ld\\n\",\n\t\t\t\tcurrent_count_sectors);\n\t\t\tif (CT(COMMAND) == FD_READ)\n\t\t\t\tpr_info(\"read\\n\");\n\t\t\tif (CT(COMMAND) == FD_WRITE)\n\t\t\t\tpr_info(\"write\\n\");\n\t\t\treturn 0;\n\t\t}\n\t} else if (raw_cmd->length > blk_rq_bytes(current_req) ||\n\t\t current_count_sectors > blk_rq_sectors(current_req)) {\n\t\tDPRINT(\"buffer overrun in direct transfer\\n\");\n\t\treturn 0;\n\t} else if (raw_cmd->length < current_count_sectors << 9) {\n\t\tDPRINT(\"more sectors than bytes\\n\");\n\t\tpr_info(\"bytes=%ld\\n\", raw_cmd->length >> 9);\n\t\tpr_info(\"sectors=%ld\\n\", current_count_sectors);\n\t}\n\tif (raw_cmd->length == 0) {\n\t\tDPRINT(\"zero dma transfer attempted from make_raw_request\\n\");\n\t\treturn 0;\n\t}", "\tvirtualdmabug_workaround();\n\treturn 2;\n}", "/*\n * Round-robin between our available drives, doing one request from each\n */\nstatic int set_next_request(void)\n{\n\tstruct request_queue *q;\n\tint old_pos = fdc_queue;", "\tdo {\n\t\tq = disks[fdc_queue]->queue;\n\t\tif (++fdc_queue == N_DRIVE)\n\t\t\tfdc_queue = 0;\n\t\tif (q) {\n\t\t\tcurrent_req = blk_fetch_request(q);\n\t\t\tif (current_req)\n\t\t\t\tbreak;\n\t\t}\n\t} while (fdc_queue != old_pos);", "\treturn current_req != NULL;\n}", "static void redo_fd_request(void)\n{\n\tint drive;\n\tint tmp;", "\tlastredo = jiffies;\n\tif (current_drive < N_DRIVE)\n\t\tfloppy_off(current_drive);", "do_request:\n\tif (!current_req) {\n\t\tint pending;", "\t\tspin_lock_irq(&floppy_lock);\n\t\tpending = set_next_request();\n\t\tspin_unlock_irq(&floppy_lock);\n\t\tif (!pending) {\n\t\t\tdo_floppy = NULL;\n\t\t\tunlock_fdc();\n\t\t\treturn;\n\t\t}\n\t}\n\tdrive = (long)current_req->rq_disk->private_data;\n\tset_fdc(drive);\n\treschedule_timeout(current_reqD, \"redo fd request\");", "\tset_floppy(drive);\n\traw_cmd = &default_raw_cmd;\n\traw_cmd->flags = 0;\n\tif (start_motor(redo_fd_request))\n\t\treturn;", "\tdisk_change(current_drive);\n\tif (test_bit(current_drive, &fake_change) ||\n\t test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) {\n\t\tDPRINT(\"disk absent or changed during operation\\n\");\n\t\trequest_done(0);\n\t\tgoto do_request;\n\t}\n\tif (!_floppy) {\t/* Autodetection */\n\t\tif (!probing) {\n\t\t\tDRS->probed_format = 0;\n\t\t\tif (next_valid_format()) {\n\t\t\t\tDPRINT(\"no autodetectable formats\\n\");\n\t\t\t\t_floppy = NULL;\n\t\t\t\trequest_done(0);\n\t\t\t\tgoto do_request;\n\t\t\t}\n\t\t}\n\t\tprobing = 1;\n\t\t_floppy = floppy_type + DP->autodetect[DRS->probed_format];\n\t} else\n\t\tprobing = 0;\n\terrors = &(current_req->errors);\n\ttmp = make_raw_rw_request();\n\tif (tmp < 2) {\n\t\trequest_done(tmp);\n\t\tgoto do_request;\n\t}", "\tif (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags))\n\t\ttwaddle();\n\tschedule_bh(floppy_start);\n\tdebugt(__func__, \"queue fd request\");\n\treturn;\n}", "static const struct cont_t rw_cont = {\n\t.interrupt\t= rw_interrupt,\n\t.redo\t\t= redo_fd_request,\n\t.error\t\t= bad_flp_intr,\n\t.done\t\t= request_done\n};", "static void process_fd_request(void)\n{\n\tcont = &rw_cont;\n\tschedule_bh(redo_fd_request);\n}", "static void do_fd_request(struct request_queue *q)\n{\n\tif (WARN(max_buffer_sectors == 0,\n\t\t \"VFS: %s called on non-open device\\n\", __func__))\n\t\treturn;", "\tif (WARN(atomic_read(&usage_count) == 0,\n\t\t \"warning: usage count=0, current_req=%p sect=%ld type=%x flags=%llx\\n\",\n\t\t current_req, (long)blk_rq_pos(current_req), current_req->cmd_type,\n\t\t (unsigned long long) current_req->cmd_flags))\n\t\treturn;", "\tif (test_and_set_bit(0, &fdc_busy)) {\n\t\t/* fdc busy, this new request will be treated when the\n\t\t current one is done */\n\t\tis_alive(__func__, \"old request running\");\n\t\treturn;\n\t}\n\tcommand_status = FD_COMMAND_NONE;\n\t__reschedule_timeout(MAXTIMEOUT, \"fd_request\");\n\tset_fdc(0);\n\tprocess_fd_request();\n\tis_alive(__func__, \"\");\n}", "static const struct cont_t poll_cont = {\n\t.interrupt\t= success_and_wakeup,\n\t.redo\t\t= floppy_ready,\n\t.error\t\t= generic_failure,\n\t.done\t\t= generic_done\n};", "static int poll_drive(bool interruptible, int flag)\n{\n\t/* no auto-sense, just clear dcl */\n\traw_cmd = &default_raw_cmd;\n\traw_cmd->flags = flag;\n\traw_cmd->track = 0;\n\traw_cmd->cmd_count = 0;\n\tcont = &poll_cont;\n\tdebug_dcl(DP->flags, \"setting NEWCHANGE in poll_drive\\n\");\n\tset_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);", "\treturn wait_til_done(floppy_ready, interruptible);\n}", "/*\n * User triggered reset\n * ====================\n */", "static void reset_intr(void)\n{\n\tpr_info(\"weird, reset interrupt called\\n\");\n}", "static const struct cont_t reset_cont = {\n\t.interrupt\t= reset_intr,\n\t.redo\t\t= success_and_wakeup,\n\t.error\t\t= generic_failure,\n\t.done\t\t= generic_done\n};", "static int user_reset_fdc(int drive, int arg, bool interruptible)\n{\n\tint ret;", "\tif (lock_fdc(drive, interruptible))\n\t\treturn -EINTR;", "\tif (arg == FD_RESET_ALWAYS)\n\t\tFDCS->reset = 1;\n\tif (FDCS->reset) {\n\t\tcont = &reset_cont;\n\t\tret = wait_til_done(reset_fdc, interruptible);\n\t\tif (ret == -EINTR)\n\t\t\treturn -EINTR;\n\t}\n\tprocess_fd_request();\n\treturn 0;\n}", "/*\n * Misc Ioctl's and support\n * ========================\n */\nstatic inline int fd_copyout(void __user *param, const void *address,\n\t\t\t unsigned long size)\n{\n\treturn copy_to_user(param, address, size) ? -EFAULT : 0;\n}", "static inline int fd_copyin(void __user *param, void *address,\n\t\t\t unsigned long size)\n{\n\treturn copy_from_user(address, param, size) ? -EFAULT : 0;\n}", "static const char *drive_name(int type, int drive)\n{\n\tstruct floppy_struct *floppy;", "\tif (type)\n\t\tfloppy = floppy_type + type;\n\telse {\n\t\tif (UDP->native_format)\n\t\t\tfloppy = floppy_type + UDP->native_format;\n\t\telse\n\t\t\treturn \"(null)\";\n\t}\n\tif (floppy->name)\n\t\treturn floppy->name;\n\telse\n\t\treturn \"(null)\";\n}", "/* raw commands */\nstatic void raw_cmd_done(int flag)\n{\n\tint i;", "\tif (!flag) {\n\t\traw_cmd->flags |= FD_RAW_FAILURE;\n\t\traw_cmd->flags |= FD_RAW_HARDFAILURE;\n\t} else {\n\t\traw_cmd->reply_count = inr;\n\t\tif (raw_cmd->reply_count > MAX_REPLIES)\n\t\t\traw_cmd->reply_count = 0;\n\t\tfor (i = 0; i < raw_cmd->reply_count; i++)\n\t\t\traw_cmd->reply[i] = reply_buffer[i];", "\t\tif (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) {\n\t\t\tunsigned long flags;\n\t\t\tflags = claim_dma_lock();\n\t\t\traw_cmd->length = fd_get_dma_residue();\n\t\t\trelease_dma_lock(flags);\n\t\t}", "\t\tif ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&\n\t\t (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))\n\t\t\traw_cmd->flags |= FD_RAW_FAILURE;", "\t\tif (disk_change(current_drive))\n\t\t\traw_cmd->flags |= FD_RAW_DISK_CHANGE;\n\t\telse\n\t\t\traw_cmd->flags &= ~FD_RAW_DISK_CHANGE;\n\t\tif (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)\n\t\t\tmotor_off_callback(current_drive);", "\t\tif (raw_cmd->next &&\n\t\t (!(raw_cmd->flags & FD_RAW_FAILURE) ||\n\t\t !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&\n\t\t ((raw_cmd->flags & FD_RAW_FAILURE) ||\n\t\t !(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) {\n\t\t\traw_cmd = raw_cmd->next;\n\t\t\treturn;\n\t\t}\n\t}\n\tgeneric_done(flag);\n}", "static const struct cont_t raw_cmd_cont = {\n\t.interrupt\t= success_and_wakeup,\n\t.redo\t\t= floppy_start,\n\t.error\t\t= generic_failure,\n\t.done\t\t= raw_cmd_done\n};", "static int raw_cmd_copyout(int cmd, void __user *param,\n\t\t\t\t struct floppy_raw_cmd *ptr)\n{\n\tint ret;", "\twhile (ptr) {", "\t\tret = copy_to_user(param, ptr, sizeof(*ptr));", "\t\tif (ret)\n\t\t\treturn -EFAULT;\n\t\tparam += sizeof(struct floppy_raw_cmd);\n\t\tif ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {\n\t\t\tif (ptr->length >= 0 &&\n\t\t\t ptr->length <= ptr->buffer_length) {\n\t\t\t\tlong length = ptr->buffer_length - ptr->length;\n\t\t\t\tret = fd_copyout(ptr->data, ptr->kernel_data,\n\t\t\t\t\t\t length);\n\t\t\t\tif (ret)\n\t\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\t\tptr = ptr->next;\n\t}", "\treturn 0;\n}", "static void raw_cmd_free(struct floppy_raw_cmd **ptr)\n{\n\tstruct floppy_raw_cmd *next;\n\tstruct floppy_raw_cmd *this;", "\tthis = *ptr;\n\t*ptr = NULL;\n\twhile (this) {\n\t\tif (this->buffer_length) {\n\t\t\tfd_dma_mem_free((unsigned long)this->kernel_data,\n\t\t\t\t\tthis->buffer_length);\n\t\t\tthis->buffer_length = 0;\n\t\t}\n\t\tnext = this->next;\n\t\tkfree(this);\n\t\tthis = next;\n\t}\n}", "static int raw_cmd_copyin(int cmd, void __user *param,\n\t\t\t\t struct floppy_raw_cmd **rcmd)\n{\n\tstruct floppy_raw_cmd *ptr;\n\tint ret;\n\tint i;", "\t*rcmd = NULL;", "loop:\n\tptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);\n\tif (!ptr)\n\t\treturn -ENOMEM;\n\t*rcmd = ptr;\n\tret = copy_from_user(ptr, param, sizeof(*ptr));\n\tptr->next = NULL;\n\tptr->buffer_length = 0;\n\tptr->kernel_data = NULL;\n\tif (ret)\n\t\treturn -EFAULT;\n\tparam += sizeof(struct floppy_raw_cmd);\n\tif (ptr->cmd_count > 33)\n\t\t\t/* the command may now also take up the space\n\t\t\t * initially intended for the reply & the\n\t\t\t * reply count. Needed for long 82078 commands\n\t\t\t * such as RESTORE, which takes ... 17 command\n\t\t\t * bytes. Murphy's law #137: When you reserve\n\t\t\t * 16 bytes for a structure, you'll one day\n\t\t\t * discover that you really need 17...\n\t\t\t */\n\t\treturn -EINVAL;", "\tfor (i = 0; i < 16; i++)\n\t\tptr->reply[i] = 0;\n\tptr->resultcode = 0;", "\tif (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {\n\t\tif (ptr->length <= 0)\n\t\t\treturn -EINVAL;\n\t\tptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);\n\t\tfallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);\n\t\tif (!ptr->kernel_data)\n\t\t\treturn -ENOMEM;\n\t\tptr->buffer_length = ptr->length;\n\t}\n\tif (ptr->flags & FD_RAW_WRITE) {\n\t\tret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\tif (ptr->flags & FD_RAW_MORE) {\n\t\trcmd = &(ptr->next);\n\t\tptr->rate &= 0x43;\n\t\tgoto loop;\n\t}", "\treturn 0;\n}", "static int raw_cmd_ioctl(int cmd, void __user *param)\n{\n\tstruct floppy_raw_cmd *my_raw_cmd;\n\tint drive;\n\tint ret2;\n\tint ret;", "\tif (FDCS->rawcmd <= 1)\n\t\tFDCS->rawcmd = 1;\n\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tif (FDC(drive) != fdc)\n\t\t\tcontinue;\n\t\tif (drive == current_drive) {\n\t\t\tif (UDRS->fd_ref > 1) {\n\t\t\t\tFDCS->rawcmd = 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else if (UDRS->fd_ref) {\n\t\t\tFDCS->rawcmd = 2;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (FDCS->reset)\n\t\treturn -EIO;", "\tret = raw_cmd_copyin(cmd, param, &my_raw_cmd);\n\tif (ret) {\n\t\traw_cmd_free(&my_raw_cmd);\n\t\treturn ret;\n\t}", "\traw_cmd = my_raw_cmd;\n\tcont = &raw_cmd_cont;\n\tret = wait_til_done(floppy_start, true);\n\tdebug_dcl(DP->flags, \"calling disk change from raw_cmd ioctl\\n\");", "\tif (ret != -EINTR && FDCS->reset)\n\t\tret = -EIO;", "\tDRS->track = NO_TRACK;", "\tret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);\n\tif (!ret)\n\t\tret = ret2;\n\traw_cmd_free(&my_raw_cmd);\n\treturn ret;\n}", "static int invalidate_drive(struct block_device *bdev)\n{\n\t/* invalidate the buffer track to force a reread */\n\tset_bit((long)bdev->bd_disk->private_data, &fake_change);\n\tprocess_fd_request();\n\tcheck_disk_change(bdev);\n\treturn 0;\n}", "static int set_geometry(unsigned int cmd, struct floppy_struct *g,\n\t\t\t int drive, int type, struct block_device *bdev)\n{\n\tint cnt;", "\t/* sanity checking for parameters. */\n\tif (g->sect <= 0 ||\n\t g->head <= 0 ||\n\t g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||\n\t /* check if reserved bits are set */\n\t (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)\n\t\treturn -EINVAL;\n\tif (type) {\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmutex_lock(&open_lock);\n\t\tif (lock_fdc(drive, true)) {\n\t\t\tmutex_unlock(&open_lock);\n\t\t\treturn -EINTR;\n\t\t}\n\t\tfloppy_type[type] = *g;\n\t\tfloppy_type[type].name = \"user format\";\n\t\tfor (cnt = type << 2; cnt < (type << 2) + 4; cnt++)\n\t\t\tfloppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =\n\t\t\t floppy_type[type].size + 1;\n\t\tprocess_fd_request();\n\t\tfor (cnt = 0; cnt < N_DRIVE; cnt++) {\n\t\t\tstruct block_device *bdev = opened_bdev[cnt];\n\t\t\tif (!bdev || ITYPE(drive_state[cnt].fd_device) != type)\n\t\t\t\tcontinue;\n\t\t\t__invalidate_device(bdev, true);\n\t\t}\n\t\tmutex_unlock(&open_lock);\n\t} else {\n\t\tint oldStretch;", "\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tif (cmd != FDDEFPRM) {\n\t\t\t/* notice a disk change immediately, else\n\t\t\t * we lose our settings immediately*/\n\t\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\toldStretch = g->stretch;\n\t\tuser_params[drive] = *g;\n\t\tif (buffer_drive == drive)\n\t\t\tSUPBOUND(buffer_max, user_params[drive].sect);\n\t\tcurrent_type[drive] = &user_params[drive];\n\t\tfloppy_sizes[drive] = user_params[drive].size;\n\t\tif (cmd == FDDEFPRM)\n\t\t\tDRS->keep_data = -1;\n\t\telse\n\t\t\tDRS->keep_data = 1;\n\t\t/* invalidation. Invalidate only when needed, i.e.\n\t\t * when there are already sectors in the buffer cache\n\t\t * whose number will change. This is useful, because\n\t\t * mtools often changes the geometry of the disk after\n\t\t * looking at the boot block */\n\t\tif (DRS->maxblock > user_params[drive].sect ||\n\t\t DRS->maxtrack ||\n\t\t ((user_params[drive].sect ^ oldStretch) &\n\t\t (FD_SWAPSIDES | FD_SECTBASEMASK)))\n\t\t\tinvalidate_drive(bdev);\n\t\telse\n\t\t\tprocess_fd_request();\n\t}\n\treturn 0;\n}", "/* handle obsolete ioctl's */\nstatic unsigned int ioctl_table[] = {\n\tFDCLRPRM,\n\tFDSETPRM,\n\tFDDEFPRM,\n\tFDGETPRM,\n\tFDMSGON,\n\tFDMSGOFF,\n\tFDFMTBEG,\n\tFDFMTTRK,\n\tFDFMTEND,\n\tFDSETEMSGTRESH,\n\tFDFLUSH,\n\tFDSETMAXERRS,\n\tFDGETMAXERRS,\n\tFDGETDRVTYP,\n\tFDSETDRVPRM,\n\tFDGETDRVPRM,\n\tFDGETDRVSTAT,\n\tFDPOLLDRVSTAT,\n\tFDRESET,\n\tFDGETFDCSTAT,\n\tFDWERRORCLR,\n\tFDWERRORGET,\n\tFDRAWCMD,\n\tFDEJECT,\n\tFDTWADDLE\n};", "static int normalize_ioctl(unsigned int *cmd, int *size)\n{\n\tint i;", "\tfor (i = 0; i < ARRAY_SIZE(ioctl_table); i++) {\n\t\tif ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) {\n\t\t\t*size = _IOC_SIZE(*cmd);\n\t\t\t*cmd = ioctl_table[i];\n\t\t\tif (*size > _IOC_SIZE(*cmd)) {\n\t\t\t\tpr_info(\"ioctl not yet supported\\n\");\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -EINVAL;\n}", "static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)\n{\n\tif (type)\n\t\t*g = &floppy_type[type];\n\telse {\n\t\tif (lock_fdc(drive, false))\n\t\t\treturn -EINTR;\n\t\tif (poll_drive(false, 0) == -EINTR)\n\t\t\treturn -EINTR;\n\t\tprocess_fd_request();\n\t\t*g = current_type[drive];\n\t}\n\tif (!*g)\n\t\treturn -ENODEV;\n\treturn 0;\n}", "static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo)\n{\n\tint drive = (long)bdev->bd_disk->private_data;\n\tint type = ITYPE(drive_state[drive].fd_device);\n\tstruct floppy_struct *g;\n\tint ret;", "\tret = get_floppy_geometry(drive, type, &g);\n\tif (ret)\n\t\treturn ret;", "\tgeo->heads = g->head;\n\tgeo->sectors = g->sect;\n\tgeo->cylinders = g->track;\n\treturn 0;\n}", "static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,\n\t\t unsigned long param)\n{\n\tint drive = (long)bdev->bd_disk->private_data;\n\tint type = ITYPE(UDRS->fd_device);\n\tint i;\n\tint ret;\n\tint size;\n\tunion inparam {\n\t\tstruct floppy_struct g;\t/* geometry */\n\t\tstruct format_descr f;\n\t\tstruct floppy_max_errors max_errors;\n\t\tstruct floppy_drive_params dp;\n\t} inparam;\t\t/* parameters coming from user space */\n\tconst void *outparam;\t/* parameters passed back to user space */", "\t/* convert compatibility eject ioctls into floppy eject ioctl.\n\t * We do this in order to provide a means to eject floppy disks before\n\t * installing the new fdutils package */\n\tif (cmd == CDROMEJECT ||\t/* CD-ROM eject */\n\t cmd == 0x6470) {\t\t/* SunOS floppy eject */\n\t\tDPRINT(\"obsolete eject ioctl\\n\");\n\t\tDPRINT(\"please use floppycontrol --eject\\n\");\n\t\tcmd = FDEJECT;\n\t}", "\tif (!((cmd & 0xff00) == 0x0200))\n\t\treturn -EINVAL;", "\t/* convert the old style command into a new style command */\n\tret = normalize_ioctl(&cmd, &size);\n\tif (ret)\n\t\treturn ret;", "\t/* permission checks */\n\tif (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) ||\n\t ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))\n\t\treturn -EPERM;", "\tif (WARN_ON(size < 0 || size > sizeof(inparam)))\n\t\treturn -EINVAL;", "\t/* copyin */\n\tmemset(&inparam, 0, sizeof(inparam));\n\tif (_IOC_DIR(cmd) & _IOC_WRITE) {\n\t\tret = fd_copyin((void __user *)param, &inparam, size);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\tswitch (cmd) {\n\tcase FDEJECT:\n\t\tif (UDRS->fd_ref != 1)\n\t\t\t/* somebody else has this drive open */\n\t\t\treturn -EBUSY;\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;", "\t\t/* do the actual eject. Fails on\n\t\t * non-Sparc architectures */\n\t\tret = fd_eject(UNIT(drive));", "\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t\tprocess_fd_request();\n\t\treturn ret;\n\tcase FDCLRPRM:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tcurrent_type[drive] = NULL;\n\t\tfloppy_sizes[drive] = MAX_DISK_SIZE << 1;\n\t\tUDRS->keep_data = 0;\n\t\treturn invalidate_drive(bdev);\n\tcase FDSETPRM:\n\tcase FDDEFPRM:\n\t\treturn set_geometry(cmd, &inparam.g, drive, type, bdev);\n\tcase FDGETPRM:\n\t\tret = get_floppy_geometry(drive, type,\n\t\t\t\t\t (struct floppy_struct **)&outparam);\n\t\tif (ret)\n\t\t\treturn ret;\n\t\tbreak;\n\tcase FDMSGON:\n\t\tUDP->flags |= FTD_MSG;\n\t\treturn 0;\n\tcase FDMSGOFF:\n\t\tUDP->flags &= ~FTD_MSG;\n\t\treturn 0;\n\tcase FDFMTBEG:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\treturn -EINTR;\n\t\tret = UDRS->flags;\n\t\tprocess_fd_request();\n\t\tif (ret & FD_VERIFY)\n\t\t\treturn -ENODEV;\n\t\tif (!(ret & FD_DISK_WRITABLE))\n\t\t\treturn -EROFS;\n\t\treturn 0;\n\tcase FDFMTTRK:\n\t\tif (UDRS->fd_ref != 1)\n\t\t\treturn -EBUSY;\n\t\treturn do_format(drive, &inparam.f);\n\tcase FDFMTEND:\n\tcase FDFLUSH:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\treturn invalidate_drive(bdev);\n\tcase FDSETEMSGTRESH:\n\t\tUDP->max_errors.reporting = (unsigned short)(param & 0x0f);\n\t\treturn 0;\n\tcase FDGETMAXERRS:\n\t\toutparam = &UDP->max_errors;\n\t\tbreak;\n\tcase FDSETMAXERRS:\n\t\tUDP->max_errors = inparam.max_errors;\n\t\tbreak;\n\tcase FDGETDRVTYP:\n\t\toutparam = drive_name(type, drive);\n\t\tSUPBOUND(size, strlen((const char *)outparam) + 1);\n\t\tbreak;\n\tcase FDSETDRVPRM:\n\t\t*UDP = inparam.dp;\n\t\tbreak;\n\tcase FDGETDRVPRM:\n\t\toutparam = UDP;\n\t\tbreak;\n\tcase FDPOLLDRVSTAT:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\treturn -EINTR;\n\t\tprocess_fd_request();\n\t\t/* fall through */\n\tcase FDGETDRVSTAT:\n\t\toutparam = UDRS;\n\t\tbreak;\n\tcase FDRESET:\n\t\treturn user_reset_fdc(drive, (int)param, true);\n\tcase FDGETFDCSTAT:\n\t\toutparam = UFDCS;\n\t\tbreak;\n\tcase FDWERRORCLR:\n\t\tmemset(UDRWE, 0, sizeof(*UDRWE));\n\t\treturn 0;\n\tcase FDWERRORGET:\n\t\toutparam = UDRWE;\n\t\tbreak;\n\tcase FDRAWCMD:\n\t\tif (type)\n\t\t\treturn -EINVAL;\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tset_floppy(drive);\n\t\ti = raw_cmd_ioctl(cmd, (void __user *)param);\n\t\tif (i == -EINTR)\n\t\t\treturn -EINTR;\n\t\tprocess_fd_request();\n\t\treturn i;\n\tcase FDTWADDLE:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\ttwaddle();\n\t\tprocess_fd_request();\n\t\treturn 0;\n\tdefault:\n\t\treturn -EINVAL;\n\t}", "\tif (_IOC_DIR(cmd) & _IOC_READ)\n\t\treturn fd_copyout((void __user *)param, outparam, size);", "\treturn 0;\n}", "static int fd_ioctl(struct block_device *bdev, fmode_t mode,\n\t\t\t unsigned int cmd, unsigned long param)\n{\n\tint ret;", "\tmutex_lock(&floppy_mutex);\n\tret = fd_locked_ioctl(bdev, mode, cmd, param);\n\tmutex_unlock(&floppy_mutex);", "\treturn ret;\n}", "static void __init config_types(void)\n{\n\tbool has_drive = false;\n\tint drive;", "\t/* read drive info out of physical CMOS */\n\tdrive = 0;\n\tif (!UDP->cmos)\n\t\tUDP->cmos = FLOPPY0_TYPE;\n\tdrive = 1;\n\tif (!UDP->cmos && FLOPPY1_TYPE)\n\t\tUDP->cmos = FLOPPY1_TYPE;", "\t/* FIXME: additional physical CMOS drive detection should go here */", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tunsigned int type = UDP->cmos;\n\t\tstruct floppy_drive_params *params;\n\t\tconst char *name = NULL;\n\t\tstatic char temparea[32];", "\t\tif (type < ARRAY_SIZE(default_drive_params)) {\n\t\t\tparams = &default_drive_params[type].params;\n\t\t\tif (type) {\n\t\t\t\tname = default_drive_params[type].name;\n\t\t\t\tallowed_drive_mask |= 1 << drive;\n\t\t\t} else\n\t\t\t\tallowed_drive_mask &= ~(1 << drive);\n\t\t} else {\n\t\t\tparams = &default_drive_params[0].params;\n\t\t\tsprintf(temparea, \"unknown type %d (usb?)\", type);\n\t\t\tname = temparea;\n\t\t}\n\t\tif (name) {\n\t\t\tconst char *prepend;\n\t\t\tif (!has_drive) {\n\t\t\t\tprepend = \"\";\n\t\t\t\thas_drive = true;\n\t\t\t\tpr_info(\"Floppy drive(s):\");\n\t\t\t} else {\n\t\t\t\tprepend = \",\";\n\t\t\t}", "\t\t\tpr_cont(\"%s fd%d is %s\", prepend, drive, name);\n\t\t}\n\t\t*UDP = *params;\n\t}", "\tif (has_drive)\n\t\tpr_cont(\"\\n\");\n}", "static void floppy_release(struct gendisk *disk, fmode_t mode)\n{\n\tint drive = (long)disk->private_data;", "\tmutex_lock(&floppy_mutex);\n\tmutex_lock(&open_lock);\n\tif (!UDRS->fd_ref--) {\n\t\tDPRINT(\"floppy_release with fd_ref == 0\");\n\t\tUDRS->fd_ref = 0;\n\t}\n\tif (!UDRS->fd_ref)\n\t\topened_bdev[drive] = NULL;\n\tmutex_unlock(&open_lock);\n\tmutex_unlock(&floppy_mutex);\n}", "/*\n * floppy_open check for aliasing (/dev/fd0 can be the same as\n * /dev/PS0 etc), and disallows simultaneous access to the same\n * drive with different device numbers.\n */\nstatic int floppy_open(struct block_device *bdev, fmode_t mode)\n{\n\tint drive = (long)bdev->bd_disk->private_data;\n\tint old_dev, new_dev;\n\tint try;\n\tint res = -EBUSY;\n\tchar *tmp;", "\tmutex_lock(&floppy_mutex);\n\tmutex_lock(&open_lock);\n\told_dev = UDRS->fd_device;\n\tif (opened_bdev[drive] && opened_bdev[drive] != bdev)\n\t\tgoto out2;", "\tif (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) {\n\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t}", "\tUDRS->fd_ref++;", "\topened_bdev[drive] = bdev;", "\tres = -ENXIO;", "\tif (!floppy_track_buffer) {\n\t\t/* if opening an ED drive, reserve a big buffer,\n\t\t * else reserve a small one */\n\t\tif ((UDP->cmos == 6) || (UDP->cmos == 5))\n\t\t\ttry = 64;\t/* Only 48 actually useful */\n\t\telse\n\t\t\ttry = 32;\t/* Only 24 actually useful */", "\t\ttmp = (char *)fd_dma_mem_alloc(1024 * try);\n\t\tif (!tmp && !floppy_track_buffer) {\n\t\t\ttry >>= 1;\t/* buffer only one side */\n\t\t\tINFBOUND(try, 16);\n\t\t\ttmp = (char *)fd_dma_mem_alloc(1024 * try);\n\t\t}\n\t\tif (!tmp && !floppy_track_buffer)\n\t\t\tfallback_on_nodma_alloc(&tmp, 2048 * try);\n\t\tif (!tmp && !floppy_track_buffer) {\n\t\t\tDPRINT(\"Unable to allocate DMA memory\\n\");\n\t\t\tgoto out;\n\t\t}\n\t\tif (floppy_track_buffer) {\n\t\t\tif (tmp)\n\t\t\t\tfd_dma_mem_free((unsigned long)tmp, try * 1024);\n\t\t} else {\n\t\t\tbuffer_min = buffer_max = -1;\n\t\t\tfloppy_track_buffer = tmp;\n\t\t\tmax_buffer_sectors = try;\n\t\t}\n\t}", "\tnew_dev = MINOR(bdev->bd_dev);\n\tUDRS->fd_device = new_dev;\n\tset_capacity(disks[drive], floppy_sizes[new_dev]);\n\tif (old_dev != -1 && old_dev != new_dev) {\n\t\tif (buffer_drive == drive)\n\t\t\tbuffer_track = -1;\n\t}", "\tif (UFDCS->rawcmd == 1)\n\t\tUFDCS->rawcmd = 2;", "\tif (!(mode & FMODE_NDELAY)) {\n\t\tif (mode & (FMODE_READ|FMODE_WRITE)) {\n\t\t\tUDRS->last_checked = 0;\n\t\t\tclear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);\n\t\t\tcheck_disk_change(bdev);\n\t\t\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags))\n\t\t\t\tgoto out;\n\t\t\tif (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags))\n\t\t\t\tgoto out;\n\t\t}\n\t\tres = -EROFS;\n\t\tif ((mode & FMODE_WRITE) &&\n\t\t !test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags))\n\t\t\tgoto out;\n\t}\n\tmutex_unlock(&open_lock);\n\tmutex_unlock(&floppy_mutex);\n\treturn 0;\nout:\n\tUDRS->fd_ref--;", "\tif (!UDRS->fd_ref)\n\t\topened_bdev[drive] = NULL;\nout2:\n\tmutex_unlock(&open_lock);\n\tmutex_unlock(&floppy_mutex);\n\treturn res;\n}", "/*\n * Check if the disk has been changed or if a change has been faked.\n */\nstatic unsigned int floppy_check_events(struct gendisk *disk,\n\t\t\t\t\tunsigned int clearing)\n{\n\tint drive = (long)disk->private_data;", "\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t test_bit(FD_VERIFY_BIT, &UDRS->flags))\n\t\treturn DISK_EVENT_MEDIA_CHANGE;", "\tif (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) {\n\t\tlock_fdc(drive, false);\n\t\tpoll_drive(false, 0);\n\t\tprocess_fd_request();\n\t}", "\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t test_bit(FD_VERIFY_BIT, &UDRS->flags) ||\n\t test_bit(drive, &fake_change) ||\n\t drive_no_geom(drive))\n\t\treturn DISK_EVENT_MEDIA_CHANGE;\n\treturn 0;\n}", "/*\n * This implements \"read block 0\" for floppy_revalidate().\n * Needed for format autodetection, checking whether there is\n * a disk in the drive, and whether that disk is writable.\n */", "struct rb0_cbdata {\n\tint drive;\n\tstruct completion complete;\n};", "static void floppy_rb0_cb(struct bio *bio, int err)\n{\n\tstruct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private;\n\tint drive = cbdata->drive;", "\tif (err) {\n\t\tpr_info(\"floppy: error %d while reading block 0\", err);\n\t\tset_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);\n\t}\n\tcomplete(&cbdata->complete);\n}", "static int __floppy_read_block_0(struct block_device *bdev, int drive)\n{\n\tstruct bio bio;\n\tstruct bio_vec bio_vec;\n\tstruct page *page;\n\tstruct rb0_cbdata cbdata;\n\tsize_t size;", "\tpage = alloc_page(GFP_NOIO);\n\tif (!page) {\n\t\tprocess_fd_request();\n\t\treturn -ENOMEM;\n\t}", "\tsize = bdev->bd_block_size;\n\tif (!size)\n\t\tsize = 1024;", "\tcbdata.drive = drive;", "\tbio_init(&bio);\n\tbio.bi_io_vec = &bio_vec;\n\tbio_vec.bv_page = page;\n\tbio_vec.bv_len = size;\n\tbio_vec.bv_offset = 0;\n\tbio.bi_vcnt = 1;\n\tbio.bi_iter.bi_size = size;\n\tbio.bi_bdev = bdev;\n\tbio.bi_iter.bi_sector = 0;\n\tbio.bi_flags = (1 << BIO_QUIET);\n\tbio.bi_private = &cbdata;\n\tbio.bi_end_io = floppy_rb0_cb;", "\tsubmit_bio(READ, &bio);\n\tprocess_fd_request();", "\tinit_completion(&cbdata.complete);\n\twait_for_completion(&cbdata.complete);", "\t__free_page(page);", "\treturn 0;\n}", "/* revalidate the floppy disk, i.e. trigger format autodetection by reading\n * the bootblock (block 0). \"Autodetection\" is also needed to check whether\n * there is a disk in the drive at all... Thus we also do it for fixed\n * geometry formats */\nstatic int floppy_revalidate(struct gendisk *disk)\n{\n\tint drive = (long)disk->private_data;\n\tint cf;\n\tint res = 0;", "\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t test_bit(FD_VERIFY_BIT, &UDRS->flags) ||\n\t test_bit(drive, &fake_change) ||\n\t drive_no_geom(drive)) {\n\t\tif (WARN(atomic_read(&usage_count) == 0,\n\t\t\t \"VFS: revalidate called on non-open device.\\n\"))\n\t\t\treturn -EFAULT;", "\t\tlock_fdc(drive, false);\n\t\tcf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t\t test_bit(FD_VERIFY_BIT, &UDRS->flags));\n\t\tif (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) {\n\t\t\tprocess_fd_request();\t/*already done by another thread */\n\t\t\treturn 0;\n\t\t}\n\t\tUDRS->maxblock = 0;\n\t\tUDRS->maxtrack = 0;\n\t\tif (buffer_drive == drive)\n\t\t\tbuffer_track = -1;\n\t\tclear_bit(drive, &fake_change);\n\t\tclear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tif (cf)\n\t\t\tUDRS->generation++;\n\t\tif (drive_no_geom(drive)) {\n\t\t\t/* auto-sensing */\n\t\t\tres = __floppy_read_block_0(opened_bdev[drive], drive);\n\t\t} else {\n\t\t\tif (cf)\n\t\t\t\tpoll_drive(false, FD_RAW_NEED_DISK);\n\t\t\tprocess_fd_request();\n\t\t}\n\t}\n\tset_capacity(disk, floppy_sizes[UDRS->fd_device]);\n\treturn res;\n}", "static const struct block_device_operations floppy_fops = {\n\t.owner\t\t\t= THIS_MODULE,\n\t.open\t\t\t= floppy_open,\n\t.release\t\t= floppy_release,\n\t.ioctl\t\t\t= fd_ioctl,\n\t.getgeo\t\t\t= fd_getgeo,\n\t.check_events\t\t= floppy_check_events,\n\t.revalidate_disk\t= floppy_revalidate,\n};", "/*\n * Floppy Driver initialization\n * =============================\n */", "/* Determine the floppy disk controller type */\n/* This routine was written by David C. Niemi */\nstatic char __init get_fdc_version(void)\n{\n\tint r;", "\toutput_byte(FD_DUMPREGS);\t/* 82072 and better know DUMPREGS */\n\tif (FDCS->reset)\n\t\treturn FDC_NONE;\n\tr = result();\n\tif (r <= 0x00)\n\t\treturn FDC_NONE;\t/* No FDC present ??? */\n\tif ((r == 1) && (reply_buffer[0] == 0x80)) {\n\t\tpr_info(\"FDC %d is an 8272A\\n\", fdc);\n\t\treturn FDC_8272A;\t/* 8272a/765 don't know DUMPREGS */\n\t}\n\tif (r != 10) {\n\t\tpr_info(\"FDC %d init: DUMPREGS: unexpected return of %d bytes.\\n\",\n\t\t\tfdc, r);\n\t\treturn FDC_UNKNOWN;\n\t}", "\tif (!fdc_configure()) {\n\t\tpr_info(\"FDC %d is an 82072\\n\", fdc);\n\t\treturn FDC_82072;\t/* 82072 doesn't know CONFIGURE */\n\t}", "\toutput_byte(FD_PERPENDICULAR);\n\tif (need_more_output() == MORE_OUTPUT) {\n\t\toutput_byte(0);\n\t} else {\n\t\tpr_info(\"FDC %d is an 82072A\\n\", fdc);\n\t\treturn FDC_82072A;\t/* 82072A as found on Sparcs. */\n\t}", "\toutput_byte(FD_UNLOCK);\n\tr = result();\n\tif ((r == 1) && (reply_buffer[0] == 0x80)) {\n\t\tpr_info(\"FDC %d is a pre-1991 82077\\n\", fdc);\n\t\treturn FDC_82077_ORIG;\t/* Pre-1991 82077, doesn't know\n\t\t\t\t\t * LOCK/UNLOCK */\n\t}\n\tif ((r != 1) || (reply_buffer[0] != 0x00)) {\n\t\tpr_info(\"FDC %d init: UNLOCK: unexpected return of %d bytes.\\n\",\n\t\t\tfdc, r);\n\t\treturn FDC_UNKNOWN;\n\t}\n\toutput_byte(FD_PARTID);\n\tr = result();\n\tif (r != 1) {\n\t\tpr_info(\"FDC %d init: PARTID: unexpected return of %d bytes.\\n\",\n\t\t\tfdc, r);\n\t\treturn FDC_UNKNOWN;\n\t}\n\tif (reply_buffer[0] == 0x80) {\n\t\tpr_info(\"FDC %d is a post-1991 82077\\n\", fdc);\n\t\treturn FDC_82077;\t/* Revised 82077AA passes all the tests */\n\t}\n\tswitch (reply_buffer[0] >> 5) {\n\tcase 0x0:\n\t\t/* Either a 82078-1 or a 82078SL running at 5Volt */\n\t\tpr_info(\"FDC %d is an 82078.\\n\", fdc);\n\t\treturn FDC_82078;\n\tcase 0x1:\n\t\tpr_info(\"FDC %d is a 44pin 82078\\n\", fdc);\n\t\treturn FDC_82078;\n\tcase 0x2:\n\t\tpr_info(\"FDC %d is a S82078B\\n\", fdc);\n\t\treturn FDC_S82078B;\n\tcase 0x3:\n\t\tpr_info(\"FDC %d is a National Semiconductor PC87306\\n\", fdc);\n\t\treturn FDC_87306;\n\tdefault:\n\t\tpr_info(\"FDC %d init: 82078 variant with unknown PARTID=%d.\\n\",\n\t\t\tfdc, reply_buffer[0] >> 5);\n\t\treturn FDC_82078_UNKN;\n\t}\n}\t\t\t\t/* get_fdc_version */", "/* lilo configuration */", "static void __init floppy_set_flags(int *ints, int param, int param2)\n{\n\tint i;", "\tfor (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {\n\t\tif (param)\n\t\t\tdefault_drive_params[i].params.flags |= param2;\n\t\telse\n\t\t\tdefault_drive_params[i].params.flags &= ~param2;\n\t}\n\tDPRINT(\"%s flag 0x%x\\n\", param2 ? \"Setting\" : \"Clearing\", param);\n}", "static void __init daring(int *ints, int param, int param2)\n{\n\tint i;", "\tfor (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {\n\t\tif (param) {\n\t\t\tdefault_drive_params[i].params.select_delay = 0;\n\t\t\tdefault_drive_params[i].params.flags |=\n\t\t\t FD_SILENT_DCL_CLEAR;\n\t\t} else {\n\t\t\tdefault_drive_params[i].params.select_delay =\n\t\t\t 2 * HZ / 100;\n\t\t\tdefault_drive_params[i].params.flags &=\n\t\t\t ~FD_SILENT_DCL_CLEAR;\n\t\t}\n\t}\n\tDPRINT(\"Assuming %s floppy hardware\\n\", param ? \"standard\" : \"broken\");\n}", "static void __init set_cmos(int *ints, int dummy, int dummy2)\n{\n\tint current_drive = 0;", "\tif (ints[0] != 2) {\n\t\tDPRINT(\"wrong number of parameters for CMOS\\n\");\n\t\treturn;\n\t}\n\tcurrent_drive = ints[1];\n\tif (current_drive < 0 || current_drive >= 8) {\n\t\tDPRINT(\"bad drive for set_cmos\\n\");\n\t\treturn;\n\t}\n#if N_FDC > 1\n\tif (current_drive >= 4 && !FDC2)\n\t\tFDC2 = 0x370;\n#endif\n\tDP->cmos = ints[2];\n\tDPRINT(\"setting CMOS code to %d\\n\", ints[2]);\n}", "static struct param_table {\n\tconst char *name;\n\tvoid (*fn) (int *ints, int param, int param2);\n\tint *var;\n\tint def_param;\n\tint param2;\n} config_params[] __initdata = {\n\t{\"allowed_drive_mask\", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */\n\t{\"all_drives\", NULL, &allowed_drive_mask, 0xff, 0},\t/* obsolete */\n\t{\"asus_pci\", NULL, &allowed_drive_mask, 0x33, 0},\n\t{\"irq\", NULL, &FLOPPY_IRQ, 6, 0},\n\t{\"dma\", NULL, &FLOPPY_DMA, 2, 0},\n\t{\"daring\", daring, NULL, 1, 0},\n#if N_FDC > 1\n\t{\"two_fdc\", NULL, &FDC2, 0x370, 0},\n\t{\"one_fdc\", NULL, &FDC2, 0, 0},\n#endif\n\t{\"thinkpad\", floppy_set_flags, NULL, 1, FD_INVERTED_DCL},\n\t{\"broken_dcl\", floppy_set_flags, NULL, 1, FD_BROKEN_DCL},\n\t{\"messages\", floppy_set_flags, NULL, 1, FTD_MSG},\n\t{\"silent_dcl_clear\", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR},\n\t{\"debug\", floppy_set_flags, NULL, 1, FD_DEBUG},\n\t{\"nodma\", NULL, &can_use_virtual_dma, 1, 0},\n\t{\"omnibook\", NULL, &can_use_virtual_dma, 1, 0},\n\t{\"yesdma\", NULL, &can_use_virtual_dma, 0, 0},\n\t{\"fifo_depth\", NULL, &fifo_depth, 0xa, 0},\n\t{\"nofifo\", NULL, &no_fifo, 0x20, 0},\n\t{\"usefifo\", NULL, &no_fifo, 0, 0},\n\t{\"cmos\", set_cmos, NULL, 0, 0},\n\t{\"slow\", NULL, &slow_floppy, 1, 0},\n\t{\"unexpected_interrupts\", NULL, &print_unex, 1, 0},\n\t{\"no_unexpected_interrupts\", NULL, &print_unex, 0, 0},\n\t{\"L40SX\", NULL, &print_unex, 0, 0}", "\tEXTRA_FLOPPY_PARAMS\n};", "static int __init floppy_setup(char *str)\n{\n\tint i;\n\tint param;\n\tint ints[11];", "\tstr = get_options(str, ARRAY_SIZE(ints), ints);\n\tif (str) {\n\t\tfor (i = 0; i < ARRAY_SIZE(config_params); i++) {\n\t\t\tif (strcmp(str, config_params[i].name) == 0) {\n\t\t\t\tif (ints[0])\n\t\t\t\t\tparam = ints[1];\n\t\t\t\telse\n\t\t\t\t\tparam = config_params[i].def_param;\n\t\t\t\tif (config_params[i].fn)\n\t\t\t\t\tconfig_params[i].fn(ints, param,\n\t\t\t\t\t\t\t config_params[i].\n\t\t\t\t\t\t\t param2);\n\t\t\t\tif (config_params[i].var) {\n\t\t\t\t\tDPRINT(\"%s=%d\\n\", str, param);\n\t\t\t\t\t*config_params[i].var = param;\n\t\t\t\t}\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\tif (str) {\n\t\tDPRINT(\"unknown floppy option [%s]\\n\", str);", "\t\tDPRINT(\"allowed options are:\");\n\t\tfor (i = 0; i < ARRAY_SIZE(config_params); i++)\n\t\t\tpr_cont(\" %s\", config_params[i].name);\n\t\tpr_cont(\"\\n\");\n\t} else\n\t\tDPRINT(\"botched floppy option\\n\");\n\tDPRINT(\"Read Documentation/blockdev/floppy.txt\\n\");\n\treturn 0;\n}", "static int have_no_fdc = -ENODEV;", "static ssize_t floppy_cmos_show(struct device *dev,\n\t\t\t\tstruct device_attribute *attr, char *buf)\n{\n\tstruct platform_device *p = to_platform_device(dev);\n\tint drive;", "\tdrive = p->id;\n\treturn sprintf(buf, \"%X\\n\", UDP->cmos);\n}", "static DEVICE_ATTR(cmos, S_IRUGO, floppy_cmos_show, NULL);", "static void floppy_device_release(struct device *dev)\n{\n}", "static int floppy_resume(struct device *dev)\n{\n\tint fdc;", "\tfor (fdc = 0; fdc < N_FDC; fdc++)\n\t\tif (FDCS->address != -1)\n\t\t\tuser_reset_fdc(-1, FD_RESET_ALWAYS, false);", "\treturn 0;\n}", "static const struct dev_pm_ops floppy_pm_ops = {\n\t.resume = floppy_resume,\n\t.restore = floppy_resume,\n};", "static struct platform_driver floppy_driver = {\n\t.driver = {\n\t\t .name = \"floppy\",\n\t\t .pm = &floppy_pm_ops,\n\t},\n};", "static struct platform_device floppy_device[N_DRIVE];", "static bool floppy_available(int drive)\n{\n\tif (!(allowed_drive_mask & (1 << drive)))\n\t\treturn false;\n\tif (fdc_state[FDC(drive)].version == FDC_NONE)\n\t\treturn false;\n\treturn true;\n}", "static struct kobject *floppy_find(dev_t dev, int *part, void *data)\n{\n\tint drive = (*part & 3) | ((*part & 0x80) >> 5);\n\tif (drive >= N_DRIVE || !floppy_available(drive))\n\t\treturn NULL;\n\tif (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type))\n\t\treturn NULL;\n\t*part = 0;\n\treturn get_disk(disks[drive]);\n}", "static int __init do_floppy_init(void)\n{\n\tint i, unit, drive, err;", "\tset_debugt();\n\tinterruptjiffies = resultjiffies = jiffies;", "#if defined(CONFIG_PPC)\n\tif (check_legacy_ioport(FDC1))\n\t\treturn -ENODEV;\n#endif", "\traw_cmd = NULL;", "\tfloppy_wq = alloc_ordered_workqueue(\"floppy\", 0);\n\tif (!floppy_wq)\n\t\treturn -ENOMEM;", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tdisks[drive] = alloc_disk(1);\n\t\tif (!disks[drive]) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_put_disk;\n\t\t}", "\t\tdisks[drive]->queue = blk_init_queue(do_fd_request, &floppy_lock);\n\t\tif (!disks[drive]->queue) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_put_disk;\n\t\t}", "\t\tblk_queue_max_hw_sectors(disks[drive]->queue, 64);\n\t\tdisks[drive]->major = FLOPPY_MAJOR;\n\t\tdisks[drive]->first_minor = TOMINOR(drive);\n\t\tdisks[drive]->fops = &floppy_fops;\n\t\tsprintf(disks[drive]->disk_name, \"fd%d\", drive);", "\t\tinit_timer(&motor_off_timer[drive]);\n\t\tmotor_off_timer[drive].data = drive;\n\t\tmotor_off_timer[drive].function = motor_off_callback;\n\t}", "\terr = register_blkdev(FLOPPY_MAJOR, \"fd\");\n\tif (err)\n\t\tgoto out_put_disk;", "\terr = platform_driver_register(&floppy_driver);\n\tif (err)\n\t\tgoto out_unreg_blkdev;", "\tblk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,\n\t\t\t floppy_find, NULL, NULL);", "\tfor (i = 0; i < 256; i++)\n\t\tif (ITYPE(i))\n\t\t\tfloppy_sizes[i] = floppy_type[ITYPE(i)].size;\n\t\telse\n\t\t\tfloppy_sizes[i] = MAX_DISK_SIZE << 1;", "\treschedule_timeout(MAXTIMEOUT, \"floppy init\");\n\tconfig_types();", "\tfor (i = 0; i < N_FDC; i++) {\n\t\tfdc = i;\n\t\tmemset(FDCS, 0, sizeof(*FDCS));\n\t\tFDCS->dtr = -1;\n\t\tFDCS->dor = 0x4;\n#if defined(__sparc__) || defined(__mc68000__)\n\t/*sparcs/sun3x don't have a DOR reset which we can fall back on to */\n#ifdef __mc68000__\n\t\tif (MACH_IS_SUN3X)\n#endif\n\t\t\tFDCS->version = FDC_82072A;\n#endif\n\t}", "\tuse_virtual_dma = can_use_virtual_dma & 1;\n\tfdc_state[0].address = FDC1;\n\tif (fdc_state[0].address == -1) {\n\t\tcancel_delayed_work(&fd_timeout);\n\t\terr = -ENODEV;\n\t\tgoto out_unreg_region;\n\t}\n#if N_FDC > 1\n\tfdc_state[1].address = FDC2;\n#endif", "\tfdc = 0;\t\t/* reset fdc in case of unexpected interrupt */\n\terr = floppy_grab_irq_and_dma();\n\tif (err) {\n\t\tcancel_delayed_work(&fd_timeout);\n\t\terr = -EBUSY;\n\t\tgoto out_unreg_region;\n\t}", "\t/* initialise drive state */\n\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tmemset(UDRS, 0, sizeof(*UDRS));\n\t\tmemset(UDRWE, 0, sizeof(*UDRWE));\n\t\tset_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);\n\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t\tUDRS->fd_device = -1;\n\t\tfloppy_track_buffer = NULL;\n\t\tmax_buffer_sectors = 0;\n\t}\n\t/*\n\t * Small 10 msec delay to let through any interrupt that\n\t * initialization might have triggered, to not\n\t * confuse detection:\n\t */\n\tmsleep(10);", "\tfor (i = 0; i < N_FDC; i++) {\n\t\tfdc = i;\n\t\tFDCS->driver_version = FD_DRIVER_VERSION;\n\t\tfor (unit = 0; unit < 4; unit++)\n\t\t\tFDCS->track[unit] = 0;\n\t\tif (FDCS->address == -1)\n\t\t\tcontinue;\n\t\tFDCS->rawcmd = 2;\n\t\tif (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) {\n\t\t\t/* free ioports reserved by floppy_grab_irq_and_dma() */\n\t\t\tfloppy_release_regions(fdc);\n\t\t\tFDCS->address = -1;\n\t\t\tFDCS->version = FDC_NONE;\n\t\t\tcontinue;\n\t\t}\n\t\t/* Try to determine the floppy controller type */\n\t\tFDCS->version = get_fdc_version();\n\t\tif (FDCS->version == FDC_NONE) {\n\t\t\t/* free ioports reserved by floppy_grab_irq_and_dma() */\n\t\t\tfloppy_release_regions(fdc);\n\t\t\tFDCS->address = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)\n\t\t\tcan_use_virtual_dma = 0;", "\t\thave_no_fdc = 0;\n\t\t/* Not all FDCs seem to be able to handle the version command\n\t\t * properly, so force a reset for the standard FDC clones,\n\t\t * to avoid interrupt garbage.\n\t\t */\n\t\tuser_reset_fdc(-1, FD_RESET_ALWAYS, false);\n\t}\n\tfdc = 0;\n\tcancel_delayed_work(&fd_timeout);\n\tcurrent_drive = 0;\n\tinitialized = true;\n\tif (have_no_fdc) {\n\t\tDPRINT(\"no floppy controllers found\\n\");\n\t\terr = have_no_fdc;\n\t\tgoto out_release_dma;\n\t}", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tif (!floppy_available(drive))\n\t\t\tcontinue;", "\t\tfloppy_device[drive].name = floppy_device_name;\n\t\tfloppy_device[drive].id = drive;\n\t\tfloppy_device[drive].dev.release = floppy_device_release;", "\t\terr = platform_device_register(&floppy_device[drive]);\n\t\tif (err)\n\t\t\tgoto out_remove_drives;", "\t\terr = device_create_file(&floppy_device[drive].dev,\n\t\t\t\t\t &dev_attr_cmos);\n\t\tif (err)\n\t\t\tgoto out_unreg_platform_dev;", "\t\t/* to be cleaned up... */\n\t\tdisks[drive]->private_data = (void *)(long)drive;\n\t\tdisks[drive]->flags |= GENHD_FL_REMOVABLE;\n\t\tdisks[drive]->driverfs_dev = &floppy_device[drive].dev;\n\t\tadd_disk(disks[drive]);\n\t}", "\treturn 0;", "out_unreg_platform_dev:\n\tplatform_device_unregister(&floppy_device[drive]);\nout_remove_drives:\n\twhile (drive--) {\n\t\tif (floppy_available(drive)) {\n\t\t\tdel_gendisk(disks[drive]);\n\t\t\tdevice_remove_file(&floppy_device[drive].dev, &dev_attr_cmos);\n\t\t\tplatform_device_unregister(&floppy_device[drive]);\n\t\t}\n\t}\nout_release_dma:\n\tif (atomic_read(&usage_count))\n\t\tfloppy_release_irq_and_dma();\nout_unreg_region:\n\tblk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);\n\tplatform_driver_unregister(&floppy_driver);\nout_unreg_blkdev:\n\tunregister_blkdev(FLOPPY_MAJOR, \"fd\");\nout_put_disk:\n\tdestroy_workqueue(floppy_wq);\n\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tif (!disks[drive])\n\t\t\tbreak;\n\t\tif (disks[drive]->queue) {\n\t\t\tdel_timer_sync(&motor_off_timer[drive]);\n\t\t\tblk_cleanup_queue(disks[drive]->queue);\n\t\t\tdisks[drive]->queue = NULL;\n\t\t}\n\t\tput_disk(disks[drive]);\n\t}\n\treturn err;\n}", "#ifndef MODULE\nstatic __init void floppy_async_init(void *data, async_cookie_t cookie)\n{\n\tdo_floppy_init();\n}\n#endif", "static int __init floppy_init(void)\n{\n#ifdef MODULE\n\treturn do_floppy_init();\n#else\n\t/* Don't hold up the bootup by the floppy initialization */\n\tasync_schedule(floppy_async_init, NULL);\n\treturn 0;\n#endif\n}", "static const struct io_region {\n\tint offset;\n\tint size;\n} io_regions[] = {\n\t{ 2, 1 },\n\t/* address + 3 is sometimes reserved by pnp bios for motherboard */\n\t{ 4, 2 },\n\t/* address + 6 is reserved, and may be taken by IDE.\n\t * Unfortunately, Adaptec doesn't know this :-(, */\n\t{ 7, 1 },\n};", "static void floppy_release_allocated_regions(int fdc, const struct io_region *p)\n{\n\twhile (p != io_regions) {\n\t\tp--;\n\t\trelease_region(FDCS->address + p->offset, p->size);\n\t}\n}", "#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))", "static int floppy_request_regions(int fdc)\n{\n\tconst struct io_region *p;", "\tfor (p = io_regions; p < ARRAY_END(io_regions); p++) {\n\t\tif (!request_region(FDCS->address + p->offset,\n\t\t\t\t p->size, \"floppy\")) {\n\t\t\tDPRINT(\"Floppy io-port 0x%04lx in use\\n\",\n\t\t\t FDCS->address + p->offset);\n\t\t\tfloppy_release_allocated_regions(fdc, p);\n\t\t\treturn -EBUSY;\n\t\t}\n\t}\n\treturn 0;\n}", "static void floppy_release_regions(int fdc)\n{\n\tfloppy_release_allocated_regions(fdc, ARRAY_END(io_regions));\n}", "static int floppy_grab_irq_and_dma(void)\n{\n\tif (atomic_inc_return(&usage_count) > 1)\n\t\treturn 0;", "\t/*\n\t * We might have scheduled a free_irq(), wait it to\n\t * drain first:\n\t */\n\tflush_workqueue(floppy_wq);", "\tif (fd_request_irq()) {\n\t\tDPRINT(\"Unable to grab IRQ%d for the floppy driver\\n\",\n\t\t FLOPPY_IRQ);\n\t\tatomic_dec(&usage_count);\n\t\treturn -1;\n\t}\n\tif (fd_request_dma()) {\n\t\tDPRINT(\"Unable to grab DMA%d for the floppy driver\\n\",\n\t\t FLOPPY_DMA);\n\t\tif (can_use_virtual_dma & 2)\n\t\t\tuse_virtual_dma = can_use_virtual_dma = 1;\n\t\tif (!(can_use_virtual_dma & 1)) {\n\t\t\tfd_free_irq();\n\t\t\tatomic_dec(&usage_count);\n\t\t\treturn -1;\n\t\t}\n\t}", "\tfor (fdc = 0; fdc < N_FDC; fdc++) {\n\t\tif (FDCS->address != -1) {\n\t\t\tif (floppy_request_regions(fdc))\n\t\t\t\tgoto cleanup;\n\t\t}\n\t}\n\tfor (fdc = 0; fdc < N_FDC; fdc++) {\n\t\tif (FDCS->address != -1) {\n\t\t\treset_fdc_info(1);\n\t\t\tfd_outb(FDCS->dor, FD_DOR);\n\t\t}\n\t}\n\tfdc = 0;\n\tset_dor(0, ~0, 8);\t/* avoid immediate interrupt */", "\tfor (fdc = 0; fdc < N_FDC; fdc++)\n\t\tif (FDCS->address != -1)\n\t\t\tfd_outb(FDCS->dor, FD_DOR);\n\t/*\n\t * The driver will try and free resources and relies on us\n\t * to know if they were allocated or not.\n\t */\n\tfdc = 0;\n\tirqdma_allocated = 1;\n\treturn 0;\ncleanup:\n\tfd_free_irq();\n\tfd_free_dma();\n\twhile (--fdc >= 0)\n\t\tfloppy_release_regions(fdc);\n\tatomic_dec(&usage_count);\n\treturn -1;\n}", "static void floppy_release_irq_and_dma(void)\n{\n\tint old_fdc;\n#ifndef __sparc__\n\tint drive;\n#endif\n\tlong tmpsize;\n\tunsigned long tmpaddr;", "\tif (!atomic_dec_and_test(&usage_count))\n\t\treturn;", "\tif (irqdma_allocated) {\n\t\tfd_disable_dma();\n\t\tfd_free_dma();\n\t\tfd_free_irq();\n\t\tirqdma_allocated = 0;\n\t}\n\tset_dor(0, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1, ~8, 0);\n#endif", "\tif (floppy_track_buffer && max_buffer_sectors) {\n\t\ttmpsize = max_buffer_sectors * 1024;\n\t\ttmpaddr = (unsigned long)floppy_track_buffer;\n\t\tfloppy_track_buffer = NULL;\n\t\tmax_buffer_sectors = 0;\n\t\tbuffer_min = buffer_max = -1;\n\t\tfd_dma_mem_free(tmpaddr, tmpsize);\n\t}\n#ifndef __sparc__\n\tfor (drive = 0; drive < N_FDC * 4; drive++)\n\t\tif (timer_pending(motor_off_timer + drive))\n\t\t\tpr_info(\"motor off timer %d still active\\n\", drive);\n#endif", "\tif (delayed_work_pending(&fd_timeout))\n\t\tpr_info(\"floppy timer still active:%s\\n\", timeout_message);\n\tif (delayed_work_pending(&fd_timer))\n\t\tpr_info(\"auxiliary floppy timer still active\\n\");\n\tif (work_pending(&floppy_work))\n\t\tpr_info(\"work still pending\\n\");\n\told_fdc = fdc;\n\tfor (fdc = 0; fdc < N_FDC; fdc++)\n\t\tif (FDCS->address != -1)\n\t\t\tfloppy_release_regions(fdc);\n\tfdc = old_fdc;\n}", "#ifdef MODULE", "static char *floppy;", "static void __init parse_floppy_cfg_string(char *cfg)\n{\n\tchar *ptr;", "\twhile (*cfg) {\n\t\tptr = cfg;\n\t\twhile (*cfg && *cfg != ' ' && *cfg != '\\t')\n\t\t\tcfg++;\n\t\tif (*cfg) {\n\t\t\t*cfg = '\\0';\n\t\t\tcfg++;\n\t\t}\n\t\tif (*ptr)\n\t\t\tfloppy_setup(ptr);\n\t}\n}", "static int __init floppy_module_init(void)\n{\n\tif (floppy)\n\t\tparse_floppy_cfg_string(floppy);\n\treturn floppy_init();\n}\nmodule_init(floppy_module_init);", "static void __exit floppy_module_exit(void)\n{\n\tint drive;", "\tblk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);\n\tunregister_blkdev(FLOPPY_MAJOR, \"fd\");\n\tplatform_driver_unregister(&floppy_driver);", "\tdestroy_workqueue(floppy_wq);", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tdel_timer_sync(&motor_off_timer[drive]);", "\t\tif (floppy_available(drive)) {\n\t\t\tdel_gendisk(disks[drive]);\n\t\t\tdevice_remove_file(&floppy_device[drive].dev, &dev_attr_cmos);\n\t\t\tplatform_device_unregister(&floppy_device[drive]);\n\t\t}\n\t\tblk_cleanup_queue(disks[drive]->queue);", "\t\t/*\n\t\t * These disks have not called add_disk(). Don't put down\n\t\t * queue reference in put_disk().\n\t\t */\n\t\tif (!(allowed_drive_mask & (1 << drive)) ||\n\t\t fdc_state[FDC(drive)].version == FDC_NONE)\n\t\t\tdisks[drive]->queue = NULL;", "\t\tput_disk(disks[drive]);\n\t}", "\tcancel_delayed_work_sync(&fd_timeout);\n\tcancel_delayed_work_sync(&fd_timer);", "\tif (atomic_read(&usage_count))\n\t\tfloppy_release_irq_and_dma();", "\t/* eject disk, if any */\n\tfd_eject(0);\n}", "module_exit(floppy_module_exit);", "module_param(floppy, charp, 0);\nmodule_param(FLOPPY_IRQ, int, 0);\nmodule_param(FLOPPY_DMA, int, 0);\nMODULE_AUTHOR(\"Alain L. Knaff\");\nMODULE_SUPPORTED_DEVICE(\"fd\");\nMODULE_LICENSE(\"GPL\");", "/* This doesn't actually get used other than for module information */\nstatic const struct pnp_device_id floppy_pnpids[] = {\n\t{\"PNP0700\", 0},\n\t{}\n};", "MODULE_DEVICE_TABLE(pnp, floppy_pnpids);", "#else", "__setup(\"floppy=\", floppy_setup);\nmodule_init(floppy_init)\n#endif", "MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [3071], "buggy_code_start_loc": [3070], "filenames": ["drivers/block/floppy.c"], "fixing_code_end_loc": [3074], "fixing_code_start_loc": [3070], "message": "The raw_cmd_copyout function in drivers/block/floppy.c in the Linux kernel through 3.14.3 does not properly restrict access to certain pointers during processing of an FDRAWCMD ioctl call, which allows local users to obtain sensitive information from kernel heap memory by leveraging write access to a /dev/fd device.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "B465C548-09E9-4CD5-A1C2-57ED09C9E3F4", "versionEndExcluding": null, "versionEndIncluding": "3.14.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux_eus:5.6:*:*:*:*:*:*:*", "matchCriteriaId": "903512FC-0017-4564-9B89-7E64FFB14B11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_eus:6.3:*:*:*:*:*:*:*", "matchCriteriaId": "8382A145-CDD9-437E-9DE7-A349956778B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "036E8A89-7A16-411F-9D31-676313BB7244", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:oracle:linux:5:-:*:*:*:*:*:*", "matchCriteriaId": "62A2AC02-A933-4E51-810E-5D040B476B7B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:oracle:linux:6:-:*:*:*:*:*:*", "matchCriteriaId": "D7B037A8-72A6-4DFF-94B2-D688A5F6F876", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:suse:linux_enterprise_desktop:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "3ED68ADD-BBDA-4485-BC76-58F011D72311", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_high_availability_extension:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "A3A907A3-2A3A-46D4-8D75-914649877B65", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_real_time_extension:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "3DB41B45-D94D-4A58-88B0-B3EC3EC350E2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_server:11:sp3:*:*:*:-:*:*", "matchCriteriaId": "E534C201-BCC5-473C-AAA7-AAB97CEB5437", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_server:11:sp3:*:*:*:vmware:*:*", "matchCriteriaId": "2470C6E8-2024-4CF5-9982-CFF50E88EAE9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The raw_cmd_copyout function in drivers/block/floppy.c in the Linux kernel through 3.14.3 does not properly restrict access to certain pointers during processing of an FDRAWCMD ioctl call, which allows local users to obtain sensitive information from kernel heap memory by leveraging write access to a /dev/fd device."}, {"lang": "es", "value": "La funci\u00f3n raw_cmd_copyout en drivers/block/floppy.c en el kernel de Linux hasta 3.14.3 no restringe debidamente acceso a ciertos punteros durante el procesamiento de una llamada FDRAWCMD ioctl, lo que permite a usuarios locales obtener informaci\u00f3n sensible de la memoria din\u00e1mica del kernel mediante el aprovechamiento de acceso a escritura hacia un dispositivo /dev/fd."}], "evaluatorComment": null, "id": "CVE-2014-1738", "lastModified": "2020-08-21T18:29:53.937", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 2.1, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-05-11T21:55:05.873", "references": [{"source": "cve-coordination@google.com", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=2145e15e0557a01b9195d1c7199a1b92cb9be81f"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-0771.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-3043.html"}, {"source": "cve-coordination@google.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-05/msg00007.html"}, {"source": "cve-coordination@google.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-05/msg00012.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-0800.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-0801.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2014/dsa-2926"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2014/dsa-2928"}, {"source": "cve-coordination@google.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/05/09/2"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/67302"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1030474"}, {"source": "cve-coordination@google.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1094299"}, {"source": "cve-coordination@google.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/2145e15e0557a01b9195d1c7199a1b92cb9be81f"}], "sourceIdentifier": "cve-coordination@google.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/2145e15e0557a01b9195d1c7199a1b92cb9be81f"}, "type": "CWE-200"}
32
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * linux/drivers/block/floppy.c\n *\n * Copyright (C) 1991, 1992 Linus Torvalds\n * Copyright (C) 1993, 1994 Alain Knaff\n * Copyright (C) 1998 Alan Cox\n */", "/*\n * 02.12.91 - Changed to static variables to indicate need for reset\n * and recalibrate. This makes some things easier (output_byte reset\n * checking etc), and means less interrupt jumping in case of errors,\n * so the code is hopefully easier to understand.\n */", "/*\n * This file is certainly a mess. I've tried my best to get it working,\n * but I don't like programming floppies, and I have only one anyway.\n * Urgel. I should check for more errors, and do more graceful error\n * recovery. Seems there are problems with several drives. I've tried to\n * correct them. No promises.\n */", "/*\n * As with hd.c, all routines within this file can (and will) be called\n * by interrupts, so extreme caution is needed. A hardware interrupt\n * handler may not sleep, or a kernel panic will happen. Thus I cannot\n * call \"floppy-on\" directly, but have to set a special timer interrupt\n * etc.\n */", "/*\n * 28.02.92 - made track-buffering routines, based on the routines written\n * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus.\n */", "/*\n * Automatic floppy-detection and formatting written by Werner Almesberger\n * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with\n * the floppy-change signal detection.\n */", "/*\n * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed\n * FDC data overrun bug, added some preliminary stuff for vertical\n * recording support.\n *\n * 1992/9/17: Added DMA allocation & DMA functions. -- hhb.\n *\n * TODO: Errors are still not counted properly.\n */", "/* 1992/9/20\n * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl)\n * modeled after the freeware MS-DOS program fdformat/88 V1.8 by\n * Christoph H. Hochst\\\"atter.\n * I have fixed the shift values to the ones I always use. Maybe a new\n * ioctl() should be created to be able to modify them.\n * There is a bug in the driver that makes it impossible to format a\n * floppy as the first thing after bootup.\n */", "/*\n * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and\n * this helped the floppy driver as well. Much cleaner, and still seems to\n * work.\n */", "/* 1994/6/24 --bbroad-- added the floppy table entries and made\n * minor modifications to allow 2.88 floppies to be run.\n */", "/* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more\n * disk types.\n */", "/*\n * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger\n * format bug fixes, but unfortunately some new bugs too...\n */", "/* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write\n * errors to allow safe writing by specialized programs.\n */", "/* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5\" disks\n * by defining bit 1 of the \"stretch\" parameter to mean put sectors on the\n * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's\n * drives are \"upside-down\").\n */", "/*\n * 1995/8/26 -- Andreas Busse -- added Mips support.\n */", "/*\n * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent\n * features to asm/floppy.h.\n */", "/*\n * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support\n */", "/*\n * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of\n * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting &\n * use of '0' for NULL.\n */", "/*\n * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation\n * failures.\n */", "/*\n * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives.\n */", "/*\n * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24\n * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were\n * being used to store jiffies, which are unsigned longs).\n */", "/*\n * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br>\n * - get rid of check_region\n * - s/suser/capable/\n */", "/*\n * 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no\n * floppy controller (lingering task on list after module is gone... boom.)\n */", "/*\n * 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range\n * (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix\n * requires many non-obvious changes in arch dependent code.\n */", "/* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>.\n * Better audit of register_blkdev.\n */", "#undef FLOPPY_SILENT_DCL_CLEAR", "#define REALLY_SLOW_IO", "#define DEBUGT 2", "#define DPRINT(format, args...) \\\n\tpr_info(\"floppy%d: \" format, current_drive, ##args)", "#define DCL_DEBUG\t\t/* debug disk change line */\n#ifdef DCL_DEBUG\n#define debug_dcl(test, fmt, args...) \\\n\tdo { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0)\n#else\n#define debug_dcl(test, fmt, args...) \\\n\tdo { if (0) DPRINT(fmt, ##args); } while (0)\n#endif", "/* do print messages for unexpected interrupts */\nstatic int print_unex = 1;\n#include <linux/module.h>\n#include <linux/sched.h>\n#include <linux/fs.h>\n#include <linux/kernel.h>\n#include <linux/timer.h>\n#include <linux/workqueue.h>\n#define FDPATCHES\n#include <linux/fdreg.h>\n#include <linux/fd.h>\n#include <linux/hdreg.h>\n#include <linux/errno.h>\n#include <linux/slab.h>\n#include <linux/mm.h>\n#include <linux/bio.h>\n#include <linux/string.h>\n#include <linux/jiffies.h>\n#include <linux/fcntl.h>\n#include <linux/delay.h>\n#include <linux/mc146818rtc.h>\t/* CMOS defines */\n#include <linux/ioport.h>\n#include <linux/interrupt.h>\n#include <linux/init.h>\n#include <linux/platform_device.h>\n#include <linux/mod_devicetable.h>\n#include <linux/mutex.h>\n#include <linux/io.h>\n#include <linux/uaccess.h>\n#include <linux/async.h>", "/*\n * PS/2 floppies have much slower step rates than regular floppies.\n * It's been recommended that take about 1/4 of the default speed\n * in some more extreme cases.\n */\nstatic DEFINE_MUTEX(floppy_mutex);\nstatic int slow_floppy;", "#include <asm/dma.h>\n#include <asm/irq.h>", "static int FLOPPY_IRQ = 6;\nstatic int FLOPPY_DMA = 2;\nstatic int can_use_virtual_dma = 2;\n/* =======\n * can use virtual DMA:\n * 0 = use of virtual DMA disallowed by config\n * 1 = use of virtual DMA prescribed by config\n * 2 = no virtual DMA preference configured. By default try hard DMA,\n * but fall back on virtual DMA when not enough memory available\n */", "static int use_virtual_dma;\n/* =======\n * use virtual DMA\n * 0 using hard DMA\n * 1 using virtual DMA\n * This variable is set to virtual when a DMA mem problem arises, and\n * reset back in floppy_grab_irq_and_dma.\n * It is not safe to reset it in other circumstances, because the floppy\n * driver may have several buffers in use at once, and we do currently not\n * record each buffers capabilities\n */", "static DEFINE_SPINLOCK(floppy_lock);", "static unsigned short virtual_dma_port = 0x3f0;\nirqreturn_t floppy_interrupt(int irq, void *dev_id);\nstatic int set_dor(int fdc, char mask, char data);", "#define K_64\t0x10000\t\t/* 64KB */", "/* the following is the mask of allowed drives. By default units 2 and\n * 3 of both floppy controllers are disabled, because switching on the\n * motor of these drives causes system hangs on some PCI computers. drive\n * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if\n * a drive is allowed.\n *\n * NOTE: This must come before we include the arch floppy header because\n * some ports reference this variable from there. -DaveM\n */", "static int allowed_drive_mask = 0x33;", "#include <asm/floppy.h>", "static int irqdma_allocated;", "#include <linux/blkdev.h>\n#include <linux/blkpg.h>\n#include <linux/cdrom.h>\t/* for the compatibility eject ioctl */\n#include <linux/completion.h>", "static struct request *current_req;\nstatic void do_fd_request(struct request_queue *q);\nstatic int set_next_request(void);", "#ifndef fd_get_dma_residue\n#define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)\n#endif", "/* Dma Memory related stuff */", "#ifndef fd_dma_mem_free\n#define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))\n#endif", "#ifndef fd_dma_mem_alloc\n#define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size))\n#endif", "static inline void fallback_on_nodma_alloc(char **addr, size_t l)\n{\n#ifdef FLOPPY_CAN_FALLBACK_ON_NODMA\n\tif (*addr)\n\t\treturn;\t\t/* we have the memory */\n\tif (can_use_virtual_dma != 2)\n\t\treturn;\t\t/* no fallback allowed */\n\tpr_info(\"DMA memory shortage. Temporarily falling back on virtual DMA\\n\");\n\t*addr = (char *)nodma_mem_alloc(l);\n#else\n\treturn;\n#endif\n}", "/* End dma memory related stuff */", "static unsigned long fake_change;\nstatic bool initialized;", "#define ITYPE(x)\t(((x) >> 2) & 0x1f)\n#define TOMINOR(x)\t((x & 3) | ((x & 4) << 5))\n#define UNIT(x)\t\t((x) & 0x03)\t\t/* drive on fdc */\n#define FDC(x)\t\t(((x) & 0x04) >> 2)\t/* fdc of drive */\n\t/* reverse mapping from unit and fdc to drive */\n#define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))", "#define DP\t(&drive_params[current_drive])\n#define DRS\t(&drive_state[current_drive])\n#define DRWE\t(&write_errors[current_drive])\n#define FDCS\t(&fdc_state[fdc])", "#define UDP\t(&drive_params[drive])\n#define UDRS\t(&drive_state[drive])\n#define UDRWE\t(&write_errors[drive])\n#define UFDCS\t(&fdc_state[FDC(drive)])", "#define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2)\n#define STRETCH(floppy)\t((floppy)->stretch & FD_STRETCH)", "/* read/write */\n#define COMMAND\t\t(raw_cmd->cmd[0])\n#define DR_SELECT\t(raw_cmd->cmd[1])\n#define TRACK\t\t(raw_cmd->cmd[2])\n#define HEAD\t\t(raw_cmd->cmd[3])\n#define SECTOR\t\t(raw_cmd->cmd[4])\n#define SIZECODE\t(raw_cmd->cmd[5])\n#define SECT_PER_TRACK\t(raw_cmd->cmd[6])\n#define GAP\t\t(raw_cmd->cmd[7])\n#define SIZECODE2\t(raw_cmd->cmd[8])\n#define NR_RW 9", "/* format */\n#define F_SIZECODE\t(raw_cmd->cmd[2])\n#define F_SECT_PER_TRACK (raw_cmd->cmd[3])\n#define F_GAP\t\t(raw_cmd->cmd[4])\n#define F_FILL\t\t(raw_cmd->cmd[5])\n#define NR_F 6", "/*\n * Maximum disk size (in kilobytes).\n * This default is used whenever the current disk size is unknown.\n * [Now it is rather a minimum]\n */\n#define MAX_DISK_SIZE 4\t\t/* 3984 */", "/*\n * globals used by 'result()'\n */\n#define MAX_REPLIES 16\nstatic unsigned char reply_buffer[MAX_REPLIES];\nstatic int inr;\t\t/* size of reply buffer, when called from interrupt */\n#define ST0\t\t(reply_buffer[0])\n#define ST1\t\t(reply_buffer[1])\n#define ST2\t\t(reply_buffer[2])\n#define ST3\t\t(reply_buffer[0])\t/* result of GETSTATUS */\n#define R_TRACK\t\t(reply_buffer[3])\n#define R_HEAD\t\t(reply_buffer[4])\n#define R_SECTOR\t(reply_buffer[5])\n#define R_SIZECODE\t(reply_buffer[6])", "#define SEL_DLY\t\t(2 * HZ / 100)", "/*\n * this struct defines the different floppy drive types.\n */\nstatic struct {\n\tstruct floppy_drive_params params;\n\tconst char *name;\t/* name printed while booting */\n} default_drive_params[] = {\n/* NOTE: the time values in jiffies should be in msec!\n CMOS drive type\n | Maximum data rate supported by drive type\n | | Head load time, msec\n | | | Head unload time, msec (not used)\n | | | | Step rate interval, usec\n | | | | | Time needed for spinup time (jiffies)\n | | | | | | Timeout for spinning down (jiffies)\n | | | | | | | Spindown offset (where disk stops)\n | | | | | | | | Select delay\n | | | | | | | | | RPS\n | | | | | | | | | | Max number of tracks\n | | | | | | | | | | | Interrupt timeout\n | | | | | | | | | | | | Max nonintlv. sectors\n | | | | | | | | | | | | | -Max Errors- flags */\n{{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0,\n 0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, \"unknown\" },", "{{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0,\n 0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, \"360K PC\" }, /*5 1/4 360 KB PC*/", "{{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0,\n 0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, \"1.2M\" }, /*5 1/4 HD AT*/", "{{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,\n 0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, \"720k\" }, /*3 1/2 DD*/", "{{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,\n 0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, \"1.44M\" }, /*3 1/2 HD*/", "{{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,\n 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, \"2.88M AMI BIOS\" }, /*3 1/2 ED*/", "{{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,\n 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, \"2.88M\" } /*3 1/2 ED*/\n/* | --autodetected formats--- | | |\n * read_track | | Name printed when booting\n *\t\t\t\t | Native format\n *\t Frequency of disk change checks */\n};", "static struct floppy_drive_params drive_params[N_DRIVE];\nstatic struct floppy_drive_struct drive_state[N_DRIVE];\nstatic struct floppy_write_errors write_errors[N_DRIVE];\nstatic struct timer_list motor_off_timer[N_DRIVE];\nstatic struct gendisk *disks[N_DRIVE];\nstatic struct block_device *opened_bdev[N_DRIVE];\nstatic DEFINE_MUTEX(open_lock);\nstatic struct floppy_raw_cmd *raw_cmd, default_raw_cmd;\nstatic int fdc_queue;", "/*\n * This struct defines the different floppy types.\n *\n * Bit 0 of 'stretch' tells if the tracks need to be doubled for some\n * types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch'\n * tells if the disk is in Commodore 1581 format, which means side 0 sectors\n * are located on side 1 of the disk but with a side 0 ID, and vice-versa.\n * This is the same as the Sharp MZ-80 5.25\" CP/M disk format, except that the\n * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical\n * side 0 is on physical side 0 (but with the misnamed sector IDs).\n * 'stretch' should probably be renamed to something more general, like\n * 'options'.\n *\n * Bits 2 through 9 of 'stretch' tell the number of the first sector.\n * The LSB (bit 2) is flipped. For most disks, the first sector\n * is 1 (represented by 0x00<<2). For some CP/M and music sampler\n * disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2).\n * For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2).\n *\n * Other parameters should be self-explanatory (see also setfdprm(8)).\n */\n/*\n\t Size\n\t | Sectors per track\n\t | | Head\n\t | | | Tracks\n\t | | | | Stretch\n\t | | | | | Gap 1 size\n\t | | | | | | Data rate, | 0x40 for perp\n\t | | | | | | | Spec1 (stepping rate, head unload\n\t | | | | | | | | /fmt gap (gap2) */\nstatic struct floppy_struct floppy_type[32] = {\n\t{ 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL },\t/* 0 no testing */\n\t{ 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,\"d360\" }, /* 1 360KB PC */\n\t{ 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,\"h1200\" },\t/* 2 1.2MB AT */\n\t{ 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,\"D360\" },\t/* 3 360KB SS 3.5\" */\n\t{ 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,\"D720\" },\t/* 4 720KB 3.5\" */\n\t{ 720, 9,2,40,1,0x23,0x01,0xDF,0x50,\"h360\" },\t/* 5 360KB AT */\n\t{ 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,\"h720\" },\t/* 6 720KB AT */\n\t{ 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,\"H1440\" },\t/* 7 1.44MB 3.5\" */\n\t{ 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,\"E2880\" },\t/* 8 2.88MB 3.5\" */\n\t{ 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,\"E3120\" },\t/* 9 3.12MB 3.5\" */", "\t{ 2880,18,2,80,0,0x25,0x00,0xDF,0x02,\"h1440\" }, /* 10 1.44MB 5.25\" */\n\t{ 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,\"H1680\" }, /* 11 1.68MB 3.5\" */\n\t{ 820,10,2,41,1,0x25,0x01,0xDF,0x2E,\"h410\" },\t/* 12 410KB 5.25\" */\n\t{ 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,\"H820\" },\t/* 13 820KB 3.5\" */\n\t{ 2952,18,2,82,0,0x25,0x00,0xDF,0x02,\"h1476\" },\t/* 14 1.48MB 5.25\" */\n\t{ 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,\"H1722\" },\t/* 15 1.72MB 3.5\" */\n\t{ 840,10,2,42,1,0x25,0x01,0xDF,0x2E,\"h420\" },\t/* 16 420KB 5.25\" */\n\t{ 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,\"H830\" },\t/* 17 830KB 3.5\" */\n\t{ 2988,18,2,83,0,0x25,0x00,0xDF,0x02,\"h1494\" },\t/* 18 1.49MB 5.25\" */\n\t{ 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,\"H1743\" }, /* 19 1.74 MB 3.5\" */", "\t{ 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,\"h880\" }, /* 20 880KB 5.25\" */\n\t{ 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,\"D1040\" }, /* 21 1.04MB 3.5\" */\n\t{ 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,\"D1120\" }, /* 22 1.12MB 3.5\" */\n\t{ 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,\"h1600\" }, /* 23 1.6MB 5.25\" */\n\t{ 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,\"H1760\" }, /* 24 1.76MB 3.5\" */\n\t{ 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,\"H1920\" }, /* 25 1.92MB 3.5\" */\n\t{ 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,\"E3200\" }, /* 26 3.20MB 3.5\" */\n\t{ 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,\"E3520\" }, /* 27 3.52MB 3.5\" */\n\t{ 7680,48,2,80,0,0x25,0x63,0xCF,0x00,\"E3840\" }, /* 28 3.84MB 3.5\" */\n\t{ 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,\"H1840\" }, /* 29 1.84MB 3.5\" */", "\t{ 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,\"D800\" },\t/* 30 800KB 3.5\" */\n\t{ 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,\"H1600\" }, /* 31 1.6MB 3.5\" */\n};", "#define SECTSIZE (_FD_SECTSIZE(*floppy))", "/* Auto-detection: Disk type used until the next media change occurs. */\nstatic struct floppy_struct *current_type[N_DRIVE];", "/*\n * User-provided type information. current_type points to\n * the respective entry of this array.\n */\nstatic struct floppy_struct user_params[N_DRIVE];", "static sector_t floppy_sizes[256];", "static char floppy_device_name[] = \"floppy\";", "/*\n * The driver is trying to determine the correct media format\n * while probing is set. rw_interrupt() clears it after a\n * successful access.\n */\nstatic int probing;", "/* Synchronization of FDC access. */\n#define FD_COMMAND_NONE\t\t-1\n#define FD_COMMAND_ERROR\t2\n#define FD_COMMAND_OKAY\t\t3", "static volatile int command_status = FD_COMMAND_NONE;\nstatic unsigned long fdc_busy;\nstatic DECLARE_WAIT_QUEUE_HEAD(fdc_wait);\nstatic DECLARE_WAIT_QUEUE_HEAD(command_done);", "/* Errors during formatting are counted here. */\nstatic int format_errors;", "/* Format request descriptor. */\nstatic struct format_descr format_req;", "/*\n * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps\n * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),\n * H is head unload time (1=16ms, 2=32ms, etc)\n */", "/*\n * Track buffer\n * Because these are written to by the DMA controller, they must\n * not contain a 64k byte boundary crossing, or data will be\n * corrupted/lost.\n */\nstatic char *floppy_track_buffer;\nstatic int max_buffer_sectors;", "static int *errors;\ntypedef void (*done_f)(int);\nstatic const struct cont_t {\n\tvoid (*interrupt)(void);\n\t\t\t\t/* this is called after the interrupt of the\n\t\t\t\t * main command */\n\tvoid (*redo)(void);\t/* this is called to retry the operation */\n\tvoid (*error)(void);\t/* this is called to tally an error */\n\tdone_f done;\t\t/* this is called to say if the operation has\n\t\t\t\t * succeeded/failed */\n} *cont;", "static void floppy_ready(void);\nstatic void floppy_start(void);\nstatic void process_fd_request(void);\nstatic void recalibrate_floppy(void);\nstatic void floppy_shutdown(struct work_struct *);", "static int floppy_request_regions(int);\nstatic void floppy_release_regions(int);\nstatic int floppy_grab_irq_and_dma(void);\nstatic void floppy_release_irq_and_dma(void);", "/*\n * The \"reset\" variable should be tested whenever an interrupt is scheduled,\n * after the commands have been sent. This is to ensure that the driver doesn't\n * get wedged when the interrupt doesn't come because of a failed command.\n * reset doesn't need to be tested before sending commands, because\n * output_byte is automatically disabled when reset is set.\n */\nstatic void reset_fdc(void);", "/*\n * These are global variables, as that's the easiest way to give\n * information to interrupts. They are the data used for the current\n * request.\n */\n#define NO_TRACK\t-1\n#define NEED_1_RECAL\t-2\n#define NEED_2_RECAL\t-3", "static atomic_t usage_count = ATOMIC_INIT(0);", "/* buffer related variables */\nstatic int buffer_track = -1;\nstatic int buffer_drive = -1;\nstatic int buffer_min = -1;\nstatic int buffer_max = -1;", "/* fdc related variables, should end up in a struct */\nstatic struct floppy_fdc_state fdc_state[N_FDC];\nstatic int fdc;\t\t\t/* current fdc */", "static struct workqueue_struct *floppy_wq;", "static struct floppy_struct *_floppy = floppy_type;\nstatic unsigned char current_drive;\nstatic long current_count_sectors;\nstatic unsigned char fsector_t;\t/* sector in track */\nstatic unsigned char in_sector_offset;\t/* offset within physical sector,\n\t\t\t\t\t * expressed in units of 512 bytes */", "static inline bool drive_no_geom(int drive)\n{\n\treturn !current_type[drive] && !ITYPE(UDRS->fd_device);\n}", "#ifndef fd_eject\nstatic inline int fd_eject(int drive)\n{\n\treturn -EINVAL;\n}\n#endif", "/*\n * Debugging\n * =========\n */\n#ifdef DEBUGT\nstatic long unsigned debugtimer;", "static inline void set_debugt(void)\n{\n\tdebugtimer = jiffies;\n}", "static inline void debugt(const char *func, const char *msg)\n{\n\tif (DP->flags & DEBUGT)\n\t\tpr_info(\"%s:%s dtime=%lu\\n\", func, msg, jiffies - debugtimer);\n}\n#else\nstatic inline void set_debugt(void) { }\nstatic inline void debugt(const char *func, const char *msg) { }\n#endif /* DEBUGT */", "\nstatic DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown);\nstatic const char *timeout_message;", "static void is_alive(const char *func, const char *message)\n{\n\t/* this routine checks whether the floppy driver is \"alive\" */\n\tif (test_bit(0, &fdc_busy) && command_status < 2 &&\n\t !delayed_work_pending(&fd_timeout)) {\n\t\tDPRINT(\"%s: timeout handler died. %s\\n\", func, message);\n\t}\n}", "static void (*do_floppy)(void) = NULL;", "#define OLOGSIZE 20", "static void (*lasthandler)(void);\nstatic unsigned long interruptjiffies;\nstatic unsigned long resultjiffies;\nstatic int resultsize;\nstatic unsigned long lastredo;", "static struct output_log {\n\tunsigned char data;\n\tunsigned char status;\n\tunsigned long jiffies;\n} output_log[OLOGSIZE];", "static int output_log_pos;", "#define current_reqD -1\n#define MAXTIMEOUT -2", "static void __reschedule_timeout(int drive, const char *message)\n{\n\tunsigned long delay;", "\tif (drive == current_reqD)\n\t\tdrive = current_drive;", "\tif (drive < 0 || drive >= N_DRIVE) {\n\t\tdelay = 20UL * HZ;\n\t\tdrive = 0;\n\t} else\n\t\tdelay = UDP->timeout;", "\tmod_delayed_work(floppy_wq, &fd_timeout, delay);\n\tif (UDP->flags & FD_DEBUG)\n\t\tDPRINT(\"reschedule timeout %s\\n\", message);\n\ttimeout_message = message;\n}", "static void reschedule_timeout(int drive, const char *message)\n{\n\tunsigned long flags;", "\tspin_lock_irqsave(&floppy_lock, flags);\n\t__reschedule_timeout(drive, message);\n\tspin_unlock_irqrestore(&floppy_lock, flags);\n}", "#define INFBOUND(a, b) (a) = max_t(int, a, b)\n#define SUPBOUND(a, b) (a) = min_t(int, a, b)", "/*\n * Bottom half floppy driver.\n * ==========================\n *\n * This part of the file contains the code talking directly to the hardware,\n * and also the main service loop (seek-configure-spinup-command)\n */", "/*\n * disk change.\n * This routine is responsible for maintaining the FD_DISK_CHANGE flag,\n * and the last_checked date.\n *\n * last_checked is the date of the last check which showed 'no disk change'\n * FD_DISK_CHANGE is set under two conditions:\n * 1. The floppy has been changed after some i/o to that floppy already\n * took place.\n * 2. No floppy disk is in the drive. This is done in order to ensure that\n * requests are quickly flushed in case there is no disk in the drive. It\n * follows that FD_DISK_CHANGE can only be cleared if there is a disk in\n * the drive.\n *\n * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.\n * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on\n * each seek. If a disk is present, the disk change line should also be\n * cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk\n * change line is set, this means either that no disk is in the drive, or\n * that it has been removed since the last seek.\n *\n * This means that we really have a third possibility too:\n * The floppy has been changed after the last seek.\n */", "static int disk_change(int drive)\n{\n\tint fdc = FDC(drive);", "\tif (time_before(jiffies, UDRS->select_date + UDP->select_delay))\n\t\tDPRINT(\"WARNING disk change called early\\n\");\n\tif (!(FDCS->dor & (0x10 << UNIT(drive))) ||\n\t (FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) {\n\t\tDPRINT(\"probing disk change on unselected drive\\n\");\n\t\tDPRINT(\"drive=%d fdc=%d dor=%x\\n\", drive, FDC(drive),\n\t\t (unsigned int)FDCS->dor);\n\t}", "\tdebug_dcl(UDP->flags,\n\t\t \"checking disk change line for drive %d\\n\", drive);\n\tdebug_dcl(UDP->flags, \"jiffies=%lu\\n\", jiffies);\n\tdebug_dcl(UDP->flags, \"disk change line=%x\\n\", fd_inb(FD_DIR) & 0x80);\n\tdebug_dcl(UDP->flags, \"flags=%lx\\n\", UDRS->flags);", "\tif (UDP->flags & FD_BROKEN_DCL)\n\t\treturn test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\tif ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) {\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t\t\t\t\t/* verify write protection */", "\t\tif (UDRS->maxblock)\t/* mark it changed */\n\t\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);", "\t\t/* invalidate its geometry */\n\t\tif (UDRS->keep_data >= 0) {\n\t\t\tif ((UDP->flags & FTD_MSG) &&\n\t\t\t current_type[drive] != NULL)\n\t\t\t\tDPRINT(\"Disk type is undefined after disk change\\n\");\n\t\t\tcurrent_type[drive] = NULL;\n\t\t\tfloppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1;\n\t\t}", "\t\treturn 1;\n\t} else {\n\t\tUDRS->last_checked = jiffies;\n\t\tclear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);\n\t}\n\treturn 0;\n}", "static inline int is_selected(int dor, int unit)\n{\n\treturn ((dor & (0x10 << unit)) && (dor & 3) == unit);\n}", "static bool is_ready_state(int status)\n{\n\tint state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA);\n\treturn state == STATUS_READY;\n}", "static int set_dor(int fdc, char mask, char data)\n{\n\tunsigned char unit;\n\tunsigned char drive;\n\tunsigned char newdor;\n\tunsigned char olddor;", "\tif (FDCS->address == -1)\n\t\treturn -1;", "\tolddor = FDCS->dor;\n\tnewdor = (olddor & mask) | data;\n\tif (newdor != olddor) {\n\t\tunit = olddor & 0x3;\n\t\tif (is_selected(olddor, unit) && !is_selected(newdor, unit)) {\n\t\t\tdrive = REVDRIVE(fdc, unit);\n\t\t\tdebug_dcl(UDP->flags,\n\t\t\t\t \"calling disk change from set_dor\\n\");\n\t\t\tdisk_change(drive);\n\t\t}\n\t\tFDCS->dor = newdor;\n\t\tfd_outb(newdor, FD_DOR);", "\t\tunit = newdor & 0x3;\n\t\tif (!is_selected(olddor, unit) && is_selected(newdor, unit)) {\n\t\t\tdrive = REVDRIVE(fdc, unit);\n\t\t\tUDRS->select_date = jiffies;\n\t\t}\n\t}\n\treturn olddor;\n}", "static void twaddle(void)\n{\n\tif (DP->select_delay)\n\t\treturn;\n\tfd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR);\n\tfd_outb(FDCS->dor, FD_DOR);\n\tDRS->select_date = jiffies;\n}", "/*\n * Reset all driver information about the current fdc.\n * This is needed after a reset, and after a raw command.\n */\nstatic void reset_fdc_info(int mode)\n{\n\tint drive;", "\tFDCS->spec1 = FDCS->spec2 = -1;\n\tFDCS->need_configure = 1;\n\tFDCS->perp_mode = 1;\n\tFDCS->rawcmd = 0;\n\tfor (drive = 0; drive < N_DRIVE; drive++)\n\t\tif (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL))\n\t\t\tUDRS->track = NEED_2_RECAL;\n}", "/* selects the fdc and drive, and enables the fdc's input/dma. */\nstatic void set_fdc(int drive)\n{\n\tif (drive >= 0 && drive < N_DRIVE) {\n\t\tfdc = FDC(drive);\n\t\tcurrent_drive = drive;\n\t}\n\tif (fdc != 1 && fdc != 0) {\n\t\tpr_info(\"bad fdc value\\n\");\n\t\treturn;\n\t}\n\tset_dor(fdc, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1 - fdc, ~8, 0);\n#endif\n\tif (FDCS->rawcmd == 2)\n\t\treset_fdc_info(1);\n\tif (fd_inb(FD_STATUS) != STATUS_READY)\n\t\tFDCS->reset = 1;\n}", "/* locks the driver */\nstatic int lock_fdc(int drive, bool interruptible)\n{\n\tif (WARN(atomic_read(&usage_count) == 0,\n\t\t \"Trying to lock fdc while usage count=0\\n\"))\n\t\treturn -1;", "\tif (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy)))\n\t\treturn -EINTR;", "\tcommand_status = FD_COMMAND_NONE;", "\treschedule_timeout(drive, \"lock fdc\");\n\tset_fdc(drive);\n\treturn 0;\n}", "/* unlocks the driver */\nstatic void unlock_fdc(void)\n{\n\tif (!test_bit(0, &fdc_busy))\n\t\tDPRINT(\"FDC access conflict!\\n\");", "\traw_cmd = NULL;\n\tcommand_status = FD_COMMAND_NONE;\n\tcancel_delayed_work(&fd_timeout);\n\tdo_floppy = NULL;\n\tcont = NULL;\n\tclear_bit(0, &fdc_busy);\n\twake_up(&fdc_wait);\n}", "/* switches the motor off after a given timeout */\nstatic void motor_off_callback(unsigned long nr)\n{\n\tunsigned char mask = ~(0x10 << UNIT(nr));", "\tset_dor(FDC(nr), mask, 0);\n}", "/* schedules motor off */\nstatic void floppy_off(unsigned int drive)\n{\n\tunsigned long volatile delta;\n\tint fdc = FDC(drive);", "\tif (!(FDCS->dor & (0x10 << UNIT(drive))))\n\t\treturn;", "\tdel_timer(motor_off_timer + drive);", "\t/* make spindle stop in a position which minimizes spinup time\n\t * next time */\n\tif (UDP->rps) {\n\t\tdelta = jiffies - UDRS->first_read_date + HZ -\n\t\t UDP->spindown_offset;\n\t\tdelta = ((delta * UDP->rps) % HZ) / UDP->rps;\n\t\tmotor_off_timer[drive].expires =\n\t\t jiffies + UDP->spindown - delta;\n\t}\n\tadd_timer(motor_off_timer + drive);\n}", "/*\n * cycle through all N_DRIVE floppy drives, for disk change testing.\n * stopping at current drive. This is done before any long operation, to\n * be sure to have up to date disk change information.\n */\nstatic void scandrives(void)\n{\n\tint i;\n\tint drive;\n\tint saved_drive;", "\tif (DP->select_delay)\n\t\treturn;", "\tsaved_drive = current_drive;\n\tfor (i = 0; i < N_DRIVE; i++) {\n\t\tdrive = (saved_drive + i + 1) % N_DRIVE;\n\t\tif (UDRS->fd_ref == 0 || UDP->select_delay != 0)\n\t\t\tcontinue;\t/* skip closed drives */\n\t\tset_fdc(drive);\n\t\tif (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) &\n\t\t (0x10 << UNIT(drive))))\n\t\t\t/* switch the motor off again, if it was off to\n\t\t\t * begin with */\n\t\t\tset_dor(fdc, ~(0x10 << UNIT(drive)), 0);\n\t}\n\tset_fdc(saved_drive);\n}", "static void empty(void)\n{\n}", "static void (*floppy_work_fn)(void);", "static void floppy_work_workfn(struct work_struct *work)\n{\n\tfloppy_work_fn();\n}", "static DECLARE_WORK(floppy_work, floppy_work_workfn);", "static void schedule_bh(void (*handler)(void))\n{\n\tWARN_ON(work_pending(&floppy_work));", "\tfloppy_work_fn = handler;\n\tqueue_work(floppy_wq, &floppy_work);\n}", "static void (*fd_timer_fn)(void) = NULL;", "static void fd_timer_workfn(struct work_struct *work)\n{\n\tfd_timer_fn();\n}", "static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn);", "static void cancel_activity(void)\n{\n\tdo_floppy = NULL;\n\tcancel_delayed_work_sync(&fd_timer);\n\tcancel_work_sync(&floppy_work);\n}", "/* this function makes sure that the disk stays in the drive during the\n * transfer */\nstatic void fd_watchdog(void)\n{\n\tdebug_dcl(DP->flags, \"calling disk change from watchdog\\n\");", "\tif (disk_change(current_drive)) {\n\t\tDPRINT(\"disk removed during i/o\\n\");\n\t\tcancel_activity();\n\t\tcont->done(0);\n\t\treset_fdc();\n\t} else {\n\t\tcancel_delayed_work(&fd_timer);\n\t\tfd_timer_fn = fd_watchdog;\n\t\tqueue_delayed_work(floppy_wq, &fd_timer, HZ / 10);\n\t}\n}", "static void main_command_interrupt(void)\n{\n\tcancel_delayed_work(&fd_timer);\n\tcont->interrupt();\n}", "/* waits for a delay (spinup or select) to pass */\nstatic int fd_wait_for_completion(unsigned long expires,\n\t\t\t\t void (*function)(void))\n{\n\tif (FDCS->reset) {\n\t\treset_fdc();\t/* do the reset during sleep to win time\n\t\t\t\t * if we don't need to sleep, it's a good\n\t\t\t\t * occasion anyways */\n\t\treturn 1;\n\t}", "\tif (time_before(jiffies, expires)) {\n\t\tcancel_delayed_work(&fd_timer);\n\t\tfd_timer_fn = function;\n\t\tqueue_delayed_work(floppy_wq, &fd_timer, expires - jiffies);\n\t\treturn 1;\n\t}\n\treturn 0;\n}", "static void setup_DMA(void)\n{\n\tunsigned long f;", "\tif (raw_cmd->length == 0) {\n\t\tint i;", "\t\tpr_info(\"zero dma transfer size:\");\n\t\tfor (i = 0; i < raw_cmd->cmd_count; i++)\n\t\t\tpr_cont(\"%x,\", raw_cmd->cmd[i]);\n\t\tpr_cont(\"\\n\");\n\t\tcont->done(0);\n\t\tFDCS->reset = 1;\n\t\treturn;\n\t}\n\tif (((unsigned long)raw_cmd->kernel_data) % 512) {\n\t\tpr_info(\"non aligned address: %p\\n\", raw_cmd->kernel_data);\n\t\tcont->done(0);\n\t\tFDCS->reset = 1;\n\t\treturn;\n\t}\n\tf = claim_dma_lock();\n\tfd_disable_dma();\n#ifdef fd_dma_setup\n\tif (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length,\n\t\t\t (raw_cmd->flags & FD_RAW_READ) ?\n\t\t\t DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) {\n\t\trelease_dma_lock(f);\n\t\tcont->done(0);\n\t\tFDCS->reset = 1;\n\t\treturn;\n\t}\n\trelease_dma_lock(f);\n#else\n\tfd_clear_dma_ff();\n\tfd_cacheflush(raw_cmd->kernel_data, raw_cmd->length);\n\tfd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ?\n\t\t\tDMA_MODE_READ : DMA_MODE_WRITE);\n\tfd_set_dma_addr(raw_cmd->kernel_data);\n\tfd_set_dma_count(raw_cmd->length);\n\tvirtual_dma_port = FDCS->address;\n\tfd_enable_dma();\n\trelease_dma_lock(f);\n#endif\n}", "static void show_floppy(void);", "/* waits until the fdc becomes ready */\nstatic int wait_til_ready(void)\n{\n\tint status;\n\tint counter;", "\tif (FDCS->reset)\n\t\treturn -1;\n\tfor (counter = 0; counter < 10000; counter++) {\n\t\tstatus = fd_inb(FD_STATUS);\n\t\tif (status & STATUS_READY)\n\t\t\treturn status;\n\t}\n\tif (initialized) {\n\t\tDPRINT(\"Getstatus times out (%x) on fdc %d\\n\", status, fdc);\n\t\tshow_floppy();\n\t}\n\tFDCS->reset = 1;\n\treturn -1;\n}", "/* sends a command byte to the fdc */\nstatic int output_byte(char byte)\n{\n\tint status = wait_til_ready();", "\tif (status < 0)\n\t\treturn -1;", "\tif (is_ready_state(status)) {\n\t\tfd_outb(byte, FD_DATA);\n\t\toutput_log[output_log_pos].data = byte;\n\t\toutput_log[output_log_pos].status = status;\n\t\toutput_log[output_log_pos].jiffies = jiffies;\n\t\toutput_log_pos = (output_log_pos + 1) % OLOGSIZE;\n\t\treturn 0;\n\t}\n\tFDCS->reset = 1;\n\tif (initialized) {\n\t\tDPRINT(\"Unable to send byte %x to FDC. Fdc=%x Status=%x\\n\",\n\t\t byte, fdc, status);\n\t\tshow_floppy();\n\t}\n\treturn -1;\n}", "/* gets the response from the fdc */\nstatic int result(void)\n{\n\tint i;\n\tint status = 0;", "\tfor (i = 0; i < MAX_REPLIES; i++) {\n\t\tstatus = wait_til_ready();\n\t\tif (status < 0)\n\t\t\tbreak;\n\t\tstatus &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA;\n\t\tif ((status & ~STATUS_BUSY) == STATUS_READY) {\n\t\t\tresultjiffies = jiffies;\n\t\t\tresultsize = i;\n\t\t\treturn i;\n\t\t}\n\t\tif (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY))\n\t\t\treply_buffer[i] = fd_inb(FD_DATA);\n\t\telse\n\t\t\tbreak;\n\t}\n\tif (initialized) {\n\t\tDPRINT(\"get result error. Fdc=%d Last status=%x Read bytes=%d\\n\",\n\t\t fdc, status, i);\n\t\tshow_floppy();\n\t}\n\tFDCS->reset = 1;\n\treturn -1;\n}", "#define MORE_OUTPUT -2\n/* does the fdc need more output? */\nstatic int need_more_output(void)\n{\n\tint status = wait_til_ready();", "\tif (status < 0)\n\t\treturn -1;", "\tif (is_ready_state(status))\n\t\treturn MORE_OUTPUT;", "\treturn result();\n}", "/* Set perpendicular mode as required, based on data rate, if supported.\n * 82077 Now tested. 1Mbps data rate only possible with 82077-1.\n */\nstatic void perpendicular_mode(void)\n{\n\tunsigned char perp_mode;", "\tif (raw_cmd->rate & 0x40) {\n\t\tswitch (raw_cmd->rate & 3) {\n\t\tcase 0:\n\t\t\tperp_mode = 2;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tperp_mode = 3;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDPRINT(\"Invalid data rate for perpendicular mode!\\n\");\n\t\t\tcont->done(0);\n\t\t\tFDCS->reset = 1;\n\t\t\t\t\t/*\n\t\t\t\t\t * convenient way to return to\n\t\t\t\t\t * redo without too much hassle\n\t\t\t\t\t * (deep stack et al.)\n\t\t\t\t\t */\n\t\t\treturn;\n\t\t}\n\t} else\n\t\tperp_mode = 0;", "\tif (FDCS->perp_mode == perp_mode)\n\t\treturn;\n\tif (FDCS->version >= FDC_82077_ORIG) {\n\t\toutput_byte(FD_PERPENDICULAR);\n\t\toutput_byte(perp_mode);\n\t\tFDCS->perp_mode = perp_mode;\n\t} else if (perp_mode) {\n\t\tDPRINT(\"perpendicular mode not supported by this FDC.\\n\");\n\t}\n}\t\t\t\t/* perpendicular_mode */", "static int fifo_depth = 0xa;\nstatic int no_fifo;", "static int fdc_configure(void)\n{\n\t/* Turn on FIFO */\n\toutput_byte(FD_CONFIGURE);\n\tif (need_more_output() != MORE_OUTPUT)\n\t\treturn 0;\n\toutput_byte(0);\n\toutput_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf));\n\toutput_byte(0);\t\t/* pre-compensation from track\n\t\t\t\t 0 upwards */\n\treturn 1;\n}", "#define NOMINAL_DTR 500", "/* Issue a \"SPECIFY\" command to set the step rate time, head unload time,\n * head load time, and DMA disable flag to values needed by floppy.\n *\n * The value \"dtr\" is the data transfer rate in Kbps. It is needed\n * to account for the data rate-based scaling done by the 82072 and 82077\n * FDC types. This parameter is ignored for other types of FDCs (i.e.\n * 8272a).\n *\n * Note that changing the data transfer rate has a (probably deleterious)\n * effect on the parameters subject to scaling for 82072/82077 FDCs, so\n * fdc_specify is called again after each data transfer rate\n * change.\n *\n * srt: 1000 to 16000 in microseconds\n * hut: 16 to 240 milliseconds\n * hlt: 2 to 254 milliseconds\n *\n * These values are rounded up to the next highest available delay time.\n */\nstatic void fdc_specify(void)\n{\n\tunsigned char spec1;\n\tunsigned char spec2;\n\tunsigned long srt;\n\tunsigned long hlt;\n\tunsigned long hut;\n\tunsigned long dtr = NOMINAL_DTR;\n\tunsigned long scale_dtr = NOMINAL_DTR;\n\tint hlt_max_code = 0x7f;\n\tint hut_max_code = 0xf;", "\tif (FDCS->need_configure && FDCS->version >= FDC_82072A) {\n\t\tfdc_configure();\n\t\tFDCS->need_configure = 0;\n\t}", "\tswitch (raw_cmd->rate & 0x03) {\n\tcase 3:\n\t\tdtr = 1000;\n\t\tbreak;\n\tcase 1:\n\t\tdtr = 300;\n\t\tif (FDCS->version >= FDC_82078) {\n\t\t\t/* chose the default rate table, not the one\n\t\t\t * where 1 = 2 Mbps */\n\t\t\toutput_byte(FD_DRIVESPEC);\n\t\t\tif (need_more_output() == MORE_OUTPUT) {\n\t\t\t\toutput_byte(UNIT(current_drive));\n\t\t\t\toutput_byte(0xc0);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\tcase 2:\n\t\tdtr = 250;\n\t\tbreak;\n\t}", "\tif (FDCS->version >= FDC_82072) {\n\t\tscale_dtr = dtr;\n\t\thlt_max_code = 0x00;\t/* 0==256msec*dtr0/dtr (not linear!) */\n\t\thut_max_code = 0x0;\t/* 0==256msec*dtr0/dtr (not linear!) */\n\t}", "\t/* Convert step rate from microseconds to milliseconds and 4 bits */\n\tsrt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR);\n\tif (slow_floppy)\n\t\tsrt = srt / 4;", "\tSUPBOUND(srt, 0xf);\n\tINFBOUND(srt, 0);", "\thlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR);\n\tif (hlt < 0x01)\n\t\thlt = 0x01;\n\telse if (hlt > 0x7f)\n\t\thlt = hlt_max_code;", "\thut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR);\n\tif (hut < 0x1)\n\t\thut = 0x1;\n\telse if (hut > 0xf)\n\t\thut = hut_max_code;", "\tspec1 = (srt << 4) | hut;\n\tspec2 = (hlt << 1) | (use_virtual_dma & 1);", "\t/* If these parameters did not change, just return with success */\n\tif (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) {\n\t\t/* Go ahead and set spec1 and spec2 */\n\t\toutput_byte(FD_SPECIFY);\n\t\toutput_byte(FDCS->spec1 = spec1);\n\t\toutput_byte(FDCS->spec2 = spec2);\n\t}\n}\t\t\t\t/* fdc_specify */", "/* Set the FDC's data transfer rate on behalf of the specified drive.\n * NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue\n * of the specify command (i.e. using the fdc_specify function).\n */\nstatic int fdc_dtr(void)\n{\n\t/* If data rate not already set to desired value, set it. */\n\tif ((raw_cmd->rate & 3) == FDCS->dtr)\n\t\treturn 0;", "\t/* Set dtr */\n\tfd_outb(raw_cmd->rate & 3, FD_DCR);", "\t/* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB)\n\t * need a stabilization period of several milliseconds to be\n\t * enforced after data rate changes before R/W operations.\n\t * Pause 5 msec to avoid trouble. (Needs to be 2 jiffies)\n\t */\n\tFDCS->dtr = raw_cmd->rate & 3;\n\treturn fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready);\n}\t\t\t\t/* fdc_dtr */", "static void tell_sector(void)\n{\n\tpr_cont(\": track %d, head %d, sector %d, size %d\",\n\t\tR_TRACK, R_HEAD, R_SECTOR, R_SIZECODE);\n}\t\t\t\t/* tell_sector */", "static void print_errors(void)\n{\n\tDPRINT(\"\");\n\tif (ST0 & ST0_ECE) {\n\t\tpr_cont(\"Recalibrate failed!\");\n\t} else if (ST2 & ST2_CRC) {\n\t\tpr_cont(\"data CRC error\");\n\t\ttell_sector();\n\t} else if (ST1 & ST1_CRC) {\n\t\tpr_cont(\"CRC error\");\n\t\ttell_sector();\n\t} else if ((ST1 & (ST1_MAM | ST1_ND)) ||\n\t\t (ST2 & ST2_MAM)) {\n\t\tif (!probing) {\n\t\t\tpr_cont(\"sector not found\");\n\t\t\ttell_sector();\n\t\t} else\n\t\t\tpr_cont(\"probe failed...\");\n\t} else if (ST2 & ST2_WC) {\t/* seek error */\n\t\tpr_cont(\"wrong cylinder\");\n\t} else if (ST2 & ST2_BC) {\t/* cylinder marked as bad */\n\t\tpr_cont(\"bad cylinder\");\n\t} else {\n\t\tpr_cont(\"unknown error. ST[0..2] are: 0x%x 0x%x 0x%x\",\n\t\t\tST0, ST1, ST2);\n\t\ttell_sector();\n\t}\n\tpr_cont(\"\\n\");\n}", "/*\n * OK, this error interpreting routine is called after a\n * DMA read/write has succeeded\n * or failed, so we check the results, and copy any buffers.\n * hhb: Added better error reporting.\n * ak: Made this into a separate routine.\n */\nstatic int interpret_errors(void)\n{\n\tchar bad;", "\tif (inr != 7) {\n\t\tDPRINT(\"-- FDC reply error\\n\");\n\t\tFDCS->reset = 1;\n\t\treturn 1;\n\t}", "\t/* check IC to find cause of interrupt */\n\tswitch (ST0 & ST0_INTR) {\n\tcase 0x40:\t\t/* error occurred during command execution */\n\t\tif (ST1 & ST1_EOC)\n\t\t\treturn 0;\t/* occurs with pseudo-DMA */\n\t\tbad = 1;\n\t\tif (ST1 & ST1_WP) {\n\t\t\tDPRINT(\"Drive is write protected\\n\");\n\t\t\tclear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);\n\t\t\tcont->done(0);\n\t\t\tbad = 2;\n\t\t} else if (ST1 & ST1_ND) {\n\t\t\tset_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);\n\t\t} else if (ST1 & ST1_OR) {\n\t\t\tif (DP->flags & FTD_MSG)\n\t\t\t\tDPRINT(\"Over/Underrun - retrying\\n\");\n\t\t\tbad = 0;\n\t\t} else if (*errors >= DP->max_errors.reporting) {\n\t\t\tprint_errors();\n\t\t}\n\t\tif (ST2 & ST2_WC || ST2 & ST2_BC)\n\t\t\t/* wrong cylinder => recal */\n\t\t\tDRS->track = NEED_2_RECAL;\n\t\treturn bad;\n\tcase 0x80:\t\t/* invalid command given */\n\t\tDPRINT(\"Invalid FDC command given!\\n\");\n\t\tcont->done(0);\n\t\treturn 2;\n\tcase 0xc0:\n\t\tDPRINT(\"Abnormal termination caused by polling\\n\");\n\t\tcont->error();\n\t\treturn 2;\n\tdefault:\t\t/* (0) Normal command termination */\n\t\treturn 0;\n\t}\n}", "/*\n * This routine is called when everything should be correctly set up\n * for the transfer (i.e. floppy motor is on, the correct floppy is\n * selected, and the head is sitting on the right track).\n */\nstatic void setup_rw_floppy(void)\n{\n\tint i;\n\tint r;\n\tint flags;\n\tint dflags;\n\tunsigned long ready_date;\n\tvoid (*function)(void);", "\tflags = raw_cmd->flags;\n\tif (flags & (FD_RAW_READ | FD_RAW_WRITE))\n\t\tflags |= FD_RAW_INTR;", "\tif ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) {\n\t\tready_date = DRS->spinup_date + DP->spinup;\n\t\t/* If spinup will take a long time, rerun scandrives\n\t\t * again just before spinup completion. Beware that\n\t\t * after scandrives, we must again wait for selection.\n\t\t */\n\t\tif (time_after(ready_date, jiffies + DP->select_delay)) {\n\t\t\tready_date -= DP->select_delay;\n\t\t\tfunction = floppy_start;\n\t\t} else\n\t\t\tfunction = setup_rw_floppy;", "\t\t/* wait until the floppy is spinning fast enough */\n\t\tif (fd_wait_for_completion(ready_date, function))\n\t\t\treturn;\n\t}\n\tdflags = DRS->flags;", "\tif ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE))\n\t\tsetup_DMA();", "\tif (flags & FD_RAW_INTR)\n\t\tdo_floppy = main_command_interrupt;", "\tr = 0;\n\tfor (i = 0; i < raw_cmd->cmd_count; i++)\n\t\tr |= output_byte(raw_cmd->cmd[i]);", "\tdebugt(__func__, \"rw_command\");", "\tif (r) {\n\t\tcont->error();\n\t\treset_fdc();\n\t\treturn;\n\t}", "\tif (!(flags & FD_RAW_INTR)) {\n\t\tinr = result();\n\t\tcont->interrupt();\n\t} else if (flags & FD_RAW_NEED_DISK)\n\t\tfd_watchdog();\n}", "static int blind_seek;", "/*\n * This is the routine called after every seek (or recalibrate) interrupt\n * from the floppy controller.\n */\nstatic void seek_interrupt(void)\n{\n\tdebugt(__func__, \"\");\n\tif (inr != 2 || (ST0 & 0xF8) != 0x20) {\n\t\tDPRINT(\"seek failed\\n\");\n\t\tDRS->track = NEED_2_RECAL;\n\t\tcont->error();\n\t\tcont->redo();\n\t\treturn;\n\t}\n\tif (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) {\n\t\tdebug_dcl(DP->flags,\n\t\t\t \"clearing NEWCHANGE flag because of effective seek\\n\");\n\t\tdebug_dcl(DP->flags, \"jiffies=%lu\\n\", jiffies);\n\t\tclear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);\n\t\t\t\t\t/* effective seek */\n\t\tDRS->select_date = jiffies;\n\t}\n\tDRS->track = ST1;\n\tfloppy_ready();\n}", "static void check_wp(void)\n{\n\tif (test_bit(FD_VERIFY_BIT, &DRS->flags)) {\n\t\t\t\t\t/* check write protection */\n\t\toutput_byte(FD_GETSTATUS);\n\t\toutput_byte(UNIT(current_drive));\n\t\tif (result() != 1) {\n\t\t\tFDCS->reset = 1;\n\t\t\treturn;\n\t\t}\n\t\tclear_bit(FD_VERIFY_BIT, &DRS->flags);\n\t\tclear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);\n\t\tdebug_dcl(DP->flags,\n\t\t\t \"checking whether disk is write protected\\n\");\n\t\tdebug_dcl(DP->flags, \"wp=%x\\n\", ST3 & 0x40);\n\t\tif (!(ST3 & 0x40))\n\t\t\tset_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);\n\t\telse\n\t\t\tclear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);\n\t}\n}", "static void seek_floppy(void)\n{\n\tint track;", "\tblind_seek = 0;", "\tdebug_dcl(DP->flags, \"calling disk change from %s\\n\", __func__);", "\tif (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&\n\t disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) {\n\t\t/* the media changed flag should be cleared after the seek.\n\t\t * If it isn't, this means that there is really no disk in\n\t\t * the drive.\n\t\t */\n\t\tset_bit(FD_DISK_CHANGED_BIT, &DRS->flags);\n\t\tcont->done(0);\n\t\tcont->redo();\n\t\treturn;\n\t}\n\tif (DRS->track <= NEED_1_RECAL) {\n\t\trecalibrate_floppy();\n\t\treturn;\n\t} else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&\n\t\t (raw_cmd->flags & FD_RAW_NEED_DISK) &&\n\t\t (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) {\n\t\t/* we seek to clear the media-changed condition. Does anybody\n\t\t * know a more elegant way, which works on all drives? */\n\t\tif (raw_cmd->track)\n\t\t\ttrack = raw_cmd->track - 1;\n\t\telse {\n\t\t\tif (DP->flags & FD_SILENT_DCL_CLEAR) {\n\t\t\t\tset_dor(fdc, ~(0x10 << UNIT(current_drive)), 0);\n\t\t\t\tblind_seek = 1;\n\t\t\t\traw_cmd->flags |= FD_RAW_NEED_SEEK;\n\t\t\t}\n\t\t\ttrack = 1;\n\t\t}\n\t} else {\n\t\tcheck_wp();\n\t\tif (raw_cmd->track != DRS->track &&\n\t\t (raw_cmd->flags & FD_RAW_NEED_SEEK))\n\t\t\ttrack = raw_cmd->track;\n\t\telse {\n\t\t\tsetup_rw_floppy();\n\t\t\treturn;\n\t\t}\n\t}", "\tdo_floppy = seek_interrupt;\n\toutput_byte(FD_SEEK);\n\toutput_byte(UNIT(current_drive));\n\tif (output_byte(track) < 0) {\n\t\treset_fdc();\n\t\treturn;\n\t}\n\tdebugt(__func__, \"\");\n}", "static void recal_interrupt(void)\n{\n\tdebugt(__func__, \"\");\n\tif (inr != 2)\n\t\tFDCS->reset = 1;\n\telse if (ST0 & ST0_ECE) {\n\t\tswitch (DRS->track) {\n\t\tcase NEED_1_RECAL:\n\t\t\tdebugt(__func__, \"need 1 recal\");\n\t\t\t/* after a second recalibrate, we still haven't\n\t\t\t * reached track 0. Probably no drive. Raise an\n\t\t\t * error, as failing immediately might upset\n\t\t\t * computers possessed by the Devil :-) */\n\t\t\tcont->error();\n\t\t\tcont->redo();\n\t\t\treturn;\n\t\tcase NEED_2_RECAL:\n\t\t\tdebugt(__func__, \"need 2 recal\");\n\t\t\t/* If we already did a recalibrate,\n\t\t\t * and we are not at track 0, this\n\t\t\t * means we have moved. (The only way\n\t\t\t * not to move at recalibration is to\n\t\t\t * be already at track 0.) Clear the\n\t\t\t * new change flag */\n\t\t\tdebug_dcl(DP->flags,\n\t\t\t\t \"clearing NEWCHANGE flag because of second recalibrate\\n\");", "\t\t\tclear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);\n\t\t\tDRS->select_date = jiffies;\n\t\t\t/* fall through */\n\t\tdefault:\n\t\t\tdebugt(__func__, \"default\");\n\t\t\t/* Recalibrate moves the head by at\n\t\t\t * most 80 steps. If after one\n\t\t\t * recalibrate we don't have reached\n\t\t\t * track 0, this might mean that we\n\t\t\t * started beyond track 80. Try\n\t\t\t * again. */\n\t\t\tDRS->track = NEED_1_RECAL;\n\t\t\tbreak;\n\t\t}\n\t} else\n\t\tDRS->track = ST1;\n\tfloppy_ready();\n}", "static void print_result(char *message, int inr)\n{\n\tint i;", "\tDPRINT(\"%s \", message);\n\tif (inr >= 0)\n\t\tfor (i = 0; i < inr; i++)\n\t\t\tpr_cont(\"repl[%d]=%x \", i, reply_buffer[i]);\n\tpr_cont(\"\\n\");\n}", "/* interrupt handler. Note that this can be called externally on the Sparc */\nirqreturn_t floppy_interrupt(int irq, void *dev_id)\n{\n\tint do_print;\n\tunsigned long f;\n\tvoid (*handler)(void) = do_floppy;", "\tlasthandler = handler;\n\tinterruptjiffies = jiffies;", "\tf = claim_dma_lock();\n\tfd_disable_dma();\n\trelease_dma_lock(f);", "\tdo_floppy = NULL;\n\tif (fdc >= N_FDC || FDCS->address == -1) {\n\t\t/* we don't even know which FDC is the culprit */\n\t\tpr_info(\"DOR0=%x\\n\", fdc_state[0].dor);\n\t\tpr_info(\"floppy interrupt on bizarre fdc %d\\n\", fdc);\n\t\tpr_info(\"handler=%pf\\n\", handler);\n\t\tis_alive(__func__, \"bizarre fdc\");\n\t\treturn IRQ_NONE;\n\t}", "\tFDCS->reset = 0;\n\t/* We have to clear the reset flag here, because apparently on boxes\n\t * with level triggered interrupts (PS/2, Sparc, ...), it is needed to\n\t * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the\n\t * emission of the SENSEI's.\n\t * It is OK to emit floppy commands because we are in an interrupt\n\t * handler here, and thus we have to fear no interference of other\n\t * activity.\n\t */", "\tdo_print = !handler && print_unex && initialized;", "\tinr = result();\n\tif (do_print)\n\t\tprint_result(\"unexpected interrupt\", inr);\n\tif (inr == 0) {\n\t\tint max_sensei = 4;\n\t\tdo {\n\t\t\toutput_byte(FD_SENSEI);\n\t\t\tinr = result();\n\t\t\tif (do_print)\n\t\t\t\tprint_result(\"sensei\", inr);\n\t\t\tmax_sensei--;\n\t\t} while ((ST0 & 0x83) != UNIT(current_drive) &&\n\t\t\t inr == 2 && max_sensei);\n\t}\n\tif (!handler) {\n\t\tFDCS->reset = 1;\n\t\treturn IRQ_NONE;\n\t}\n\tschedule_bh(handler);\n\tis_alive(__func__, \"normal interrupt end\");", "\t/* FIXME! Was it really for us? */\n\treturn IRQ_HANDLED;\n}", "static void recalibrate_floppy(void)\n{\n\tdebugt(__func__, \"\");\n\tdo_floppy = recal_interrupt;\n\toutput_byte(FD_RECALIBRATE);\n\tif (output_byte(UNIT(current_drive)) < 0)\n\t\treset_fdc();\n}", "/*\n * Must do 4 FD_SENSEIs after reset because of ``drive polling''.\n */\nstatic void reset_interrupt(void)\n{\n\tdebugt(__func__, \"\");\n\tresult();\t\t/* get the status ready for set_fdc */\n\tif (FDCS->reset) {\n\t\tpr_info(\"reset set in interrupt, calling %pf\\n\", cont->error);\n\t\tcont->error();\t/* a reset just after a reset. BAD! */\n\t}\n\tcont->redo();\n}", "/*\n * reset is done by pulling bit 2 of DOR low for a while (old FDCs),\n * or by setting the self clearing bit 7 of STATUS (newer FDCs)\n */\nstatic void reset_fdc(void)\n{\n\tunsigned long flags;", "\tdo_floppy = reset_interrupt;\n\tFDCS->reset = 0;\n\treset_fdc_info(0);", "\t/* Pseudo-DMA may intercept 'reset finished' interrupt. */\n\t/* Irrelevant for systems with true DMA (i386). */", "\tflags = claim_dma_lock();\n\tfd_disable_dma();\n\trelease_dma_lock(flags);", "\tif (FDCS->version >= FDC_82072A)\n\t\tfd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS);\n\telse {\n\t\tfd_outb(FDCS->dor & ~0x04, FD_DOR);\n\t\tudelay(FD_RESET_DELAY);\n\t\tfd_outb(FDCS->dor, FD_DOR);\n\t}\n}", "static void show_floppy(void)\n{\n\tint i;", "\tpr_info(\"\\n\");\n\tpr_info(\"floppy driver state\\n\");\n\tpr_info(\"-------------------\\n\");\n\tpr_info(\"now=%lu last interrupt=%lu diff=%lu last called handler=%pf\\n\",\n\t\tjiffies, interruptjiffies, jiffies - interruptjiffies,\n\t\tlasthandler);", "\tpr_info(\"timeout_message=%s\\n\", timeout_message);\n\tpr_info(\"last output bytes:\\n\");\n\tfor (i = 0; i < OLOGSIZE; i++)\n\t\tpr_info(\"%2x %2x %lu\\n\",\n\t\t\toutput_log[(i + output_log_pos) % OLOGSIZE].data,\n\t\t\toutput_log[(i + output_log_pos) % OLOGSIZE].status,\n\t\t\toutput_log[(i + output_log_pos) % OLOGSIZE].jiffies);\n\tpr_info(\"last result at %lu\\n\", resultjiffies);\n\tpr_info(\"last redo_fd_request at %lu\\n\", lastredo);\n\tprint_hex_dump(KERN_INFO, \"\", DUMP_PREFIX_NONE, 16, 1,\n\t\t reply_buffer, resultsize, true);", "\tpr_info(\"status=%x\\n\", fd_inb(FD_STATUS));\n\tpr_info(\"fdc_busy=%lu\\n\", fdc_busy);\n\tif (do_floppy)\n\t\tpr_info(\"do_floppy=%pf\\n\", do_floppy);\n\tif (work_pending(&floppy_work))\n\t\tpr_info(\"floppy_work.func=%pf\\n\", floppy_work.func);\n\tif (delayed_work_pending(&fd_timer))\n\t\tpr_info(\"delayed work.function=%p expires=%ld\\n\",\n\t\t fd_timer.work.func,\n\t\t fd_timer.timer.expires - jiffies);\n\tif (delayed_work_pending(&fd_timeout))\n\t\tpr_info(\"timer_function=%p expires=%ld\\n\",\n\t\t fd_timeout.work.func,\n\t\t fd_timeout.timer.expires - jiffies);", "\tpr_info(\"cont=%p\\n\", cont);\n\tpr_info(\"current_req=%p\\n\", current_req);\n\tpr_info(\"command_status=%d\\n\", command_status);\n\tpr_info(\"\\n\");\n}", "static void floppy_shutdown(struct work_struct *arg)\n{\n\tunsigned long flags;", "\tif (initialized)\n\t\tshow_floppy();\n\tcancel_activity();", "\tflags = claim_dma_lock();\n\tfd_disable_dma();\n\trelease_dma_lock(flags);", "\t/* avoid dma going to a random drive after shutdown */", "\tif (initialized)\n\t\tDPRINT(\"floppy timeout called\\n\");\n\tFDCS->reset = 1;\n\tif (cont) {\n\t\tcont->done(0);\n\t\tcont->redo();\t/* this will recall reset when needed */\n\t} else {\n\t\tpr_info(\"no cont in shutdown!\\n\");\n\t\tprocess_fd_request();\n\t}\n\tis_alive(__func__, \"\");\n}", "/* start motor, check media-changed condition and write protection */\nstatic int start_motor(void (*function)(void))\n{\n\tint mask;\n\tint data;", "\tmask = 0xfc;\n\tdata = UNIT(current_drive);\n\tif (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) {\n\t\tif (!(FDCS->dor & (0x10 << UNIT(current_drive)))) {\n\t\t\tset_debugt();\n\t\t\t/* no read since this drive is running */\n\t\t\tDRS->first_read_date = 0;\n\t\t\t/* note motor start time if motor is not yet running */\n\t\t\tDRS->spinup_date = jiffies;\n\t\t\tdata |= (0x10 << UNIT(current_drive));\n\t\t}\n\t} else if (FDCS->dor & (0x10 << UNIT(current_drive)))\n\t\tmask &= ~(0x10 << UNIT(current_drive));", "\t/* starts motor and selects floppy */\n\tdel_timer(motor_off_timer + current_drive);\n\tset_dor(fdc, mask, data);", "\t/* wait_for_completion also schedules reset if needed. */\n\treturn fd_wait_for_completion(DRS->select_date + DP->select_delay,\n\t\t\t\t function);\n}", "static void floppy_ready(void)\n{\n\tif (FDCS->reset) {\n\t\treset_fdc();\n\t\treturn;\n\t}\n\tif (start_motor(floppy_ready))\n\t\treturn;\n\tif (fdc_dtr())\n\t\treturn;", "\tdebug_dcl(DP->flags, \"calling disk change from floppy_ready\\n\");\n\tif (!(raw_cmd->flags & FD_RAW_NO_MOTOR) &&\n\t disk_change(current_drive) && !DP->select_delay)\n\t\ttwaddle();\t/* this clears the dcl on certain\n\t\t\t\t * drive/controller combinations */", "#ifdef fd_chose_dma_mode\n\tif ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) {\n\t\tunsigned long flags = claim_dma_lock();\n\t\tfd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length);\n\t\trelease_dma_lock(flags);\n\t}\n#endif", "\tif (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) {\n\t\tperpendicular_mode();\n\t\tfdc_specify();\t/* must be done here because of hut, hlt ... */\n\t\tseek_floppy();\n\t} else {\n\t\tif ((raw_cmd->flags & FD_RAW_READ) ||\n\t\t (raw_cmd->flags & FD_RAW_WRITE))\n\t\t\tfdc_specify();\n\t\tsetup_rw_floppy();\n\t}\n}", "static void floppy_start(void)\n{\n\treschedule_timeout(current_reqD, \"floppy start\");", "\tscandrives();\n\tdebug_dcl(DP->flags, \"setting NEWCHANGE in floppy_start\\n\");\n\tset_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);\n\tfloppy_ready();\n}", "/*\n * ========================================================================\n * here ends the bottom half. Exported routines are:\n * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc,\n * start_motor, reset_fdc, reset_fdc_info, interpret_errors.\n * Initialization also uses output_byte, result, set_dor, floppy_interrupt\n * and set_dor.\n * ========================================================================\n */\n/*\n * General purpose continuations.\n * ==============================\n */", "static void do_wakeup(void)\n{\n\treschedule_timeout(MAXTIMEOUT, \"do wakeup\");\n\tcont = NULL;\n\tcommand_status += 2;\n\twake_up(&command_done);\n}", "static const struct cont_t wakeup_cont = {\n\t.interrupt\t= empty,\n\t.redo\t\t= do_wakeup,\n\t.error\t\t= empty,\n\t.done\t\t= (done_f)empty\n};", "static const struct cont_t intr_cont = {\n\t.interrupt\t= empty,\n\t.redo\t\t= process_fd_request,\n\t.error\t\t= empty,\n\t.done\t\t= (done_f)empty\n};", "static int wait_til_done(void (*handler)(void), bool interruptible)\n{\n\tint ret;", "\tschedule_bh(handler);", "\tif (interruptible)\n\t\twait_event_interruptible(command_done, command_status >= 2);\n\telse\n\t\twait_event(command_done, command_status >= 2);", "\tif (command_status < 2) {\n\t\tcancel_activity();\n\t\tcont = &intr_cont;\n\t\treset_fdc();\n\t\treturn -EINTR;\n\t}", "\tif (FDCS->reset)\n\t\tcommand_status = FD_COMMAND_ERROR;\n\tif (command_status == FD_COMMAND_OKAY)\n\t\tret = 0;\n\telse\n\t\tret = -EIO;\n\tcommand_status = FD_COMMAND_NONE;\n\treturn ret;\n}", "static void generic_done(int result)\n{\n\tcommand_status = result;\n\tcont = &wakeup_cont;\n}", "static void generic_success(void)\n{\n\tcont->done(1);\n}", "static void generic_failure(void)\n{\n\tcont->done(0);\n}", "static void success_and_wakeup(void)\n{\n\tgeneric_success();\n\tcont->redo();\n}", "/*\n * formatting and rw support.\n * ==========================\n */", "static int next_valid_format(void)\n{\n\tint probed_format;", "\tprobed_format = DRS->probed_format;\n\twhile (1) {\n\t\tif (probed_format >= 8 || !DP->autodetect[probed_format]) {\n\t\t\tDRS->probed_format = 0;\n\t\t\treturn 1;\n\t\t}\n\t\tif (floppy_type[DP->autodetect[probed_format]].sect) {\n\t\t\tDRS->probed_format = probed_format;\n\t\t\treturn 0;\n\t\t}\n\t\tprobed_format++;\n\t}\n}", "static void bad_flp_intr(void)\n{\n\tint err_count;", "\tif (probing) {\n\t\tDRS->probed_format++;\n\t\tif (!next_valid_format())\n\t\t\treturn;\n\t}\n\terr_count = ++(*errors);\n\tINFBOUND(DRWE->badness, err_count);\n\tif (err_count > DP->max_errors.abort)\n\t\tcont->done(0);\n\tif (err_count > DP->max_errors.reset)\n\t\tFDCS->reset = 1;\n\telse if (err_count > DP->max_errors.recal)\n\t\tDRS->track = NEED_2_RECAL;\n}", "static void set_floppy(int drive)\n{\n\tint type = ITYPE(UDRS->fd_device);", "\tif (type)\n\t\t_floppy = floppy_type + type;\n\telse\n\t\t_floppy = current_type[drive];\n}", "/*\n * formatting support.\n * ===================\n */\nstatic void format_interrupt(void)\n{\n\tswitch (interpret_errors()) {\n\tcase 1:\n\t\tcont->error();\n\tcase 2:\n\t\tbreak;\n\tcase 0:\n\t\tcont->done(1);\n\t}\n\tcont->redo();\n}", "#define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1))\n#define CT(x) ((x) | 0xc0)", "static void setup_format_params(int track)\n{\n\tint n;\n\tint il;\n\tint count;\n\tint head_shift;\n\tint track_shift;\n\tstruct fparm {\n\t\tunsigned char track, head, sect, size;\n\t} *here = (struct fparm *)floppy_track_buffer;", "\traw_cmd = &default_raw_cmd;\n\traw_cmd->track = track;", "\traw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |\n\t\t\t FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);\n\traw_cmd->rate = _floppy->rate & 0x43;\n\traw_cmd->cmd_count = NR_F;\n\tCOMMAND = FM_MODE(_floppy, FD_FORMAT);\n\tDR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);\n\tF_SIZECODE = FD_SIZECODE(_floppy);\n\tF_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;\n\tF_GAP = _floppy->fmt_gap;\n\tF_FILL = FD_FILL_BYTE;", "\traw_cmd->kernel_data = floppy_track_buffer;\n\traw_cmd->length = 4 * F_SECT_PER_TRACK;", "\t/* allow for about 30ms for data transport per track */\n\thead_shift = (F_SECT_PER_TRACK + 5) / 6;", "\t/* a ``cylinder'' is two tracks plus a little stepping time */\n\ttrack_shift = 2 * head_shift + 3;", "\t/* position of logical sector 1 on this track */\n\tn = (track_shift * format_req.track + head_shift * format_req.head)\n\t % F_SECT_PER_TRACK;", "\t/* determine interleave */\n\til = 1;\n\tif (_floppy->fmt_gap < 0x22)\n\t\til++;", "\t/* initialize field */\n\tfor (count = 0; count < F_SECT_PER_TRACK; ++count) {\n\t\there[count].track = format_req.track;\n\t\there[count].head = format_req.head;\n\t\there[count].sect = 0;\n\t\there[count].size = F_SIZECODE;\n\t}\n\t/* place logical sectors */\n\tfor (count = 1; count <= F_SECT_PER_TRACK; ++count) {\n\t\there[n].sect = count;\n\t\tn = (n + il) % F_SECT_PER_TRACK;\n\t\tif (here[n].sect) {\t/* sector busy, find next free sector */\n\t\t\t++n;\n\t\t\tif (n >= F_SECT_PER_TRACK) {\n\t\t\t\tn -= F_SECT_PER_TRACK;\n\t\t\t\twhile (here[n].sect)\n\t\t\t\t\t++n;\n\t\t\t}\n\t\t}\n\t}\n\tif (_floppy->stretch & FD_SECTBASEMASK) {\n\t\tfor (count = 0; count < F_SECT_PER_TRACK; count++)\n\t\t\there[count].sect += FD_SECTBASE(_floppy) - 1;\n\t}\n}", "static void redo_format(void)\n{\n\tbuffer_track = -1;\n\tsetup_format_params(format_req.track << STRETCH(_floppy));\n\tfloppy_start();\n\tdebugt(__func__, \"queue format request\");\n}", "static const struct cont_t format_cont = {\n\t.interrupt\t= format_interrupt,\n\t.redo\t\t= redo_format,\n\t.error\t\t= bad_flp_intr,\n\t.done\t\t= generic_done\n};", "static int do_format(int drive, struct format_descr *tmp_format_req)\n{\n\tint ret;", "\tif (lock_fdc(drive, true))\n\t\treturn -EINTR;", "\tset_floppy(drive);\n\tif (!_floppy ||\n\t _floppy->track > DP->tracks ||\n\t tmp_format_req->track >= _floppy->track ||\n\t tmp_format_req->head >= _floppy->head ||\n\t (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) ||\n\t !_floppy->fmt_gap) {\n\t\tprocess_fd_request();\n\t\treturn -EINVAL;\n\t}\n\tformat_req = *tmp_format_req;\n\tformat_errors = 0;\n\tcont = &format_cont;\n\terrors = &format_errors;\n\tret = wait_til_done(redo_format, true);\n\tif (ret == -EINTR)\n\t\treturn -EINTR;\n\tprocess_fd_request();\n\treturn ret;\n}", "/*\n * Buffer read/write and support\n * =============================\n */", "static void floppy_end_request(struct request *req, int error)\n{\n\tunsigned int nr_sectors = current_count_sectors;\n\tunsigned int drive = (unsigned long)req->rq_disk->private_data;", "\t/* current_count_sectors can be zero if transfer failed */\n\tif (error)\n\t\tnr_sectors = blk_rq_cur_sectors(req);\n\tif (__blk_end_request(req, error, nr_sectors << 9))\n\t\treturn;", "\t/* We're done with the request */\n\tfloppy_off(drive);\n\tcurrent_req = NULL;\n}", "/* new request_done. Can handle physical sectors which are smaller than a\n * logical buffer */\nstatic void request_done(int uptodate)\n{\n\tstruct request *req = current_req;\n\tstruct request_queue *q;\n\tunsigned long flags;\n\tint block;\n\tchar msg[sizeof(\"request done \") + sizeof(int) * 3];", "\tprobing = 0;\n\tsnprintf(msg, sizeof(msg), \"request done %d\", uptodate);\n\treschedule_timeout(MAXTIMEOUT, msg);", "\tif (!req) {\n\t\tpr_info(\"floppy.c: no request in request_done\\n\");\n\t\treturn;\n\t}", "\tq = req->q;", "\tif (uptodate) {\n\t\t/* maintain values for invalidation on geometry\n\t\t * change */\n\t\tblock = current_count_sectors + blk_rq_pos(req);\n\t\tINFBOUND(DRS->maxblock, block);\n\t\tif (block > _floppy->sect)\n\t\t\tDRS->maxtrack = 1;", "\t\t/* unlock chained buffers */\n\t\tspin_lock_irqsave(q->queue_lock, flags);\n\t\tfloppy_end_request(req, 0);\n\t\tspin_unlock_irqrestore(q->queue_lock, flags);\n\t} else {\n\t\tif (rq_data_dir(req) == WRITE) {\n\t\t\t/* record write error information */\n\t\t\tDRWE->write_errors++;\n\t\t\tif (DRWE->write_errors == 1) {\n\t\t\t\tDRWE->first_error_sector = blk_rq_pos(req);\n\t\t\t\tDRWE->first_error_generation = DRS->generation;\n\t\t\t}\n\t\t\tDRWE->last_error_sector = blk_rq_pos(req);\n\t\t\tDRWE->last_error_generation = DRS->generation;\n\t\t}\n\t\tspin_lock_irqsave(q->queue_lock, flags);\n\t\tfloppy_end_request(req, -EIO);\n\t\tspin_unlock_irqrestore(q->queue_lock, flags);\n\t}\n}", "/* Interrupt handler evaluating the result of the r/w operation */\nstatic void rw_interrupt(void)\n{\n\tint eoc;\n\tint ssize;\n\tint heads;\n\tint nr_sectors;", "\tif (R_HEAD >= 2) {\n\t\t/* some Toshiba floppy controllers occasionnally seem to\n\t\t * return bogus interrupts after read/write operations, which\n\t\t * can be recognized by a bad head number (>= 2) */\n\t\treturn;\n\t}", "\tif (!DRS->first_read_date)\n\t\tDRS->first_read_date = jiffies;", "\tnr_sectors = 0;\n\tssize = DIV_ROUND_UP(1 << SIZECODE, 4);", "\tif (ST1 & ST1_EOC)\n\t\teoc = 1;\n\telse\n\t\teoc = 0;", "\tif (COMMAND & 0x80)\n\t\theads = 2;\n\telse\n\t\theads = 1;", "\tnr_sectors = (((R_TRACK - TRACK) * heads +\n\t\t R_HEAD - HEAD) * SECT_PER_TRACK +\n\t\t R_SECTOR - SECTOR + eoc) << SIZECODE >> 2;", "\tif (nr_sectors / ssize >\n\t DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) {\n\t\tDPRINT(\"long rw: %x instead of %lx\\n\",\n\t\t nr_sectors, current_count_sectors);\n\t\tpr_info(\"rs=%d s=%d\\n\", R_SECTOR, SECTOR);\n\t\tpr_info(\"rh=%d h=%d\\n\", R_HEAD, HEAD);\n\t\tpr_info(\"rt=%d t=%d\\n\", R_TRACK, TRACK);\n\t\tpr_info(\"heads=%d eoc=%d\\n\", heads, eoc);\n\t\tpr_info(\"spt=%d st=%d ss=%d\\n\",\n\t\t\tSECT_PER_TRACK, fsector_t, ssize);\n\t\tpr_info(\"in_sector_offset=%d\\n\", in_sector_offset);\n\t}", "\tnr_sectors -= in_sector_offset;\n\tINFBOUND(nr_sectors, 0);\n\tSUPBOUND(current_count_sectors, nr_sectors);", "\tswitch (interpret_errors()) {\n\tcase 2:\n\t\tcont->redo();\n\t\treturn;\n\tcase 1:\n\t\tif (!current_count_sectors) {\n\t\t\tcont->error();\n\t\t\tcont->redo();\n\t\t\treturn;\n\t\t}\n\t\tbreak;\n\tcase 0:\n\t\tif (!current_count_sectors) {\n\t\t\tcont->redo();\n\t\t\treturn;\n\t\t}\n\t\tcurrent_type[current_drive] = _floppy;\n\t\tfloppy_sizes[TOMINOR(current_drive)] = _floppy->size;\n\t\tbreak;\n\t}", "\tif (probing) {\n\t\tif (DP->flags & FTD_MSG)\n\t\t\tDPRINT(\"Auto-detected floppy type %s in fd%d\\n\",\n\t\t\t _floppy->name, current_drive);\n\t\tcurrent_type[current_drive] = _floppy;\n\t\tfloppy_sizes[TOMINOR(current_drive)] = _floppy->size;\n\t\tprobing = 0;\n\t}", "\tif (CT(COMMAND) != FD_READ ||\n\t raw_cmd->kernel_data == current_req->buffer) {\n\t\t/* transfer directly from buffer */\n\t\tcont->done(1);\n\t} else if (CT(COMMAND) == FD_READ) {\n\t\tbuffer_track = raw_cmd->track;\n\t\tbuffer_drive = current_drive;\n\t\tINFBOUND(buffer_max, nr_sectors + fsector_t);\n\t}\n\tcont->redo();\n}", "/* Compute maximal contiguous buffer size. */\nstatic int buffer_chain_size(void)\n{\n\tstruct bio_vec bv;\n\tint size;\n\tstruct req_iterator iter;\n\tchar *base;", "\tbase = bio_data(current_req->bio);\n\tsize = 0;", "\trq_for_each_segment(bv, current_req, iter) {\n\t\tif (page_address(bv.bv_page) + bv.bv_offset != base + size)\n\t\t\tbreak;", "\t\tsize += bv.bv_len;\n\t}", "\treturn size >> 9;\n}", "/* Compute the maximal transfer size */\nstatic int transfer_size(int ssize, int max_sector, int max_size)\n{\n\tSUPBOUND(max_sector, fsector_t + max_size);", "\t/* alignment */\n\tmax_sector -= (max_sector % _floppy->sect) % ssize;", "\t/* transfer size, beginning not aligned */\n\tcurrent_count_sectors = max_sector - fsector_t;", "\treturn max_sector;\n}", "/*\n * Move data from/to the track buffer to/from the buffer cache.\n */\nstatic void copy_buffer(int ssize, int max_sector, int max_sector_2)\n{\n\tint remaining;\t\t/* number of transferred 512-byte sectors */\n\tstruct bio_vec bv;\n\tchar *buffer;\n\tchar *dma_buffer;\n\tint size;\n\tstruct req_iterator iter;", "\tmax_sector = transfer_size(ssize,\n\t\t\t\t min(max_sector, max_sector_2),\n\t\t\t\t blk_rq_sectors(current_req));", "\tif (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&\n\t buffer_max > fsector_t + blk_rq_sectors(current_req))\n\t\tcurrent_count_sectors = min_t(int, buffer_max - fsector_t,\n\t\t\t\t\t blk_rq_sectors(current_req));", "\tremaining = current_count_sectors << 9;\n\tif (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) {\n\t\tDPRINT(\"in copy buffer\\n\");\n\t\tpr_info(\"current_count_sectors=%ld\\n\", current_count_sectors);\n\t\tpr_info(\"remaining=%d\\n\", remaining >> 9);\n\t\tpr_info(\"current_req->nr_sectors=%u\\n\",\n\t\t\tblk_rq_sectors(current_req));\n\t\tpr_info(\"current_req->current_nr_sectors=%u\\n\",\n\t\t\tblk_rq_cur_sectors(current_req));\n\t\tpr_info(\"max_sector=%d\\n\", max_sector);\n\t\tpr_info(\"ssize=%d\\n\", ssize);\n\t}", "\tbuffer_max = max(max_sector, buffer_max);", "\tdma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9);", "\tsize = blk_rq_cur_bytes(current_req);", "\trq_for_each_segment(bv, current_req, iter) {\n\t\tif (!remaining)\n\t\t\tbreak;", "\t\tsize = bv.bv_len;\n\t\tSUPBOUND(size, remaining);", "\t\tbuffer = page_address(bv.bv_page) + bv.bv_offset;\n\t\tif (dma_buffer + size >\n\t\t floppy_track_buffer + (max_buffer_sectors << 10) ||\n\t\t dma_buffer < floppy_track_buffer) {\n\t\t\tDPRINT(\"buffer overrun in copy buffer %d\\n\",\n\t\t\t (int)((floppy_track_buffer - dma_buffer) >> 9));\n\t\t\tpr_info(\"fsector_t=%d buffer_min=%d\\n\",\n\t\t\t\tfsector_t, buffer_min);\n\t\t\tpr_info(\"current_count_sectors=%ld\\n\",\n\t\t\t\tcurrent_count_sectors);\n\t\t\tif (CT(COMMAND) == FD_READ)\n\t\t\t\tpr_info(\"read\\n\");\n\t\t\tif (CT(COMMAND) == FD_WRITE)\n\t\t\t\tpr_info(\"write\\n\");\n\t\t\tbreak;\n\t\t}\n\t\tif (((unsigned long)buffer) % 512)\n\t\t\tDPRINT(\"%p buffer not aligned\\n\", buffer);", "\t\tif (CT(COMMAND) == FD_READ)\n\t\t\tmemcpy(buffer, dma_buffer, size);\n\t\telse\n\t\t\tmemcpy(dma_buffer, buffer, size);", "\t\tremaining -= size;\n\t\tdma_buffer += size;\n\t}\n\tif (remaining) {\n\t\tif (remaining > 0)\n\t\t\tmax_sector -= remaining >> 9;\n\t\tDPRINT(\"weirdness: remaining %d\\n\", remaining >> 9);\n\t}\n}", "/* work around a bug in pseudo DMA\n * (on some FDCs) pseudo DMA does not stop when the CPU stops\n * sending data. Hence we need a different way to signal the\n * transfer length: We use SECT_PER_TRACK. Unfortunately, this\n * does not work with MT, hence we can only transfer one head at\n * a time\n */\nstatic void virtualdmabug_workaround(void)\n{\n\tint hard_sectors;\n\tint end_sector;", "\tif (CT(COMMAND) == FD_WRITE) {\n\t\tCOMMAND &= ~0x80;\t/* switch off multiple track mode */", "\t\thard_sectors = raw_cmd->length >> (7 + SIZECODE);\n\t\tend_sector = SECTOR + hard_sectors - 1;\n\t\tif (end_sector > SECT_PER_TRACK) {\n\t\t\tpr_info(\"too many sectors %d > %d\\n\",\n\t\t\t\tend_sector, SECT_PER_TRACK);\n\t\t\treturn;\n\t\t}\n\t\tSECT_PER_TRACK = end_sector;\n\t\t\t\t\t/* make sure SECT_PER_TRACK\n\t\t\t\t\t * points to end of transfer */\n\t}\n}", "/*\n * Formulate a read/write request.\n * this routine decides where to load the data (directly to buffer, or to\n * tmp floppy area), how much data to load (the size of the buffer, the whole\n * track, or a single sector)\n * All floppy_track_buffer handling goes in here. If we ever add track buffer\n * allocation on the fly, it should be done here. No other part should need\n * modification.\n */", "static int make_raw_rw_request(void)\n{\n\tint aligned_sector_t;\n\tint max_sector;\n\tint max_size;\n\tint tracksize;\n\tint ssize;", "\tif (WARN(max_buffer_sectors == 0, \"VFS: Block I/O scheduled on unopened device\\n\"))\n\t\treturn 0;", "\tset_fdc((long)current_req->rq_disk->private_data);", "\traw_cmd = &default_raw_cmd;\n\traw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK;\n\traw_cmd->cmd_count = NR_RW;\n\tif (rq_data_dir(current_req) == READ) {\n\t\traw_cmd->flags |= FD_RAW_READ;\n\t\tCOMMAND = FM_MODE(_floppy, FD_READ);\n\t} else if (rq_data_dir(current_req) == WRITE) {\n\t\traw_cmd->flags |= FD_RAW_WRITE;\n\t\tCOMMAND = FM_MODE(_floppy, FD_WRITE);\n\t} else {\n\t\tDPRINT(\"%s: unknown command\\n\", __func__);\n\t\treturn 0;\n\t}", "\tmax_sector = _floppy->sect * _floppy->head;", "\tTRACK = (int)blk_rq_pos(current_req) / max_sector;\n\tfsector_t = (int)blk_rq_pos(current_req) % max_sector;\n\tif (_floppy->track && TRACK >= _floppy->track) {\n\t\tif (blk_rq_cur_sectors(current_req) & 1) {\n\t\t\tcurrent_count_sectors = 1;\n\t\t\treturn 1;\n\t\t} else\n\t\t\treturn 0;\n\t}\n\tHEAD = fsector_t / _floppy->sect;", "\tif (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) ||\n\t test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) &&\n\t fsector_t < _floppy->sect)\n\t\tmax_sector = _floppy->sect;", "\t/* 2M disks have phantom sectors on the first track */\n\tif ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) {\n\t\tmax_sector = 2 * _floppy->sect / 3;\n\t\tif (fsector_t >= max_sector) {\n\t\t\tcurrent_count_sectors =\n\t\t\t min_t(int, _floppy->sect - fsector_t,\n\t\t\t\t blk_rq_sectors(current_req));\n\t\t\treturn 1;\n\t\t}\n\t\tSIZECODE = 2;\n\t} else\n\t\tSIZECODE = FD_SIZECODE(_floppy);\n\traw_cmd->rate = _floppy->rate & 0x43;\n\tif ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2)\n\t\traw_cmd->rate = 1;", "\tif (SIZECODE)\n\t\tSIZECODE2 = 0xff;\n\telse\n\t\tSIZECODE2 = 0x80;\n\traw_cmd->track = TRACK << STRETCH(_floppy);\n\tDR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD);\n\tGAP = _floppy->gap;\n\tssize = DIV_ROUND_UP(1 << SIZECODE, 4);\n\tSECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;\n\tSECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) +\n\t FD_SECTBASE(_floppy);", "\t/* tracksize describes the size which can be filled up with sectors\n\t * of size ssize.\n\t */\n\ttracksize = _floppy->sect - _floppy->sect % ssize;\n\tif (tracksize < _floppy->sect) {\n\t\tSECT_PER_TRACK++;\n\t\tif (tracksize <= fsector_t % _floppy->sect)\n\t\t\tSECTOR--;", "\t\t/* if we are beyond tracksize, fill up using smaller sectors */\n\t\twhile (tracksize <= fsector_t % _floppy->sect) {\n\t\t\twhile (tracksize + ssize > _floppy->sect) {\n\t\t\t\tSIZECODE--;\n\t\t\t\tssize >>= 1;\n\t\t\t}\n\t\t\tSECTOR++;\n\t\t\tSECT_PER_TRACK++;\n\t\t\ttracksize += ssize;\n\t\t}\n\t\tmax_sector = HEAD * _floppy->sect + tracksize;\n\t} else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {\n\t\tmax_sector = _floppy->sect;\n\t} else if (!HEAD && CT(COMMAND) == FD_WRITE) {\n\t\t/* for virtual DMA bug workaround */\n\t\tmax_sector = _floppy->sect;\n\t}", "\tin_sector_offset = (fsector_t % _floppy->sect) % ssize;\n\taligned_sector_t = fsector_t - in_sector_offset;\n\tmax_size = blk_rq_sectors(current_req);\n\tif ((raw_cmd->track == buffer_track) &&\n\t (current_drive == buffer_drive) &&\n\t (fsector_t >= buffer_min) && (fsector_t < buffer_max)) {\n\t\t/* data already in track buffer */\n\t\tif (CT(COMMAND) == FD_READ) {\n\t\t\tcopy_buffer(1, max_sector, buffer_max);\n\t\t\treturn 1;\n\t\t}\n\t} else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) {\n\t\tif (CT(COMMAND) == FD_WRITE) {\n\t\t\tunsigned int sectors;", "\t\t\tsectors = fsector_t + blk_rq_sectors(current_req);\n\t\t\tif (sectors > ssize && sectors < ssize + ssize)\n\t\t\t\tmax_size = ssize + ssize;\n\t\t\telse\n\t\t\t\tmax_size = ssize;\n\t\t}\n\t\traw_cmd->flags &= ~FD_RAW_WRITE;\n\t\traw_cmd->flags |= FD_RAW_READ;\n\t\tCOMMAND = FM_MODE(_floppy, FD_READ);\n\t} else if ((unsigned long)current_req->buffer < MAX_DMA_ADDRESS) {\n\t\tunsigned long dma_limit;\n\t\tint direct, indirect;", "\t\tindirect =\n\t\t transfer_size(ssize, max_sector,\n\t\t\t\t max_buffer_sectors * 2) - fsector_t;", "\t\t/*\n\t\t * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide\n\t\t * on a 64 bit machine!\n\t\t */\n\t\tmax_size = buffer_chain_size();\n\t\tdma_limit = (MAX_DMA_ADDRESS -\n\t\t\t ((unsigned long)current_req->buffer)) >> 9;\n\t\tif ((unsigned long)max_size > dma_limit)\n\t\t\tmax_size = dma_limit;\n\t\t/* 64 kb boundaries */\n\t\tif (CROSS_64KB(current_req->buffer, max_size << 9))\n\t\t\tmax_size = (K_64 -\n\t\t\t\t ((unsigned long)current_req->buffer) %\n\t\t\t\t K_64) >> 9;\n\t\tdirect = transfer_size(ssize, max_sector, max_size) - fsector_t;\n\t\t/*\n\t\t * We try to read tracks, but if we get too many errors, we\n\t\t * go back to reading just one sector at a time.\n\t\t *\n\t\t * This means we should be able to read a sector even if there\n\t\t * are other bad sectors on this track.\n\t\t */\n\t\tif (!direct ||\n\t\t (indirect * 2 > direct * 3 &&\n\t\t *errors < DP->max_errors.read_track &&\n\t\t ((!probing ||\n\t\t (DP->read_track & (1 << DRS->probed_format)))))) {\n\t\t\tmax_size = blk_rq_sectors(current_req);\n\t\t} else {\n\t\t\traw_cmd->kernel_data = current_req->buffer;\n\t\t\traw_cmd->length = current_count_sectors << 9;\n\t\t\tif (raw_cmd->length == 0) {\n\t\t\t\tDPRINT(\"%s: zero dma transfer attempted\\n\", __func__);\n\t\t\t\tDPRINT(\"indirect=%d direct=%d fsector_t=%d\\n\",\n\t\t\t\t indirect, direct, fsector_t);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tvirtualdmabug_workaround();\n\t\t\treturn 2;\n\t\t}\n\t}", "\tif (CT(COMMAND) == FD_READ)\n\t\tmax_size = max_sector;\t/* unbounded */", "\t/* claim buffer track if needed */\n\tif (buffer_track != raw_cmd->track ||\t/* bad track */\n\t buffer_drive != current_drive ||\t/* bad drive */\n\t fsector_t > buffer_max ||\n\t fsector_t < buffer_min ||\n\t ((CT(COMMAND) == FD_READ ||\n\t (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) &&\n\t max_sector > 2 * max_buffer_sectors + buffer_min &&\n\t max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) {\n\t\t/* not enough space */\n\t\tbuffer_track = -1;\n\t\tbuffer_drive = current_drive;\n\t\tbuffer_max = buffer_min = aligned_sector_t;\n\t}\n\traw_cmd->kernel_data = floppy_track_buffer +\n\t\t((aligned_sector_t - buffer_min) << 9);", "\tif (CT(COMMAND) == FD_WRITE) {\n\t\t/* copy write buffer to track buffer.\n\t\t * if we get here, we know that the write\n\t\t * is either aligned or the data already in the buffer\n\t\t * (buffer will be overwritten) */\n\t\tif (in_sector_offset && buffer_track == -1)\n\t\t\tDPRINT(\"internal error offset !=0 on write\\n\");\n\t\tbuffer_track = raw_cmd->track;\n\t\tbuffer_drive = current_drive;\n\t\tcopy_buffer(ssize, max_sector,\n\t\t\t 2 * max_buffer_sectors + buffer_min);\n\t} else\n\t\ttransfer_size(ssize, max_sector,\n\t\t\t 2 * max_buffer_sectors + buffer_min -\n\t\t\t aligned_sector_t);", "\t/* round up current_count_sectors to get dma xfer size */\n\traw_cmd->length = in_sector_offset + current_count_sectors;\n\traw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1;\n\traw_cmd->length <<= 9;\n\tif ((raw_cmd->length < current_count_sectors << 9) ||\n\t (raw_cmd->kernel_data != current_req->buffer &&\n\t CT(COMMAND) == FD_WRITE &&\n\t (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||\n\t aligned_sector_t < buffer_min)) ||\n\t raw_cmd->length % (128 << SIZECODE) ||\n\t raw_cmd->length <= 0 || current_count_sectors <= 0) {\n\t\tDPRINT(\"fractionary current count b=%lx s=%lx\\n\",\n\t\t raw_cmd->length, current_count_sectors);\n\t\tif (raw_cmd->kernel_data != current_req->buffer)\n\t\t\tpr_info(\"addr=%d, length=%ld\\n\",\n\t\t\t\t(int)((raw_cmd->kernel_data -\n\t\t\t\t floppy_track_buffer) >> 9),\n\t\t\t\tcurrent_count_sectors);\n\t\tpr_info(\"st=%d ast=%d mse=%d msi=%d\\n\",\n\t\t\tfsector_t, aligned_sector_t, max_sector, max_size);\n\t\tpr_info(\"ssize=%x SIZECODE=%d\\n\", ssize, SIZECODE);\n\t\tpr_info(\"command=%x SECTOR=%d HEAD=%d, TRACK=%d\\n\",\n\t\t\tCOMMAND, SECTOR, HEAD, TRACK);\n\t\tpr_info(\"buffer drive=%d\\n\", buffer_drive);\n\t\tpr_info(\"buffer track=%d\\n\", buffer_track);\n\t\tpr_info(\"buffer_min=%d\\n\", buffer_min);\n\t\tpr_info(\"buffer_max=%d\\n\", buffer_max);\n\t\treturn 0;\n\t}", "\tif (raw_cmd->kernel_data != current_req->buffer) {\n\t\tif (raw_cmd->kernel_data < floppy_track_buffer ||\n\t\t current_count_sectors < 0 ||\n\t\t raw_cmd->length < 0 ||\n\t\t raw_cmd->kernel_data + raw_cmd->length >\n\t\t floppy_track_buffer + (max_buffer_sectors << 10)) {\n\t\t\tDPRINT(\"buffer overrun in schedule dma\\n\");\n\t\t\tpr_info(\"fsector_t=%d buffer_min=%d current_count=%ld\\n\",\n\t\t\t\tfsector_t, buffer_min, raw_cmd->length >> 9);\n\t\t\tpr_info(\"current_count_sectors=%ld\\n\",\n\t\t\t\tcurrent_count_sectors);\n\t\t\tif (CT(COMMAND) == FD_READ)\n\t\t\t\tpr_info(\"read\\n\");\n\t\t\tif (CT(COMMAND) == FD_WRITE)\n\t\t\t\tpr_info(\"write\\n\");\n\t\t\treturn 0;\n\t\t}\n\t} else if (raw_cmd->length > blk_rq_bytes(current_req) ||\n\t\t current_count_sectors > blk_rq_sectors(current_req)) {\n\t\tDPRINT(\"buffer overrun in direct transfer\\n\");\n\t\treturn 0;\n\t} else if (raw_cmd->length < current_count_sectors << 9) {\n\t\tDPRINT(\"more sectors than bytes\\n\");\n\t\tpr_info(\"bytes=%ld\\n\", raw_cmd->length >> 9);\n\t\tpr_info(\"sectors=%ld\\n\", current_count_sectors);\n\t}\n\tif (raw_cmd->length == 0) {\n\t\tDPRINT(\"zero dma transfer attempted from make_raw_request\\n\");\n\t\treturn 0;\n\t}", "\tvirtualdmabug_workaround();\n\treturn 2;\n}", "/*\n * Round-robin between our available drives, doing one request from each\n */\nstatic int set_next_request(void)\n{\n\tstruct request_queue *q;\n\tint old_pos = fdc_queue;", "\tdo {\n\t\tq = disks[fdc_queue]->queue;\n\t\tif (++fdc_queue == N_DRIVE)\n\t\t\tfdc_queue = 0;\n\t\tif (q) {\n\t\t\tcurrent_req = blk_fetch_request(q);\n\t\t\tif (current_req)\n\t\t\t\tbreak;\n\t\t}\n\t} while (fdc_queue != old_pos);", "\treturn current_req != NULL;\n}", "static void redo_fd_request(void)\n{\n\tint drive;\n\tint tmp;", "\tlastredo = jiffies;\n\tif (current_drive < N_DRIVE)\n\t\tfloppy_off(current_drive);", "do_request:\n\tif (!current_req) {\n\t\tint pending;", "\t\tspin_lock_irq(&floppy_lock);\n\t\tpending = set_next_request();\n\t\tspin_unlock_irq(&floppy_lock);\n\t\tif (!pending) {\n\t\t\tdo_floppy = NULL;\n\t\t\tunlock_fdc();\n\t\t\treturn;\n\t\t}\n\t}\n\tdrive = (long)current_req->rq_disk->private_data;\n\tset_fdc(drive);\n\treschedule_timeout(current_reqD, \"redo fd request\");", "\tset_floppy(drive);\n\traw_cmd = &default_raw_cmd;\n\traw_cmd->flags = 0;\n\tif (start_motor(redo_fd_request))\n\t\treturn;", "\tdisk_change(current_drive);\n\tif (test_bit(current_drive, &fake_change) ||\n\t test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) {\n\t\tDPRINT(\"disk absent or changed during operation\\n\");\n\t\trequest_done(0);\n\t\tgoto do_request;\n\t}\n\tif (!_floppy) {\t/* Autodetection */\n\t\tif (!probing) {\n\t\t\tDRS->probed_format = 0;\n\t\t\tif (next_valid_format()) {\n\t\t\t\tDPRINT(\"no autodetectable formats\\n\");\n\t\t\t\t_floppy = NULL;\n\t\t\t\trequest_done(0);\n\t\t\t\tgoto do_request;\n\t\t\t}\n\t\t}\n\t\tprobing = 1;\n\t\t_floppy = floppy_type + DP->autodetect[DRS->probed_format];\n\t} else\n\t\tprobing = 0;\n\terrors = &(current_req->errors);\n\ttmp = make_raw_rw_request();\n\tif (tmp < 2) {\n\t\trequest_done(tmp);\n\t\tgoto do_request;\n\t}", "\tif (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags))\n\t\ttwaddle();\n\tschedule_bh(floppy_start);\n\tdebugt(__func__, \"queue fd request\");\n\treturn;\n}", "static const struct cont_t rw_cont = {\n\t.interrupt\t= rw_interrupt,\n\t.redo\t\t= redo_fd_request,\n\t.error\t\t= bad_flp_intr,\n\t.done\t\t= request_done\n};", "static void process_fd_request(void)\n{\n\tcont = &rw_cont;\n\tschedule_bh(redo_fd_request);\n}", "static void do_fd_request(struct request_queue *q)\n{\n\tif (WARN(max_buffer_sectors == 0,\n\t\t \"VFS: %s called on non-open device\\n\", __func__))\n\t\treturn;", "\tif (WARN(atomic_read(&usage_count) == 0,\n\t\t \"warning: usage count=0, current_req=%p sect=%ld type=%x flags=%llx\\n\",\n\t\t current_req, (long)blk_rq_pos(current_req), current_req->cmd_type,\n\t\t (unsigned long long) current_req->cmd_flags))\n\t\treturn;", "\tif (test_and_set_bit(0, &fdc_busy)) {\n\t\t/* fdc busy, this new request will be treated when the\n\t\t current one is done */\n\t\tis_alive(__func__, \"old request running\");\n\t\treturn;\n\t}\n\tcommand_status = FD_COMMAND_NONE;\n\t__reschedule_timeout(MAXTIMEOUT, \"fd_request\");\n\tset_fdc(0);\n\tprocess_fd_request();\n\tis_alive(__func__, \"\");\n}", "static const struct cont_t poll_cont = {\n\t.interrupt\t= success_and_wakeup,\n\t.redo\t\t= floppy_ready,\n\t.error\t\t= generic_failure,\n\t.done\t\t= generic_done\n};", "static int poll_drive(bool interruptible, int flag)\n{\n\t/* no auto-sense, just clear dcl */\n\traw_cmd = &default_raw_cmd;\n\traw_cmd->flags = flag;\n\traw_cmd->track = 0;\n\traw_cmd->cmd_count = 0;\n\tcont = &poll_cont;\n\tdebug_dcl(DP->flags, \"setting NEWCHANGE in poll_drive\\n\");\n\tset_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);", "\treturn wait_til_done(floppy_ready, interruptible);\n}", "/*\n * User triggered reset\n * ====================\n */", "static void reset_intr(void)\n{\n\tpr_info(\"weird, reset interrupt called\\n\");\n}", "static const struct cont_t reset_cont = {\n\t.interrupt\t= reset_intr,\n\t.redo\t\t= success_and_wakeup,\n\t.error\t\t= generic_failure,\n\t.done\t\t= generic_done\n};", "static int user_reset_fdc(int drive, int arg, bool interruptible)\n{\n\tint ret;", "\tif (lock_fdc(drive, interruptible))\n\t\treturn -EINTR;", "\tif (arg == FD_RESET_ALWAYS)\n\t\tFDCS->reset = 1;\n\tif (FDCS->reset) {\n\t\tcont = &reset_cont;\n\t\tret = wait_til_done(reset_fdc, interruptible);\n\t\tif (ret == -EINTR)\n\t\t\treturn -EINTR;\n\t}\n\tprocess_fd_request();\n\treturn 0;\n}", "/*\n * Misc Ioctl's and support\n * ========================\n */\nstatic inline int fd_copyout(void __user *param, const void *address,\n\t\t\t unsigned long size)\n{\n\treturn copy_to_user(param, address, size) ? -EFAULT : 0;\n}", "static inline int fd_copyin(void __user *param, void *address,\n\t\t\t unsigned long size)\n{\n\treturn copy_from_user(address, param, size) ? -EFAULT : 0;\n}", "static const char *drive_name(int type, int drive)\n{\n\tstruct floppy_struct *floppy;", "\tif (type)\n\t\tfloppy = floppy_type + type;\n\telse {\n\t\tif (UDP->native_format)\n\t\t\tfloppy = floppy_type + UDP->native_format;\n\t\telse\n\t\t\treturn \"(null)\";\n\t}\n\tif (floppy->name)\n\t\treturn floppy->name;\n\telse\n\t\treturn \"(null)\";\n}", "/* raw commands */\nstatic void raw_cmd_done(int flag)\n{\n\tint i;", "\tif (!flag) {\n\t\traw_cmd->flags |= FD_RAW_FAILURE;\n\t\traw_cmd->flags |= FD_RAW_HARDFAILURE;\n\t} else {\n\t\traw_cmd->reply_count = inr;\n\t\tif (raw_cmd->reply_count > MAX_REPLIES)\n\t\t\traw_cmd->reply_count = 0;\n\t\tfor (i = 0; i < raw_cmd->reply_count; i++)\n\t\t\traw_cmd->reply[i] = reply_buffer[i];", "\t\tif (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) {\n\t\t\tunsigned long flags;\n\t\t\tflags = claim_dma_lock();\n\t\t\traw_cmd->length = fd_get_dma_residue();\n\t\t\trelease_dma_lock(flags);\n\t\t}", "\t\tif ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&\n\t\t (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))\n\t\t\traw_cmd->flags |= FD_RAW_FAILURE;", "\t\tif (disk_change(current_drive))\n\t\t\traw_cmd->flags |= FD_RAW_DISK_CHANGE;\n\t\telse\n\t\t\traw_cmd->flags &= ~FD_RAW_DISK_CHANGE;\n\t\tif (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)\n\t\t\tmotor_off_callback(current_drive);", "\t\tif (raw_cmd->next &&\n\t\t (!(raw_cmd->flags & FD_RAW_FAILURE) ||\n\t\t !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&\n\t\t ((raw_cmd->flags & FD_RAW_FAILURE) ||\n\t\t !(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) {\n\t\t\traw_cmd = raw_cmd->next;\n\t\t\treturn;\n\t\t}\n\t}\n\tgeneric_done(flag);\n}", "static const struct cont_t raw_cmd_cont = {\n\t.interrupt\t= success_and_wakeup,\n\t.redo\t\t= floppy_start,\n\t.error\t\t= generic_failure,\n\t.done\t\t= raw_cmd_done\n};", "static int raw_cmd_copyout(int cmd, void __user *param,\n\t\t\t\t struct floppy_raw_cmd *ptr)\n{\n\tint ret;", "\twhile (ptr) {", "\t\tstruct floppy_raw_cmd cmd = *ptr;\n\t\tcmd.next = NULL;\n\t\tcmd.kernel_data = NULL;\n\t\tret = copy_to_user(param, &cmd, sizeof(cmd));", "\t\tif (ret)\n\t\t\treturn -EFAULT;\n\t\tparam += sizeof(struct floppy_raw_cmd);\n\t\tif ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {\n\t\t\tif (ptr->length >= 0 &&\n\t\t\t ptr->length <= ptr->buffer_length) {\n\t\t\t\tlong length = ptr->buffer_length - ptr->length;\n\t\t\t\tret = fd_copyout(ptr->data, ptr->kernel_data,\n\t\t\t\t\t\t length);\n\t\t\t\tif (ret)\n\t\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\t\tptr = ptr->next;\n\t}", "\treturn 0;\n}", "static void raw_cmd_free(struct floppy_raw_cmd **ptr)\n{\n\tstruct floppy_raw_cmd *next;\n\tstruct floppy_raw_cmd *this;", "\tthis = *ptr;\n\t*ptr = NULL;\n\twhile (this) {\n\t\tif (this->buffer_length) {\n\t\t\tfd_dma_mem_free((unsigned long)this->kernel_data,\n\t\t\t\t\tthis->buffer_length);\n\t\t\tthis->buffer_length = 0;\n\t\t}\n\t\tnext = this->next;\n\t\tkfree(this);\n\t\tthis = next;\n\t}\n}", "static int raw_cmd_copyin(int cmd, void __user *param,\n\t\t\t\t struct floppy_raw_cmd **rcmd)\n{\n\tstruct floppy_raw_cmd *ptr;\n\tint ret;\n\tint i;", "\t*rcmd = NULL;", "loop:\n\tptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);\n\tif (!ptr)\n\t\treturn -ENOMEM;\n\t*rcmd = ptr;\n\tret = copy_from_user(ptr, param, sizeof(*ptr));\n\tptr->next = NULL;\n\tptr->buffer_length = 0;\n\tptr->kernel_data = NULL;\n\tif (ret)\n\t\treturn -EFAULT;\n\tparam += sizeof(struct floppy_raw_cmd);\n\tif (ptr->cmd_count > 33)\n\t\t\t/* the command may now also take up the space\n\t\t\t * initially intended for the reply & the\n\t\t\t * reply count. Needed for long 82078 commands\n\t\t\t * such as RESTORE, which takes ... 17 command\n\t\t\t * bytes. Murphy's law #137: When you reserve\n\t\t\t * 16 bytes for a structure, you'll one day\n\t\t\t * discover that you really need 17...\n\t\t\t */\n\t\treturn -EINVAL;", "\tfor (i = 0; i < 16; i++)\n\t\tptr->reply[i] = 0;\n\tptr->resultcode = 0;", "\tif (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {\n\t\tif (ptr->length <= 0)\n\t\t\treturn -EINVAL;\n\t\tptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);\n\t\tfallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);\n\t\tif (!ptr->kernel_data)\n\t\t\treturn -ENOMEM;\n\t\tptr->buffer_length = ptr->length;\n\t}\n\tif (ptr->flags & FD_RAW_WRITE) {\n\t\tret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\tif (ptr->flags & FD_RAW_MORE) {\n\t\trcmd = &(ptr->next);\n\t\tptr->rate &= 0x43;\n\t\tgoto loop;\n\t}", "\treturn 0;\n}", "static int raw_cmd_ioctl(int cmd, void __user *param)\n{\n\tstruct floppy_raw_cmd *my_raw_cmd;\n\tint drive;\n\tint ret2;\n\tint ret;", "\tif (FDCS->rawcmd <= 1)\n\t\tFDCS->rawcmd = 1;\n\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tif (FDC(drive) != fdc)\n\t\t\tcontinue;\n\t\tif (drive == current_drive) {\n\t\t\tif (UDRS->fd_ref > 1) {\n\t\t\t\tFDCS->rawcmd = 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else if (UDRS->fd_ref) {\n\t\t\tFDCS->rawcmd = 2;\n\t\t\tbreak;\n\t\t}\n\t}", "\tif (FDCS->reset)\n\t\treturn -EIO;", "\tret = raw_cmd_copyin(cmd, param, &my_raw_cmd);\n\tif (ret) {\n\t\traw_cmd_free(&my_raw_cmd);\n\t\treturn ret;\n\t}", "\traw_cmd = my_raw_cmd;\n\tcont = &raw_cmd_cont;\n\tret = wait_til_done(floppy_start, true);\n\tdebug_dcl(DP->flags, \"calling disk change from raw_cmd ioctl\\n\");", "\tif (ret != -EINTR && FDCS->reset)\n\t\tret = -EIO;", "\tDRS->track = NO_TRACK;", "\tret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);\n\tif (!ret)\n\t\tret = ret2;\n\traw_cmd_free(&my_raw_cmd);\n\treturn ret;\n}", "static int invalidate_drive(struct block_device *bdev)\n{\n\t/* invalidate the buffer track to force a reread */\n\tset_bit((long)bdev->bd_disk->private_data, &fake_change);\n\tprocess_fd_request();\n\tcheck_disk_change(bdev);\n\treturn 0;\n}", "static int set_geometry(unsigned int cmd, struct floppy_struct *g,\n\t\t\t int drive, int type, struct block_device *bdev)\n{\n\tint cnt;", "\t/* sanity checking for parameters. */\n\tif (g->sect <= 0 ||\n\t g->head <= 0 ||\n\t g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||\n\t /* check if reserved bits are set */\n\t (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)\n\t\treturn -EINVAL;\n\tif (type) {\n\t\tif (!capable(CAP_SYS_ADMIN))\n\t\t\treturn -EPERM;\n\t\tmutex_lock(&open_lock);\n\t\tif (lock_fdc(drive, true)) {\n\t\t\tmutex_unlock(&open_lock);\n\t\t\treturn -EINTR;\n\t\t}\n\t\tfloppy_type[type] = *g;\n\t\tfloppy_type[type].name = \"user format\";\n\t\tfor (cnt = type << 2; cnt < (type << 2) + 4; cnt++)\n\t\t\tfloppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =\n\t\t\t floppy_type[type].size + 1;\n\t\tprocess_fd_request();\n\t\tfor (cnt = 0; cnt < N_DRIVE; cnt++) {\n\t\t\tstruct block_device *bdev = opened_bdev[cnt];\n\t\t\tif (!bdev || ITYPE(drive_state[cnt].fd_device) != type)\n\t\t\t\tcontinue;\n\t\t\t__invalidate_device(bdev, true);\n\t\t}\n\t\tmutex_unlock(&open_lock);\n\t} else {\n\t\tint oldStretch;", "\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tif (cmd != FDDEFPRM) {\n\t\t\t/* notice a disk change immediately, else\n\t\t\t * we lose our settings immediately*/\n\t\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\t\treturn -EINTR;\n\t\t}\n\t\toldStretch = g->stretch;\n\t\tuser_params[drive] = *g;\n\t\tif (buffer_drive == drive)\n\t\t\tSUPBOUND(buffer_max, user_params[drive].sect);\n\t\tcurrent_type[drive] = &user_params[drive];\n\t\tfloppy_sizes[drive] = user_params[drive].size;\n\t\tif (cmd == FDDEFPRM)\n\t\t\tDRS->keep_data = -1;\n\t\telse\n\t\t\tDRS->keep_data = 1;\n\t\t/* invalidation. Invalidate only when needed, i.e.\n\t\t * when there are already sectors in the buffer cache\n\t\t * whose number will change. This is useful, because\n\t\t * mtools often changes the geometry of the disk after\n\t\t * looking at the boot block */\n\t\tif (DRS->maxblock > user_params[drive].sect ||\n\t\t DRS->maxtrack ||\n\t\t ((user_params[drive].sect ^ oldStretch) &\n\t\t (FD_SWAPSIDES | FD_SECTBASEMASK)))\n\t\t\tinvalidate_drive(bdev);\n\t\telse\n\t\t\tprocess_fd_request();\n\t}\n\treturn 0;\n}", "/* handle obsolete ioctl's */\nstatic unsigned int ioctl_table[] = {\n\tFDCLRPRM,\n\tFDSETPRM,\n\tFDDEFPRM,\n\tFDGETPRM,\n\tFDMSGON,\n\tFDMSGOFF,\n\tFDFMTBEG,\n\tFDFMTTRK,\n\tFDFMTEND,\n\tFDSETEMSGTRESH,\n\tFDFLUSH,\n\tFDSETMAXERRS,\n\tFDGETMAXERRS,\n\tFDGETDRVTYP,\n\tFDSETDRVPRM,\n\tFDGETDRVPRM,\n\tFDGETDRVSTAT,\n\tFDPOLLDRVSTAT,\n\tFDRESET,\n\tFDGETFDCSTAT,\n\tFDWERRORCLR,\n\tFDWERRORGET,\n\tFDRAWCMD,\n\tFDEJECT,\n\tFDTWADDLE\n};", "static int normalize_ioctl(unsigned int *cmd, int *size)\n{\n\tint i;", "\tfor (i = 0; i < ARRAY_SIZE(ioctl_table); i++) {\n\t\tif ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) {\n\t\t\t*size = _IOC_SIZE(*cmd);\n\t\t\t*cmd = ioctl_table[i];\n\t\t\tif (*size > _IOC_SIZE(*cmd)) {\n\t\t\t\tpr_info(\"ioctl not yet supported\\n\");\n\t\t\t\treturn -EFAULT;\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\t}\n\treturn -EINVAL;\n}", "static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)\n{\n\tif (type)\n\t\t*g = &floppy_type[type];\n\telse {\n\t\tif (lock_fdc(drive, false))\n\t\t\treturn -EINTR;\n\t\tif (poll_drive(false, 0) == -EINTR)\n\t\t\treturn -EINTR;\n\t\tprocess_fd_request();\n\t\t*g = current_type[drive];\n\t}\n\tif (!*g)\n\t\treturn -ENODEV;\n\treturn 0;\n}", "static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo)\n{\n\tint drive = (long)bdev->bd_disk->private_data;\n\tint type = ITYPE(drive_state[drive].fd_device);\n\tstruct floppy_struct *g;\n\tint ret;", "\tret = get_floppy_geometry(drive, type, &g);\n\tif (ret)\n\t\treturn ret;", "\tgeo->heads = g->head;\n\tgeo->sectors = g->sect;\n\tgeo->cylinders = g->track;\n\treturn 0;\n}", "static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,\n\t\t unsigned long param)\n{\n\tint drive = (long)bdev->bd_disk->private_data;\n\tint type = ITYPE(UDRS->fd_device);\n\tint i;\n\tint ret;\n\tint size;\n\tunion inparam {\n\t\tstruct floppy_struct g;\t/* geometry */\n\t\tstruct format_descr f;\n\t\tstruct floppy_max_errors max_errors;\n\t\tstruct floppy_drive_params dp;\n\t} inparam;\t\t/* parameters coming from user space */\n\tconst void *outparam;\t/* parameters passed back to user space */", "\t/* convert compatibility eject ioctls into floppy eject ioctl.\n\t * We do this in order to provide a means to eject floppy disks before\n\t * installing the new fdutils package */\n\tif (cmd == CDROMEJECT ||\t/* CD-ROM eject */\n\t cmd == 0x6470) {\t\t/* SunOS floppy eject */\n\t\tDPRINT(\"obsolete eject ioctl\\n\");\n\t\tDPRINT(\"please use floppycontrol --eject\\n\");\n\t\tcmd = FDEJECT;\n\t}", "\tif (!((cmd & 0xff00) == 0x0200))\n\t\treturn -EINVAL;", "\t/* convert the old style command into a new style command */\n\tret = normalize_ioctl(&cmd, &size);\n\tif (ret)\n\t\treturn ret;", "\t/* permission checks */\n\tif (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) ||\n\t ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))\n\t\treturn -EPERM;", "\tif (WARN_ON(size < 0 || size > sizeof(inparam)))\n\t\treturn -EINVAL;", "\t/* copyin */\n\tmemset(&inparam, 0, sizeof(inparam));\n\tif (_IOC_DIR(cmd) & _IOC_WRITE) {\n\t\tret = fd_copyin((void __user *)param, &inparam, size);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}", "\tswitch (cmd) {\n\tcase FDEJECT:\n\t\tif (UDRS->fd_ref != 1)\n\t\t\t/* somebody else has this drive open */\n\t\t\treturn -EBUSY;\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;", "\t\t/* do the actual eject. Fails on\n\t\t * non-Sparc architectures */\n\t\tret = fd_eject(UNIT(drive));", "\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t\tprocess_fd_request();\n\t\treturn ret;\n\tcase FDCLRPRM:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tcurrent_type[drive] = NULL;\n\t\tfloppy_sizes[drive] = MAX_DISK_SIZE << 1;\n\t\tUDRS->keep_data = 0;\n\t\treturn invalidate_drive(bdev);\n\tcase FDSETPRM:\n\tcase FDDEFPRM:\n\t\treturn set_geometry(cmd, &inparam.g, drive, type, bdev);\n\tcase FDGETPRM:\n\t\tret = get_floppy_geometry(drive, type,\n\t\t\t\t\t (struct floppy_struct **)&outparam);\n\t\tif (ret)\n\t\t\treturn ret;\n\t\tbreak;\n\tcase FDMSGON:\n\t\tUDP->flags |= FTD_MSG;\n\t\treturn 0;\n\tcase FDMSGOFF:\n\t\tUDP->flags &= ~FTD_MSG;\n\t\treturn 0;\n\tcase FDFMTBEG:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\treturn -EINTR;\n\t\tret = UDRS->flags;\n\t\tprocess_fd_request();\n\t\tif (ret & FD_VERIFY)\n\t\t\treturn -ENODEV;\n\t\tif (!(ret & FD_DISK_WRITABLE))\n\t\t\treturn -EROFS;\n\t\treturn 0;\n\tcase FDFMTTRK:\n\t\tif (UDRS->fd_ref != 1)\n\t\t\treturn -EBUSY;\n\t\treturn do_format(drive, &inparam.f);\n\tcase FDFMTEND:\n\tcase FDFLUSH:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\treturn invalidate_drive(bdev);\n\tcase FDSETEMSGTRESH:\n\t\tUDP->max_errors.reporting = (unsigned short)(param & 0x0f);\n\t\treturn 0;\n\tcase FDGETMAXERRS:\n\t\toutparam = &UDP->max_errors;\n\t\tbreak;\n\tcase FDSETMAXERRS:\n\t\tUDP->max_errors = inparam.max_errors;\n\t\tbreak;\n\tcase FDGETDRVTYP:\n\t\toutparam = drive_name(type, drive);\n\t\tSUPBOUND(size, strlen((const char *)outparam) + 1);\n\t\tbreak;\n\tcase FDSETDRVPRM:\n\t\t*UDP = inparam.dp;\n\t\tbreak;\n\tcase FDGETDRVPRM:\n\t\toutparam = UDP;\n\t\tbreak;\n\tcase FDPOLLDRVSTAT:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tif (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)\n\t\t\treturn -EINTR;\n\t\tprocess_fd_request();\n\t\t/* fall through */\n\tcase FDGETDRVSTAT:\n\t\toutparam = UDRS;\n\t\tbreak;\n\tcase FDRESET:\n\t\treturn user_reset_fdc(drive, (int)param, true);\n\tcase FDGETFDCSTAT:\n\t\toutparam = UFDCS;\n\t\tbreak;\n\tcase FDWERRORCLR:\n\t\tmemset(UDRWE, 0, sizeof(*UDRWE));\n\t\treturn 0;\n\tcase FDWERRORGET:\n\t\toutparam = UDRWE;\n\t\tbreak;\n\tcase FDRAWCMD:\n\t\tif (type)\n\t\t\treturn -EINVAL;\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\tset_floppy(drive);\n\t\ti = raw_cmd_ioctl(cmd, (void __user *)param);\n\t\tif (i == -EINTR)\n\t\t\treturn -EINTR;\n\t\tprocess_fd_request();\n\t\treturn i;\n\tcase FDTWADDLE:\n\t\tif (lock_fdc(drive, true))\n\t\t\treturn -EINTR;\n\t\ttwaddle();\n\t\tprocess_fd_request();\n\t\treturn 0;\n\tdefault:\n\t\treturn -EINVAL;\n\t}", "\tif (_IOC_DIR(cmd) & _IOC_READ)\n\t\treturn fd_copyout((void __user *)param, outparam, size);", "\treturn 0;\n}", "static int fd_ioctl(struct block_device *bdev, fmode_t mode,\n\t\t\t unsigned int cmd, unsigned long param)\n{\n\tint ret;", "\tmutex_lock(&floppy_mutex);\n\tret = fd_locked_ioctl(bdev, mode, cmd, param);\n\tmutex_unlock(&floppy_mutex);", "\treturn ret;\n}", "static void __init config_types(void)\n{\n\tbool has_drive = false;\n\tint drive;", "\t/* read drive info out of physical CMOS */\n\tdrive = 0;\n\tif (!UDP->cmos)\n\t\tUDP->cmos = FLOPPY0_TYPE;\n\tdrive = 1;\n\tif (!UDP->cmos && FLOPPY1_TYPE)\n\t\tUDP->cmos = FLOPPY1_TYPE;", "\t/* FIXME: additional physical CMOS drive detection should go here */", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tunsigned int type = UDP->cmos;\n\t\tstruct floppy_drive_params *params;\n\t\tconst char *name = NULL;\n\t\tstatic char temparea[32];", "\t\tif (type < ARRAY_SIZE(default_drive_params)) {\n\t\t\tparams = &default_drive_params[type].params;\n\t\t\tif (type) {\n\t\t\t\tname = default_drive_params[type].name;\n\t\t\t\tallowed_drive_mask |= 1 << drive;\n\t\t\t} else\n\t\t\t\tallowed_drive_mask &= ~(1 << drive);\n\t\t} else {\n\t\t\tparams = &default_drive_params[0].params;\n\t\t\tsprintf(temparea, \"unknown type %d (usb?)\", type);\n\t\t\tname = temparea;\n\t\t}\n\t\tif (name) {\n\t\t\tconst char *prepend;\n\t\t\tif (!has_drive) {\n\t\t\t\tprepend = \"\";\n\t\t\t\thas_drive = true;\n\t\t\t\tpr_info(\"Floppy drive(s):\");\n\t\t\t} else {\n\t\t\t\tprepend = \",\";\n\t\t\t}", "\t\t\tpr_cont(\"%s fd%d is %s\", prepend, drive, name);\n\t\t}\n\t\t*UDP = *params;\n\t}", "\tif (has_drive)\n\t\tpr_cont(\"\\n\");\n}", "static void floppy_release(struct gendisk *disk, fmode_t mode)\n{\n\tint drive = (long)disk->private_data;", "\tmutex_lock(&floppy_mutex);\n\tmutex_lock(&open_lock);\n\tif (!UDRS->fd_ref--) {\n\t\tDPRINT(\"floppy_release with fd_ref == 0\");\n\t\tUDRS->fd_ref = 0;\n\t}\n\tif (!UDRS->fd_ref)\n\t\topened_bdev[drive] = NULL;\n\tmutex_unlock(&open_lock);\n\tmutex_unlock(&floppy_mutex);\n}", "/*\n * floppy_open check for aliasing (/dev/fd0 can be the same as\n * /dev/PS0 etc), and disallows simultaneous access to the same\n * drive with different device numbers.\n */\nstatic int floppy_open(struct block_device *bdev, fmode_t mode)\n{\n\tint drive = (long)bdev->bd_disk->private_data;\n\tint old_dev, new_dev;\n\tint try;\n\tint res = -EBUSY;\n\tchar *tmp;", "\tmutex_lock(&floppy_mutex);\n\tmutex_lock(&open_lock);\n\told_dev = UDRS->fd_device;\n\tif (opened_bdev[drive] && opened_bdev[drive] != bdev)\n\t\tgoto out2;", "\tif (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) {\n\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t}", "\tUDRS->fd_ref++;", "\topened_bdev[drive] = bdev;", "\tres = -ENXIO;", "\tif (!floppy_track_buffer) {\n\t\t/* if opening an ED drive, reserve a big buffer,\n\t\t * else reserve a small one */\n\t\tif ((UDP->cmos == 6) || (UDP->cmos == 5))\n\t\t\ttry = 64;\t/* Only 48 actually useful */\n\t\telse\n\t\t\ttry = 32;\t/* Only 24 actually useful */", "\t\ttmp = (char *)fd_dma_mem_alloc(1024 * try);\n\t\tif (!tmp && !floppy_track_buffer) {\n\t\t\ttry >>= 1;\t/* buffer only one side */\n\t\t\tINFBOUND(try, 16);\n\t\t\ttmp = (char *)fd_dma_mem_alloc(1024 * try);\n\t\t}\n\t\tif (!tmp && !floppy_track_buffer)\n\t\t\tfallback_on_nodma_alloc(&tmp, 2048 * try);\n\t\tif (!tmp && !floppy_track_buffer) {\n\t\t\tDPRINT(\"Unable to allocate DMA memory\\n\");\n\t\t\tgoto out;\n\t\t}\n\t\tif (floppy_track_buffer) {\n\t\t\tif (tmp)\n\t\t\t\tfd_dma_mem_free((unsigned long)tmp, try * 1024);\n\t\t} else {\n\t\t\tbuffer_min = buffer_max = -1;\n\t\t\tfloppy_track_buffer = tmp;\n\t\t\tmax_buffer_sectors = try;\n\t\t}\n\t}", "\tnew_dev = MINOR(bdev->bd_dev);\n\tUDRS->fd_device = new_dev;\n\tset_capacity(disks[drive], floppy_sizes[new_dev]);\n\tif (old_dev != -1 && old_dev != new_dev) {\n\t\tif (buffer_drive == drive)\n\t\t\tbuffer_track = -1;\n\t}", "\tif (UFDCS->rawcmd == 1)\n\t\tUFDCS->rawcmd = 2;", "\tif (!(mode & FMODE_NDELAY)) {\n\t\tif (mode & (FMODE_READ|FMODE_WRITE)) {\n\t\t\tUDRS->last_checked = 0;\n\t\t\tclear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);\n\t\t\tcheck_disk_change(bdev);\n\t\t\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags))\n\t\t\t\tgoto out;\n\t\t\tif (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags))\n\t\t\t\tgoto out;\n\t\t}\n\t\tres = -EROFS;\n\t\tif ((mode & FMODE_WRITE) &&\n\t\t !test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags))\n\t\t\tgoto out;\n\t}\n\tmutex_unlock(&open_lock);\n\tmutex_unlock(&floppy_mutex);\n\treturn 0;\nout:\n\tUDRS->fd_ref--;", "\tif (!UDRS->fd_ref)\n\t\topened_bdev[drive] = NULL;\nout2:\n\tmutex_unlock(&open_lock);\n\tmutex_unlock(&floppy_mutex);\n\treturn res;\n}", "/*\n * Check if the disk has been changed or if a change has been faked.\n */\nstatic unsigned int floppy_check_events(struct gendisk *disk,\n\t\t\t\t\tunsigned int clearing)\n{\n\tint drive = (long)disk->private_data;", "\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t test_bit(FD_VERIFY_BIT, &UDRS->flags))\n\t\treturn DISK_EVENT_MEDIA_CHANGE;", "\tif (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) {\n\t\tlock_fdc(drive, false);\n\t\tpoll_drive(false, 0);\n\t\tprocess_fd_request();\n\t}", "\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t test_bit(FD_VERIFY_BIT, &UDRS->flags) ||\n\t test_bit(drive, &fake_change) ||\n\t drive_no_geom(drive))\n\t\treturn DISK_EVENT_MEDIA_CHANGE;\n\treturn 0;\n}", "/*\n * This implements \"read block 0\" for floppy_revalidate().\n * Needed for format autodetection, checking whether there is\n * a disk in the drive, and whether that disk is writable.\n */", "struct rb0_cbdata {\n\tint drive;\n\tstruct completion complete;\n};", "static void floppy_rb0_cb(struct bio *bio, int err)\n{\n\tstruct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private;\n\tint drive = cbdata->drive;", "\tif (err) {\n\t\tpr_info(\"floppy: error %d while reading block 0\", err);\n\t\tset_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);\n\t}\n\tcomplete(&cbdata->complete);\n}", "static int __floppy_read_block_0(struct block_device *bdev, int drive)\n{\n\tstruct bio bio;\n\tstruct bio_vec bio_vec;\n\tstruct page *page;\n\tstruct rb0_cbdata cbdata;\n\tsize_t size;", "\tpage = alloc_page(GFP_NOIO);\n\tif (!page) {\n\t\tprocess_fd_request();\n\t\treturn -ENOMEM;\n\t}", "\tsize = bdev->bd_block_size;\n\tif (!size)\n\t\tsize = 1024;", "\tcbdata.drive = drive;", "\tbio_init(&bio);\n\tbio.bi_io_vec = &bio_vec;\n\tbio_vec.bv_page = page;\n\tbio_vec.bv_len = size;\n\tbio_vec.bv_offset = 0;\n\tbio.bi_vcnt = 1;\n\tbio.bi_iter.bi_size = size;\n\tbio.bi_bdev = bdev;\n\tbio.bi_iter.bi_sector = 0;\n\tbio.bi_flags = (1 << BIO_QUIET);\n\tbio.bi_private = &cbdata;\n\tbio.bi_end_io = floppy_rb0_cb;", "\tsubmit_bio(READ, &bio);\n\tprocess_fd_request();", "\tinit_completion(&cbdata.complete);\n\twait_for_completion(&cbdata.complete);", "\t__free_page(page);", "\treturn 0;\n}", "/* revalidate the floppy disk, i.e. trigger format autodetection by reading\n * the bootblock (block 0). \"Autodetection\" is also needed to check whether\n * there is a disk in the drive at all... Thus we also do it for fixed\n * geometry formats */\nstatic int floppy_revalidate(struct gendisk *disk)\n{\n\tint drive = (long)disk->private_data;\n\tint cf;\n\tint res = 0;", "\tif (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t test_bit(FD_VERIFY_BIT, &UDRS->flags) ||\n\t test_bit(drive, &fake_change) ||\n\t drive_no_geom(drive)) {\n\t\tif (WARN(atomic_read(&usage_count) == 0,\n\t\t\t \"VFS: revalidate called on non-open device.\\n\"))\n\t\t\treturn -EFAULT;", "\t\tlock_fdc(drive, false);\n\t\tcf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||\n\t\t test_bit(FD_VERIFY_BIT, &UDRS->flags));\n\t\tif (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) {\n\t\t\tprocess_fd_request();\t/*already done by another thread */\n\t\t\treturn 0;\n\t\t}\n\t\tUDRS->maxblock = 0;\n\t\tUDRS->maxtrack = 0;\n\t\tif (buffer_drive == drive)\n\t\t\tbuffer_track = -1;\n\t\tclear_bit(drive, &fake_change);\n\t\tclear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tif (cf)\n\t\t\tUDRS->generation++;\n\t\tif (drive_no_geom(drive)) {\n\t\t\t/* auto-sensing */\n\t\t\tres = __floppy_read_block_0(opened_bdev[drive], drive);\n\t\t} else {\n\t\t\tif (cf)\n\t\t\t\tpoll_drive(false, FD_RAW_NEED_DISK);\n\t\t\tprocess_fd_request();\n\t\t}\n\t}\n\tset_capacity(disk, floppy_sizes[UDRS->fd_device]);\n\treturn res;\n}", "static const struct block_device_operations floppy_fops = {\n\t.owner\t\t\t= THIS_MODULE,\n\t.open\t\t\t= floppy_open,\n\t.release\t\t= floppy_release,\n\t.ioctl\t\t\t= fd_ioctl,\n\t.getgeo\t\t\t= fd_getgeo,\n\t.check_events\t\t= floppy_check_events,\n\t.revalidate_disk\t= floppy_revalidate,\n};", "/*\n * Floppy Driver initialization\n * =============================\n */", "/* Determine the floppy disk controller type */\n/* This routine was written by David C. Niemi */\nstatic char __init get_fdc_version(void)\n{\n\tint r;", "\toutput_byte(FD_DUMPREGS);\t/* 82072 and better know DUMPREGS */\n\tif (FDCS->reset)\n\t\treturn FDC_NONE;\n\tr = result();\n\tif (r <= 0x00)\n\t\treturn FDC_NONE;\t/* No FDC present ??? */\n\tif ((r == 1) && (reply_buffer[0] == 0x80)) {\n\t\tpr_info(\"FDC %d is an 8272A\\n\", fdc);\n\t\treturn FDC_8272A;\t/* 8272a/765 don't know DUMPREGS */\n\t}\n\tif (r != 10) {\n\t\tpr_info(\"FDC %d init: DUMPREGS: unexpected return of %d bytes.\\n\",\n\t\t\tfdc, r);\n\t\treturn FDC_UNKNOWN;\n\t}", "\tif (!fdc_configure()) {\n\t\tpr_info(\"FDC %d is an 82072\\n\", fdc);\n\t\treturn FDC_82072;\t/* 82072 doesn't know CONFIGURE */\n\t}", "\toutput_byte(FD_PERPENDICULAR);\n\tif (need_more_output() == MORE_OUTPUT) {\n\t\toutput_byte(0);\n\t} else {\n\t\tpr_info(\"FDC %d is an 82072A\\n\", fdc);\n\t\treturn FDC_82072A;\t/* 82072A as found on Sparcs. */\n\t}", "\toutput_byte(FD_UNLOCK);\n\tr = result();\n\tif ((r == 1) && (reply_buffer[0] == 0x80)) {\n\t\tpr_info(\"FDC %d is a pre-1991 82077\\n\", fdc);\n\t\treturn FDC_82077_ORIG;\t/* Pre-1991 82077, doesn't know\n\t\t\t\t\t * LOCK/UNLOCK */\n\t}\n\tif ((r != 1) || (reply_buffer[0] != 0x00)) {\n\t\tpr_info(\"FDC %d init: UNLOCK: unexpected return of %d bytes.\\n\",\n\t\t\tfdc, r);\n\t\treturn FDC_UNKNOWN;\n\t}\n\toutput_byte(FD_PARTID);\n\tr = result();\n\tif (r != 1) {\n\t\tpr_info(\"FDC %d init: PARTID: unexpected return of %d bytes.\\n\",\n\t\t\tfdc, r);\n\t\treturn FDC_UNKNOWN;\n\t}\n\tif (reply_buffer[0] == 0x80) {\n\t\tpr_info(\"FDC %d is a post-1991 82077\\n\", fdc);\n\t\treturn FDC_82077;\t/* Revised 82077AA passes all the tests */\n\t}\n\tswitch (reply_buffer[0] >> 5) {\n\tcase 0x0:\n\t\t/* Either a 82078-1 or a 82078SL running at 5Volt */\n\t\tpr_info(\"FDC %d is an 82078.\\n\", fdc);\n\t\treturn FDC_82078;\n\tcase 0x1:\n\t\tpr_info(\"FDC %d is a 44pin 82078\\n\", fdc);\n\t\treturn FDC_82078;\n\tcase 0x2:\n\t\tpr_info(\"FDC %d is a S82078B\\n\", fdc);\n\t\treturn FDC_S82078B;\n\tcase 0x3:\n\t\tpr_info(\"FDC %d is a National Semiconductor PC87306\\n\", fdc);\n\t\treturn FDC_87306;\n\tdefault:\n\t\tpr_info(\"FDC %d init: 82078 variant with unknown PARTID=%d.\\n\",\n\t\t\tfdc, reply_buffer[0] >> 5);\n\t\treturn FDC_82078_UNKN;\n\t}\n}\t\t\t\t/* get_fdc_version */", "/* lilo configuration */", "static void __init floppy_set_flags(int *ints, int param, int param2)\n{\n\tint i;", "\tfor (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {\n\t\tif (param)\n\t\t\tdefault_drive_params[i].params.flags |= param2;\n\t\telse\n\t\t\tdefault_drive_params[i].params.flags &= ~param2;\n\t}\n\tDPRINT(\"%s flag 0x%x\\n\", param2 ? \"Setting\" : \"Clearing\", param);\n}", "static void __init daring(int *ints, int param, int param2)\n{\n\tint i;", "\tfor (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {\n\t\tif (param) {\n\t\t\tdefault_drive_params[i].params.select_delay = 0;\n\t\t\tdefault_drive_params[i].params.flags |=\n\t\t\t FD_SILENT_DCL_CLEAR;\n\t\t} else {\n\t\t\tdefault_drive_params[i].params.select_delay =\n\t\t\t 2 * HZ / 100;\n\t\t\tdefault_drive_params[i].params.flags &=\n\t\t\t ~FD_SILENT_DCL_CLEAR;\n\t\t}\n\t}\n\tDPRINT(\"Assuming %s floppy hardware\\n\", param ? \"standard\" : \"broken\");\n}", "static void __init set_cmos(int *ints, int dummy, int dummy2)\n{\n\tint current_drive = 0;", "\tif (ints[0] != 2) {\n\t\tDPRINT(\"wrong number of parameters for CMOS\\n\");\n\t\treturn;\n\t}\n\tcurrent_drive = ints[1];\n\tif (current_drive < 0 || current_drive >= 8) {\n\t\tDPRINT(\"bad drive for set_cmos\\n\");\n\t\treturn;\n\t}\n#if N_FDC > 1\n\tif (current_drive >= 4 && !FDC2)\n\t\tFDC2 = 0x370;\n#endif\n\tDP->cmos = ints[2];\n\tDPRINT(\"setting CMOS code to %d\\n\", ints[2]);\n}", "static struct param_table {\n\tconst char *name;\n\tvoid (*fn) (int *ints, int param, int param2);\n\tint *var;\n\tint def_param;\n\tint param2;\n} config_params[] __initdata = {\n\t{\"allowed_drive_mask\", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */\n\t{\"all_drives\", NULL, &allowed_drive_mask, 0xff, 0},\t/* obsolete */\n\t{\"asus_pci\", NULL, &allowed_drive_mask, 0x33, 0},\n\t{\"irq\", NULL, &FLOPPY_IRQ, 6, 0},\n\t{\"dma\", NULL, &FLOPPY_DMA, 2, 0},\n\t{\"daring\", daring, NULL, 1, 0},\n#if N_FDC > 1\n\t{\"two_fdc\", NULL, &FDC2, 0x370, 0},\n\t{\"one_fdc\", NULL, &FDC2, 0, 0},\n#endif\n\t{\"thinkpad\", floppy_set_flags, NULL, 1, FD_INVERTED_DCL},\n\t{\"broken_dcl\", floppy_set_flags, NULL, 1, FD_BROKEN_DCL},\n\t{\"messages\", floppy_set_flags, NULL, 1, FTD_MSG},\n\t{\"silent_dcl_clear\", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR},\n\t{\"debug\", floppy_set_flags, NULL, 1, FD_DEBUG},\n\t{\"nodma\", NULL, &can_use_virtual_dma, 1, 0},\n\t{\"omnibook\", NULL, &can_use_virtual_dma, 1, 0},\n\t{\"yesdma\", NULL, &can_use_virtual_dma, 0, 0},\n\t{\"fifo_depth\", NULL, &fifo_depth, 0xa, 0},\n\t{\"nofifo\", NULL, &no_fifo, 0x20, 0},\n\t{\"usefifo\", NULL, &no_fifo, 0, 0},\n\t{\"cmos\", set_cmos, NULL, 0, 0},\n\t{\"slow\", NULL, &slow_floppy, 1, 0},\n\t{\"unexpected_interrupts\", NULL, &print_unex, 1, 0},\n\t{\"no_unexpected_interrupts\", NULL, &print_unex, 0, 0},\n\t{\"L40SX\", NULL, &print_unex, 0, 0}", "\tEXTRA_FLOPPY_PARAMS\n};", "static int __init floppy_setup(char *str)\n{\n\tint i;\n\tint param;\n\tint ints[11];", "\tstr = get_options(str, ARRAY_SIZE(ints), ints);\n\tif (str) {\n\t\tfor (i = 0; i < ARRAY_SIZE(config_params); i++) {\n\t\t\tif (strcmp(str, config_params[i].name) == 0) {\n\t\t\t\tif (ints[0])\n\t\t\t\t\tparam = ints[1];\n\t\t\t\telse\n\t\t\t\t\tparam = config_params[i].def_param;\n\t\t\t\tif (config_params[i].fn)\n\t\t\t\t\tconfig_params[i].fn(ints, param,\n\t\t\t\t\t\t\t config_params[i].\n\t\t\t\t\t\t\t param2);\n\t\t\t\tif (config_params[i].var) {\n\t\t\t\t\tDPRINT(\"%s=%d\\n\", str, param);\n\t\t\t\t\t*config_params[i].var = param;\n\t\t\t\t}\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\tif (str) {\n\t\tDPRINT(\"unknown floppy option [%s]\\n\", str);", "\t\tDPRINT(\"allowed options are:\");\n\t\tfor (i = 0; i < ARRAY_SIZE(config_params); i++)\n\t\t\tpr_cont(\" %s\", config_params[i].name);\n\t\tpr_cont(\"\\n\");\n\t} else\n\t\tDPRINT(\"botched floppy option\\n\");\n\tDPRINT(\"Read Documentation/blockdev/floppy.txt\\n\");\n\treturn 0;\n}", "static int have_no_fdc = -ENODEV;", "static ssize_t floppy_cmos_show(struct device *dev,\n\t\t\t\tstruct device_attribute *attr, char *buf)\n{\n\tstruct platform_device *p = to_platform_device(dev);\n\tint drive;", "\tdrive = p->id;\n\treturn sprintf(buf, \"%X\\n\", UDP->cmos);\n}", "static DEVICE_ATTR(cmos, S_IRUGO, floppy_cmos_show, NULL);", "static void floppy_device_release(struct device *dev)\n{\n}", "static int floppy_resume(struct device *dev)\n{\n\tint fdc;", "\tfor (fdc = 0; fdc < N_FDC; fdc++)\n\t\tif (FDCS->address != -1)\n\t\t\tuser_reset_fdc(-1, FD_RESET_ALWAYS, false);", "\treturn 0;\n}", "static const struct dev_pm_ops floppy_pm_ops = {\n\t.resume = floppy_resume,\n\t.restore = floppy_resume,\n};", "static struct platform_driver floppy_driver = {\n\t.driver = {\n\t\t .name = \"floppy\",\n\t\t .pm = &floppy_pm_ops,\n\t},\n};", "static struct platform_device floppy_device[N_DRIVE];", "static bool floppy_available(int drive)\n{\n\tif (!(allowed_drive_mask & (1 << drive)))\n\t\treturn false;\n\tif (fdc_state[FDC(drive)].version == FDC_NONE)\n\t\treturn false;\n\treturn true;\n}", "static struct kobject *floppy_find(dev_t dev, int *part, void *data)\n{\n\tint drive = (*part & 3) | ((*part & 0x80) >> 5);\n\tif (drive >= N_DRIVE || !floppy_available(drive))\n\t\treturn NULL;\n\tif (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type))\n\t\treturn NULL;\n\t*part = 0;\n\treturn get_disk(disks[drive]);\n}", "static int __init do_floppy_init(void)\n{\n\tint i, unit, drive, err;", "\tset_debugt();\n\tinterruptjiffies = resultjiffies = jiffies;", "#if defined(CONFIG_PPC)\n\tif (check_legacy_ioport(FDC1))\n\t\treturn -ENODEV;\n#endif", "\traw_cmd = NULL;", "\tfloppy_wq = alloc_ordered_workqueue(\"floppy\", 0);\n\tif (!floppy_wq)\n\t\treturn -ENOMEM;", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tdisks[drive] = alloc_disk(1);\n\t\tif (!disks[drive]) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_put_disk;\n\t\t}", "\t\tdisks[drive]->queue = blk_init_queue(do_fd_request, &floppy_lock);\n\t\tif (!disks[drive]->queue) {\n\t\t\terr = -ENOMEM;\n\t\t\tgoto out_put_disk;\n\t\t}", "\t\tblk_queue_max_hw_sectors(disks[drive]->queue, 64);\n\t\tdisks[drive]->major = FLOPPY_MAJOR;\n\t\tdisks[drive]->first_minor = TOMINOR(drive);\n\t\tdisks[drive]->fops = &floppy_fops;\n\t\tsprintf(disks[drive]->disk_name, \"fd%d\", drive);", "\t\tinit_timer(&motor_off_timer[drive]);\n\t\tmotor_off_timer[drive].data = drive;\n\t\tmotor_off_timer[drive].function = motor_off_callback;\n\t}", "\terr = register_blkdev(FLOPPY_MAJOR, \"fd\");\n\tif (err)\n\t\tgoto out_put_disk;", "\terr = platform_driver_register(&floppy_driver);\n\tif (err)\n\t\tgoto out_unreg_blkdev;", "\tblk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,\n\t\t\t floppy_find, NULL, NULL);", "\tfor (i = 0; i < 256; i++)\n\t\tif (ITYPE(i))\n\t\t\tfloppy_sizes[i] = floppy_type[ITYPE(i)].size;\n\t\telse\n\t\t\tfloppy_sizes[i] = MAX_DISK_SIZE << 1;", "\treschedule_timeout(MAXTIMEOUT, \"floppy init\");\n\tconfig_types();", "\tfor (i = 0; i < N_FDC; i++) {\n\t\tfdc = i;\n\t\tmemset(FDCS, 0, sizeof(*FDCS));\n\t\tFDCS->dtr = -1;\n\t\tFDCS->dor = 0x4;\n#if defined(__sparc__) || defined(__mc68000__)\n\t/*sparcs/sun3x don't have a DOR reset which we can fall back on to */\n#ifdef __mc68000__\n\t\tif (MACH_IS_SUN3X)\n#endif\n\t\t\tFDCS->version = FDC_82072A;\n#endif\n\t}", "\tuse_virtual_dma = can_use_virtual_dma & 1;\n\tfdc_state[0].address = FDC1;\n\tif (fdc_state[0].address == -1) {\n\t\tcancel_delayed_work(&fd_timeout);\n\t\terr = -ENODEV;\n\t\tgoto out_unreg_region;\n\t}\n#if N_FDC > 1\n\tfdc_state[1].address = FDC2;\n#endif", "\tfdc = 0;\t\t/* reset fdc in case of unexpected interrupt */\n\terr = floppy_grab_irq_and_dma();\n\tif (err) {\n\t\tcancel_delayed_work(&fd_timeout);\n\t\terr = -EBUSY;\n\t\tgoto out_unreg_region;\n\t}", "\t/* initialise drive state */\n\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tmemset(UDRS, 0, sizeof(*UDRS));\n\t\tmemset(UDRWE, 0, sizeof(*UDRWE));\n\t\tset_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);\n\t\tset_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);\n\t\tset_bit(FD_VERIFY_BIT, &UDRS->flags);\n\t\tUDRS->fd_device = -1;\n\t\tfloppy_track_buffer = NULL;\n\t\tmax_buffer_sectors = 0;\n\t}\n\t/*\n\t * Small 10 msec delay to let through any interrupt that\n\t * initialization might have triggered, to not\n\t * confuse detection:\n\t */\n\tmsleep(10);", "\tfor (i = 0; i < N_FDC; i++) {\n\t\tfdc = i;\n\t\tFDCS->driver_version = FD_DRIVER_VERSION;\n\t\tfor (unit = 0; unit < 4; unit++)\n\t\t\tFDCS->track[unit] = 0;\n\t\tif (FDCS->address == -1)\n\t\t\tcontinue;\n\t\tFDCS->rawcmd = 2;\n\t\tif (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) {\n\t\t\t/* free ioports reserved by floppy_grab_irq_and_dma() */\n\t\t\tfloppy_release_regions(fdc);\n\t\t\tFDCS->address = -1;\n\t\t\tFDCS->version = FDC_NONE;\n\t\t\tcontinue;\n\t\t}\n\t\t/* Try to determine the floppy controller type */\n\t\tFDCS->version = get_fdc_version();\n\t\tif (FDCS->version == FDC_NONE) {\n\t\t\t/* free ioports reserved by floppy_grab_irq_and_dma() */\n\t\t\tfloppy_release_regions(fdc);\n\t\t\tFDCS->address = -1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)\n\t\t\tcan_use_virtual_dma = 0;", "\t\thave_no_fdc = 0;\n\t\t/* Not all FDCs seem to be able to handle the version command\n\t\t * properly, so force a reset for the standard FDC clones,\n\t\t * to avoid interrupt garbage.\n\t\t */\n\t\tuser_reset_fdc(-1, FD_RESET_ALWAYS, false);\n\t}\n\tfdc = 0;\n\tcancel_delayed_work(&fd_timeout);\n\tcurrent_drive = 0;\n\tinitialized = true;\n\tif (have_no_fdc) {\n\t\tDPRINT(\"no floppy controllers found\\n\");\n\t\terr = have_no_fdc;\n\t\tgoto out_release_dma;\n\t}", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tif (!floppy_available(drive))\n\t\t\tcontinue;", "\t\tfloppy_device[drive].name = floppy_device_name;\n\t\tfloppy_device[drive].id = drive;\n\t\tfloppy_device[drive].dev.release = floppy_device_release;", "\t\terr = platform_device_register(&floppy_device[drive]);\n\t\tif (err)\n\t\t\tgoto out_remove_drives;", "\t\terr = device_create_file(&floppy_device[drive].dev,\n\t\t\t\t\t &dev_attr_cmos);\n\t\tif (err)\n\t\t\tgoto out_unreg_platform_dev;", "\t\t/* to be cleaned up... */\n\t\tdisks[drive]->private_data = (void *)(long)drive;\n\t\tdisks[drive]->flags |= GENHD_FL_REMOVABLE;\n\t\tdisks[drive]->driverfs_dev = &floppy_device[drive].dev;\n\t\tadd_disk(disks[drive]);\n\t}", "\treturn 0;", "out_unreg_platform_dev:\n\tplatform_device_unregister(&floppy_device[drive]);\nout_remove_drives:\n\twhile (drive--) {\n\t\tif (floppy_available(drive)) {\n\t\t\tdel_gendisk(disks[drive]);\n\t\t\tdevice_remove_file(&floppy_device[drive].dev, &dev_attr_cmos);\n\t\t\tplatform_device_unregister(&floppy_device[drive]);\n\t\t}\n\t}\nout_release_dma:\n\tif (atomic_read(&usage_count))\n\t\tfloppy_release_irq_and_dma();\nout_unreg_region:\n\tblk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);\n\tplatform_driver_unregister(&floppy_driver);\nout_unreg_blkdev:\n\tunregister_blkdev(FLOPPY_MAJOR, \"fd\");\nout_put_disk:\n\tdestroy_workqueue(floppy_wq);\n\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tif (!disks[drive])\n\t\t\tbreak;\n\t\tif (disks[drive]->queue) {\n\t\t\tdel_timer_sync(&motor_off_timer[drive]);\n\t\t\tblk_cleanup_queue(disks[drive]->queue);\n\t\t\tdisks[drive]->queue = NULL;\n\t\t}\n\t\tput_disk(disks[drive]);\n\t}\n\treturn err;\n}", "#ifndef MODULE\nstatic __init void floppy_async_init(void *data, async_cookie_t cookie)\n{\n\tdo_floppy_init();\n}\n#endif", "static int __init floppy_init(void)\n{\n#ifdef MODULE\n\treturn do_floppy_init();\n#else\n\t/* Don't hold up the bootup by the floppy initialization */\n\tasync_schedule(floppy_async_init, NULL);\n\treturn 0;\n#endif\n}", "static const struct io_region {\n\tint offset;\n\tint size;\n} io_regions[] = {\n\t{ 2, 1 },\n\t/* address + 3 is sometimes reserved by pnp bios for motherboard */\n\t{ 4, 2 },\n\t/* address + 6 is reserved, and may be taken by IDE.\n\t * Unfortunately, Adaptec doesn't know this :-(, */\n\t{ 7, 1 },\n};", "static void floppy_release_allocated_regions(int fdc, const struct io_region *p)\n{\n\twhile (p != io_regions) {\n\t\tp--;\n\t\trelease_region(FDCS->address + p->offset, p->size);\n\t}\n}", "#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))", "static int floppy_request_regions(int fdc)\n{\n\tconst struct io_region *p;", "\tfor (p = io_regions; p < ARRAY_END(io_regions); p++) {\n\t\tif (!request_region(FDCS->address + p->offset,\n\t\t\t\t p->size, \"floppy\")) {\n\t\t\tDPRINT(\"Floppy io-port 0x%04lx in use\\n\",\n\t\t\t FDCS->address + p->offset);\n\t\t\tfloppy_release_allocated_regions(fdc, p);\n\t\t\treturn -EBUSY;\n\t\t}\n\t}\n\treturn 0;\n}", "static void floppy_release_regions(int fdc)\n{\n\tfloppy_release_allocated_regions(fdc, ARRAY_END(io_regions));\n}", "static int floppy_grab_irq_and_dma(void)\n{\n\tif (atomic_inc_return(&usage_count) > 1)\n\t\treturn 0;", "\t/*\n\t * We might have scheduled a free_irq(), wait it to\n\t * drain first:\n\t */\n\tflush_workqueue(floppy_wq);", "\tif (fd_request_irq()) {\n\t\tDPRINT(\"Unable to grab IRQ%d for the floppy driver\\n\",\n\t\t FLOPPY_IRQ);\n\t\tatomic_dec(&usage_count);\n\t\treturn -1;\n\t}\n\tif (fd_request_dma()) {\n\t\tDPRINT(\"Unable to grab DMA%d for the floppy driver\\n\",\n\t\t FLOPPY_DMA);\n\t\tif (can_use_virtual_dma & 2)\n\t\t\tuse_virtual_dma = can_use_virtual_dma = 1;\n\t\tif (!(can_use_virtual_dma & 1)) {\n\t\t\tfd_free_irq();\n\t\t\tatomic_dec(&usage_count);\n\t\t\treturn -1;\n\t\t}\n\t}", "\tfor (fdc = 0; fdc < N_FDC; fdc++) {\n\t\tif (FDCS->address != -1) {\n\t\t\tif (floppy_request_regions(fdc))\n\t\t\t\tgoto cleanup;\n\t\t}\n\t}\n\tfor (fdc = 0; fdc < N_FDC; fdc++) {\n\t\tif (FDCS->address != -1) {\n\t\t\treset_fdc_info(1);\n\t\t\tfd_outb(FDCS->dor, FD_DOR);\n\t\t}\n\t}\n\tfdc = 0;\n\tset_dor(0, ~0, 8);\t/* avoid immediate interrupt */", "\tfor (fdc = 0; fdc < N_FDC; fdc++)\n\t\tif (FDCS->address != -1)\n\t\t\tfd_outb(FDCS->dor, FD_DOR);\n\t/*\n\t * The driver will try and free resources and relies on us\n\t * to know if they were allocated or not.\n\t */\n\tfdc = 0;\n\tirqdma_allocated = 1;\n\treturn 0;\ncleanup:\n\tfd_free_irq();\n\tfd_free_dma();\n\twhile (--fdc >= 0)\n\t\tfloppy_release_regions(fdc);\n\tatomic_dec(&usage_count);\n\treturn -1;\n}", "static void floppy_release_irq_and_dma(void)\n{\n\tint old_fdc;\n#ifndef __sparc__\n\tint drive;\n#endif\n\tlong tmpsize;\n\tunsigned long tmpaddr;", "\tif (!atomic_dec_and_test(&usage_count))\n\t\treturn;", "\tif (irqdma_allocated) {\n\t\tfd_disable_dma();\n\t\tfd_free_dma();\n\t\tfd_free_irq();\n\t\tirqdma_allocated = 0;\n\t}\n\tset_dor(0, ~0, 8);\n#if N_FDC > 1\n\tset_dor(1, ~8, 0);\n#endif", "\tif (floppy_track_buffer && max_buffer_sectors) {\n\t\ttmpsize = max_buffer_sectors * 1024;\n\t\ttmpaddr = (unsigned long)floppy_track_buffer;\n\t\tfloppy_track_buffer = NULL;\n\t\tmax_buffer_sectors = 0;\n\t\tbuffer_min = buffer_max = -1;\n\t\tfd_dma_mem_free(tmpaddr, tmpsize);\n\t}\n#ifndef __sparc__\n\tfor (drive = 0; drive < N_FDC * 4; drive++)\n\t\tif (timer_pending(motor_off_timer + drive))\n\t\t\tpr_info(\"motor off timer %d still active\\n\", drive);\n#endif", "\tif (delayed_work_pending(&fd_timeout))\n\t\tpr_info(\"floppy timer still active:%s\\n\", timeout_message);\n\tif (delayed_work_pending(&fd_timer))\n\t\tpr_info(\"auxiliary floppy timer still active\\n\");\n\tif (work_pending(&floppy_work))\n\t\tpr_info(\"work still pending\\n\");\n\told_fdc = fdc;\n\tfor (fdc = 0; fdc < N_FDC; fdc++)\n\t\tif (FDCS->address != -1)\n\t\t\tfloppy_release_regions(fdc);\n\tfdc = old_fdc;\n}", "#ifdef MODULE", "static char *floppy;", "static void __init parse_floppy_cfg_string(char *cfg)\n{\n\tchar *ptr;", "\twhile (*cfg) {\n\t\tptr = cfg;\n\t\twhile (*cfg && *cfg != ' ' && *cfg != '\\t')\n\t\t\tcfg++;\n\t\tif (*cfg) {\n\t\t\t*cfg = '\\0';\n\t\t\tcfg++;\n\t\t}\n\t\tif (*ptr)\n\t\t\tfloppy_setup(ptr);\n\t}\n}", "static int __init floppy_module_init(void)\n{\n\tif (floppy)\n\t\tparse_floppy_cfg_string(floppy);\n\treturn floppy_init();\n}\nmodule_init(floppy_module_init);", "static void __exit floppy_module_exit(void)\n{\n\tint drive;", "\tblk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);\n\tunregister_blkdev(FLOPPY_MAJOR, \"fd\");\n\tplatform_driver_unregister(&floppy_driver);", "\tdestroy_workqueue(floppy_wq);", "\tfor (drive = 0; drive < N_DRIVE; drive++) {\n\t\tdel_timer_sync(&motor_off_timer[drive]);", "\t\tif (floppy_available(drive)) {\n\t\t\tdel_gendisk(disks[drive]);\n\t\t\tdevice_remove_file(&floppy_device[drive].dev, &dev_attr_cmos);\n\t\t\tplatform_device_unregister(&floppy_device[drive]);\n\t\t}\n\t\tblk_cleanup_queue(disks[drive]->queue);", "\t\t/*\n\t\t * These disks have not called add_disk(). Don't put down\n\t\t * queue reference in put_disk().\n\t\t */\n\t\tif (!(allowed_drive_mask & (1 << drive)) ||\n\t\t fdc_state[FDC(drive)].version == FDC_NONE)\n\t\t\tdisks[drive]->queue = NULL;", "\t\tput_disk(disks[drive]);\n\t}", "\tcancel_delayed_work_sync(&fd_timeout);\n\tcancel_delayed_work_sync(&fd_timer);", "\tif (atomic_read(&usage_count))\n\t\tfloppy_release_irq_and_dma();", "\t/* eject disk, if any */\n\tfd_eject(0);\n}", "module_exit(floppy_module_exit);", "module_param(floppy, charp, 0);\nmodule_param(FLOPPY_IRQ, int, 0);\nmodule_param(FLOPPY_DMA, int, 0);\nMODULE_AUTHOR(\"Alain L. Knaff\");\nMODULE_SUPPORTED_DEVICE(\"fd\");\nMODULE_LICENSE(\"GPL\");", "/* This doesn't actually get used other than for module information */\nstatic const struct pnp_device_id floppy_pnpids[] = {\n\t{\"PNP0700\", 0},\n\t{}\n};", "MODULE_DEVICE_TABLE(pnp, floppy_pnpids);", "#else", "__setup(\"floppy=\", floppy_setup);\nmodule_init(floppy_init)\n#endif", "MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [3071], "buggy_code_start_loc": [3070], "filenames": ["drivers/block/floppy.c"], "fixing_code_end_loc": [3074], "fixing_code_start_loc": [3070], "message": "The raw_cmd_copyout function in drivers/block/floppy.c in the Linux kernel through 3.14.3 does not properly restrict access to certain pointers during processing of an FDRAWCMD ioctl call, which allows local users to obtain sensitive information from kernel heap memory by leveraging write access to a /dev/fd device.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "B465C548-09E9-4CD5-A1C2-57ED09C9E3F4", "versionEndExcluding": null, "versionEndIncluding": "3.14.3", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:redhat:enterprise_linux_eus:5.6:*:*:*:*:*:*:*", "matchCriteriaId": "903512FC-0017-4564-9B89-7E64FFB14B11", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:redhat:enterprise_linux_eus:6.3:*:*:*:*:*:*:*", "matchCriteriaId": "8382A145-CDD9-437E-9DE7-A349956778B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:debian:debian_linux:6.0:*:*:*:*:*:*:*", "matchCriteriaId": "036E8A89-7A16-411F-9D31-676313BB7244", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:debian:debian_linux:7.0:*:*:*:*:*:*:*", "matchCriteriaId": "16F59A04-14CF-49E2-9973-645477EA09DA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:oracle:linux:5:-:*:*:*:*:*:*", "matchCriteriaId": "62A2AC02-A933-4E51-810E-5D040B476B7B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:oracle:linux:6:-:*:*:*:*:*:*", "matchCriteriaId": "D7B037A8-72A6-4DFF-94B2-D688A5F6F876", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}, {"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:suse:linux_enterprise_desktop:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "3ED68ADD-BBDA-4485-BC76-58F011D72311", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_high_availability_extension:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "A3A907A3-2A3A-46D4-8D75-914649877B65", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_real_time_extension:11:sp3:*:*:*:*:*:*", "matchCriteriaId": "3DB41B45-D94D-4A58-88B0-B3EC3EC350E2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_server:11:sp3:*:*:*:-:*:*", "matchCriteriaId": "E534C201-BCC5-473C-AAA7-AAB97CEB5437", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:suse:linux_enterprise_server:11:sp3:*:*:*:vmware:*:*", "matchCriteriaId": "2470C6E8-2024-4CF5-9982-CFF50E88EAE9", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The raw_cmd_copyout function in drivers/block/floppy.c in the Linux kernel through 3.14.3 does not properly restrict access to certain pointers during processing of an FDRAWCMD ioctl call, which allows local users to obtain sensitive information from kernel heap memory by leveraging write access to a /dev/fd device."}, {"lang": "es", "value": "La funci\u00f3n raw_cmd_copyout en drivers/block/floppy.c en el kernel de Linux hasta 3.14.3 no restringe debidamente acceso a ciertos punteros durante el procesamiento de una llamada FDRAWCMD ioctl, lo que permite a usuarios locales obtener informaci\u00f3n sensible de la memoria din\u00e1mica del kernel mediante el aprovechamiento de acceso a escritura hacia un dispositivo /dev/fd."}], "evaluatorComment": null, "id": "CVE-2014-1738", "lastModified": "2020-08-21T18:29:53.937", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "LOW", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 2.1, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.9, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2014-05-11T21:55:05.873", "references": [{"source": "cve-coordination@google.com", "tags": ["Mailing List", "Patch", "Vendor Advisory"], "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=2145e15e0557a01b9195d1c7199a1b92cb9be81f"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-0771.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://linux.oracle.com/errata/ELSA-2014-3043.html"}, {"source": "cve-coordination@google.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-05/msg00007.html"}, {"source": "cve-coordination@google.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://lists.opensuse.org/opensuse-security-announce/2014-05/msg00012.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-0800.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://rhn.redhat.com/errata/RHSA-2014-0801.html"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2014/dsa-2926"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory"], "url": "http://www.debian.org/security/2014/dsa-2928"}, {"source": "cve-coordination@google.com", "tags": ["Mailing List", "Third Party Advisory"], "url": "http://www.openwall.com/lists/oss-security/2014/05/09/2"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securityfocus.com/bid/67302"}, {"source": "cve-coordination@google.com", "tags": ["Third Party Advisory", "VDB Entry"], "url": "http://www.securitytracker.com/id/1030474"}, {"source": "cve-coordination@google.com", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://bugzilla.redhat.com/show_bug.cgi?id=1094299"}, {"source": "cve-coordination@google.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/torvalds/linux/commit/2145e15e0557a01b9195d1c7199a1b92cb9be81f"}], "sourceIdentifier": "cve-coordination@google.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-200"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/2145e15e0557a01b9195d1c7199a1b92cb9be81f"}, "type": "CWE-200"}
32
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com\n * Written by Alex Tomas <alex@clusterfs.com>\n *\n * Architecture independence:\n * Copyright (c) 2005, Bull S.A.\n * Written by Pierre Peiffer <pierre.peiffer@bull.net>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public Licens\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-\n */", "/*\n * Extents support for EXT4\n *\n * TODO:\n * - ext4*_error() should be used in some situations\n * - analyze all BUG()/BUG_ON(), use -EIO where appropriate\n * - smart tree reduction\n */", "#include <linux/fs.h>\n#include <linux/time.h>\n#include <linux/jbd2.h>\n#include <linux/highuid.h>\n#include <linux/pagemap.h>\n#include <linux/quotaops.h>\n#include <linux/string.h>\n#include <linux/slab.h>\n#include <linux/falloc.h>\n#include <asm/uaccess.h>\n#include <linux/fiemap.h>\n#include \"ext4_jbd2.h\"", "#include <trace/events/ext4.h>", "/*\n * used by extent splitting.\n */\n#define EXT4_EXT_MAY_ZEROOUT\t0x1 /* safe to zeroout if split fails \\\n\t\t\t\t\tdue to ENOSPC */\n#define EXT4_EXT_MARK_UNINIT1\t0x2 /* mark first half uninitialized */\n#define EXT4_EXT_MARK_UNINIT2\t0x4 /* mark second half uninitialized */", "", "\nstatic __le32 ext4_extent_block_csum(struct inode *inode,\n\t\t\t\t struct ext4_extent_header *eh)\n{\n\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\t__u32 csum;", "\tcsum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,\n\t\t\t EXT4_EXTENT_TAIL_OFFSET(eh));\n\treturn cpu_to_le32(csum);\n}", "static int ext4_extent_block_csum_verify(struct inode *inode,\n\t\t\t\t\t struct ext4_extent_header *eh)\n{\n\tstruct ext4_extent_tail *et;", "\tif (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,\n\t\tEXT4_FEATURE_RO_COMPAT_METADATA_CSUM))\n\t\treturn 1;", "\tet = find_ext4_extent_tail(eh);\n\tif (et->et_checksum != ext4_extent_block_csum(inode, eh))\n\t\treturn 0;\n\treturn 1;\n}", "static void ext4_extent_block_csum_set(struct inode *inode,\n\t\t\t\t struct ext4_extent_header *eh)\n{\n\tstruct ext4_extent_tail *et;", "\tif (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,\n\t\tEXT4_FEATURE_RO_COMPAT_METADATA_CSUM))\n\t\treturn;", "\tet = find_ext4_extent_tail(eh);\n\tet->et_checksum = ext4_extent_block_csum(inode, eh);\n}", "static int ext4_split_extent(handle_t *handle,\n\t\t\t\tstruct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\tstruct ext4_map_blocks *map,\n\t\t\t\tint split_flag,\n\t\t\t\tint flags);", "static int ext4_split_extent_at(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t split,\n\t\t\t int split_flag,\n\t\t\t int flags);", "static int ext4_ext_truncate_extend_restart(handle_t *handle,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t int needed)\n{\n\tint err;", "\tif (!ext4_handle_valid(handle))\n\t\treturn 0;\n\tif (handle->h_buffer_credits > needed)\n\t\treturn 0;\n\terr = ext4_journal_extend(handle, needed);\n\tif (err <= 0)\n\t\treturn err;\n\terr = ext4_truncate_restart_trans(handle, inode, needed);\n\tif (err == 0)\n\t\terr = -EAGAIN;", "\treturn err;\n}", "/*\n * could return:\n * - EROFS\n * - ENOMEM\n */\nstatic int ext4_ext_get_access(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path)\n{\n\tif (path->p_bh) {\n\t\t/* path points to block */\n\t\treturn ext4_journal_get_write_access(handle, path->p_bh);\n\t}\n\t/* path points to leaf/index in inode body */\n\t/* we use in-core data, no need to protect them */\n\treturn 0;\n}", "/*\n * could return:\n * - EROFS\n * - ENOMEM\n * - EIO\n */\n#define ext4_ext_dirty(handle, inode, path) \\\n\t\t__ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))\nstatic int __ext4_ext_dirty(const char *where, unsigned int line,\n\t\t\t handle_t *handle, struct inode *inode,\n\t\t\t struct ext4_ext_path *path)\n{\n\tint err;\n\tif (path->p_bh) {\n\t\text4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));\n\t\t/* path points to block */\n\t\terr = __ext4_handle_dirty_metadata(where, line, handle,\n\t\t\t\t\t\t inode, path->p_bh);\n\t} else {\n\t\t/* path points to leaf/index in inode body */\n\t\terr = ext4_mark_inode_dirty(handle, inode);\n\t}\n\treturn err;\n}", "static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t block)\n{\n\tif (path) {\n\t\tint depth = path->p_depth;\n\t\tstruct ext4_extent *ex;", "\t\t/*\n\t\t * Try to predict block placement assuming that we are\n\t\t * filling in a file which will eventually be\n\t\t * non-sparse --- i.e., in the case of libbfd writing\n\t\t * an ELF object sections out-of-order but in a way\n\t\t * the eventually results in a contiguous object or\n\t\t * executable file, or some database extending a table\n\t\t * space file. However, this is actually somewhat\n\t\t * non-ideal if we are writing a sparse file such as\n\t\t * qemu or KVM writing a raw image file that is going\n\t\t * to stay fairly sparse, since it will end up\n\t\t * fragmenting the file system's free space. Maybe we\n\t\t * should have some hueristics or some way to allow\n\t\t * userspace to pass a hint to file system,\n\t\t * especially if the latter case turns out to be\n\t\t * common.\n\t\t */\n\t\tex = path[depth].p_ext;\n\t\tif (ex) {\n\t\t\text4_fsblk_t ext_pblk = ext4_ext_pblock(ex);\n\t\t\text4_lblk_t ext_block = le32_to_cpu(ex->ee_block);", "\t\t\tif (block > ext_block)\n\t\t\t\treturn ext_pblk + (block - ext_block);\n\t\t\telse\n\t\t\t\treturn ext_pblk - (ext_block - block);\n\t\t}", "\t\t/* it looks like index is empty;\n\t\t * try to find starting block from index itself */\n\t\tif (path[depth].p_bh)\n\t\t\treturn path[depth].p_bh->b_blocknr;\n\t}", "\t/* OK. use inode's group */\n\treturn ext4_inode_to_goal_block(inode);\n}", "/*\n * Allocation for a meta data block\n */\nstatic ext4_fsblk_t\next4_ext_new_meta_block(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_ext_path *path,\n\t\t\tstruct ext4_extent *ex, int *err, unsigned int flags)\n{\n\text4_fsblk_t goal, newblock;", "\tgoal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));\n\tnewblock = ext4_new_meta_blocks(handle, inode, goal, flags,\n\t\t\t\t\tNULL, err);\n\treturn newblock;\n}", "static inline int ext4_ext_space_block(struct inode *inode, int check)\n{\n\tint size;", "\tsize = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))\n\t\t\t/ sizeof(struct ext4_extent);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 6)\n\t\tsize = 6;\n#endif\n\treturn size;\n}", "static inline int ext4_ext_space_block_idx(struct inode *inode, int check)\n{\n\tint size;", "\tsize = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))\n\t\t\t/ sizeof(struct ext4_extent_idx);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 5)\n\t\tsize = 5;\n#endif\n\treturn size;\n}", "static inline int ext4_ext_space_root(struct inode *inode, int check)\n{\n\tint size;", "\tsize = sizeof(EXT4_I(inode)->i_data);\n\tsize -= sizeof(struct ext4_extent_header);\n\tsize /= sizeof(struct ext4_extent);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 3)\n\t\tsize = 3;\n#endif\n\treturn size;\n}", "static inline int ext4_ext_space_root_idx(struct inode *inode, int check)\n{\n\tint size;", "\tsize = sizeof(EXT4_I(inode)->i_data);\n\tsize -= sizeof(struct ext4_extent_header);\n\tsize /= sizeof(struct ext4_extent_idx);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 4)\n\t\tsize = 4;\n#endif\n\treturn size;\n}", "/*\n * Calculate the number of metadata blocks needed\n * to allocate @blocks\n * Worse case is one block per extent\n */\nint ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)\n{\n\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\tint idxs;", "\tidxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))\n\t\t/ sizeof(struct ext4_extent_idx));", "\t/*\n\t * If the new delayed allocation block is contiguous with the\n\t * previous da block, it can share index blocks with the\n\t * previous block, so we only need to allocate a new index\n\t * block every idxs leaf blocks. At ldxs**2 blocks, we need\n\t * an additional index block, and at ldxs**3 blocks, yet\n\t * another index blocks.\n\t */\n\tif (ei->i_da_metadata_calc_len &&\n\t ei->i_da_metadata_calc_last_lblock+1 == lblock) {\n\t\tint num = 0;", "\t\tif ((ei->i_da_metadata_calc_len % idxs) == 0)\n\t\t\tnum++;\n\t\tif ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)\n\t\t\tnum++;\n\t\tif ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {\n\t\t\tnum++;\n\t\t\tei->i_da_metadata_calc_len = 0;\n\t\t} else\n\t\t\tei->i_da_metadata_calc_len++;\n\t\tei->i_da_metadata_calc_last_lblock++;\n\t\treturn num;\n\t}", "\t/*\n\t * In the worst case we need a new set of index blocks at\n\t * every level of the inode's extent tree.\n\t */\n\tei->i_da_metadata_calc_len = 1;\n\tei->i_da_metadata_calc_last_lblock = lblock;\n\treturn ext_depth(inode) + 1;\n}", "static int\next4_ext_max_entries(struct inode *inode, int depth)\n{\n\tint max;", "\tif (depth == ext_depth(inode)) {\n\t\tif (depth == 0)\n\t\t\tmax = ext4_ext_space_root(inode, 1);\n\t\telse\n\t\t\tmax = ext4_ext_space_root_idx(inode, 1);\n\t} else {\n\t\tif (depth == 0)\n\t\t\tmax = ext4_ext_space_block(inode, 1);\n\t\telse\n\t\t\tmax = ext4_ext_space_block_idx(inode, 1);\n\t}", "\treturn max;\n}", "static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)\n{\n\text4_fsblk_t block = ext4_ext_pblock(ext);\n\tint len = ext4_ext_get_actual_len(ext);", "\tif (len == 0)\n\t\treturn 0;\n\treturn ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);\n}", "static int ext4_valid_extent_idx(struct inode *inode,\n\t\t\t\tstruct ext4_extent_idx *ext_idx)\n{\n\text4_fsblk_t block = ext4_idx_pblock(ext_idx);", "\treturn ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);\n}", "static int ext4_valid_extent_entries(struct inode *inode,\n\t\t\t\tstruct ext4_extent_header *eh,\n\t\t\t\tint depth)\n{\n\tunsigned short entries;\n\tif (eh->eh_entries == 0)\n\t\treturn 1;", "\tentries = le16_to_cpu(eh->eh_entries);", "\tif (depth == 0) {\n\t\t/* leaf entries */\n\t\tstruct ext4_extent *ext = EXT_FIRST_EXTENT(eh);\n\t\twhile (entries) {\n\t\t\tif (!ext4_valid_extent(inode, ext))\n\t\t\t\treturn 0;\n\t\t\text++;\n\t\t\tentries--;\n\t\t}\n\t} else {\n\t\tstruct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);\n\t\twhile (entries) {\n\t\t\tif (!ext4_valid_extent_idx(inode, ext_idx))\n\t\t\t\treturn 0;\n\t\t\text_idx++;\n\t\t\tentries--;\n\t\t}\n\t}\n\treturn 1;\n}", "static int __ext4_ext_check(const char *function, unsigned int line,\n\t\t\t struct inode *inode, struct ext4_extent_header *eh,\n\t\t\t int depth)\n{\n\tconst char *error_msg;\n\tint max = 0;", "\tif (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {\n\t\terror_msg = \"invalid magic\";\n\t\tgoto corrupted;\n\t}\n\tif (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {\n\t\terror_msg = \"unexpected eh_depth\";\n\t\tgoto corrupted;\n\t}\n\tif (unlikely(eh->eh_max == 0)) {\n\t\terror_msg = \"invalid eh_max\";\n\t\tgoto corrupted;\n\t}\n\tmax = ext4_ext_max_entries(inode, depth);\n\tif (unlikely(le16_to_cpu(eh->eh_max) > max)) {\n\t\terror_msg = \"too large eh_max\";\n\t\tgoto corrupted;\n\t}\n\tif (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {\n\t\terror_msg = \"invalid eh_entries\";\n\t\tgoto corrupted;\n\t}\n\tif (!ext4_valid_extent_entries(inode, eh, depth)) {\n\t\terror_msg = \"invalid extent entries\";\n\t\tgoto corrupted;\n\t}\n\t/* Verify checksum on non-root extent tree nodes */\n\tif (ext_depth(inode) != depth &&\n\t !ext4_extent_block_csum_verify(inode, eh)) {\n\t\terror_msg = \"extent tree corrupted\";\n\t\tgoto corrupted;\n\t}\n\treturn 0;", "corrupted:\n\text4_error_inode(inode, function, line, 0,\n\t\t\t\"bad header/extent: %s - magic %x, \"\n\t\t\t\"entries %u, max %u(%u), depth %u(%u)\",\n\t\t\terror_msg, le16_to_cpu(eh->eh_magic),\n\t\t\tle16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),\n\t\t\tmax, le16_to_cpu(eh->eh_depth), depth);", "\treturn -EIO;\n}", "#define ext4_ext_check(inode, eh, depth)\t\\\n\t__ext4_ext_check(__func__, __LINE__, inode, eh, depth)", "int ext4_ext_check_inode(struct inode *inode)\n{\n\treturn ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));\n}", "static int __ext4_ext_check_block(const char *function, unsigned int line,\n\t\t\t\t struct inode *inode,\n\t\t\t\t struct ext4_extent_header *eh,\n\t\t\t\t int depth,\n\t\t\t\t struct buffer_head *bh)\n{\n\tint ret;", "\tif (buffer_verified(bh))\n\t\treturn 0;\n\tret = ext4_ext_check(inode, eh, depth);\n\tif (ret)\n\t\treturn ret;\n\tset_buffer_verified(bh);\n\treturn ret;\n}", "#define ext4_ext_check_block(inode, eh, depth, bh)\t\\\n\t__ext4_ext_check_block(__func__, __LINE__, inode, eh, depth, bh)", "#ifdef EXT_DEBUG\nstatic void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)\n{\n\tint k, l = path->p_depth;", "\text_debug(\"path:\");\n\tfor (k = 0; k <= l; k++, path++) {\n\t\tif (path->p_idx) {\n\t\t ext_debug(\" %d->%llu\", le32_to_cpu(path->p_idx->ei_block),\n\t\t\t ext4_idx_pblock(path->p_idx));\n\t\t} else if (path->p_ext) {\n\t\t\text_debug(\" %d:[%d]%d:%llu \",\n\t\t\t\t le32_to_cpu(path->p_ext->ee_block),\n\t\t\t\t ext4_ext_is_uninitialized(path->p_ext),\n\t\t\t\t ext4_ext_get_actual_len(path->p_ext),\n\t\t\t\t ext4_ext_pblock(path->p_ext));\n\t\t} else\n\t\t\text_debug(\" []\");\n\t}\n\text_debug(\"\\n\");\n}", "static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)\n{\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *ex;\n\tint i;", "\tif (!path)\n\t\treturn;", "\teh = path[depth].p_hdr;\n\tex = EXT_FIRST_EXTENT(eh);", "\text_debug(\"Displaying leaf extents for inode %lu\\n\", inode->i_ino);", "\tfor (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {\n\t\text_debug(\"%d:[%d]%d:%llu \", le32_to_cpu(ex->ee_block),\n\t\t\t ext4_ext_is_uninitialized(ex),\n\t\t\t ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));\n\t}\n\text_debug(\"\\n\");\n}", "static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,\n\t\t\text4_fsblk_t newblock, int level)\n{\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent *ex;", "\tif (depth != level) {\n\t\tstruct ext4_extent_idx *idx;\n\t\tidx = path[level].p_idx;\n\t\twhile (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {\n\t\t\text_debug(\"%d: move %d:%llu in new index %llu\\n\", level,\n\t\t\t\t\tle32_to_cpu(idx->ei_block),\n\t\t\t\t\text4_idx_pblock(idx),\n\t\t\t\t\tnewblock);\n\t\t\tidx++;\n\t\t}", "\t\treturn;\n\t}", "\tex = path[depth].p_ext;\n\twhile (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {\n\t\text_debug(\"move %d:%llu:[%d]%d in new leaf %llu\\n\",\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\text4_ext_pblock(ex),\n\t\t\t\text4_ext_is_uninitialized(ex),\n\t\t\t\text4_ext_get_actual_len(ex),\n\t\t\t\tnewblock);\n\t\tex++;\n\t}\n}", "#else\n#define ext4_ext_show_path(inode, path)\n#define ext4_ext_show_leaf(inode, path)\n#define ext4_ext_show_move(inode, path, newblock, level)\n#endif", "void ext4_ext_drop_refs(struct ext4_ext_path *path)\n{\n\tint depth = path->p_depth;\n\tint i;", "\tfor (i = 0; i <= depth; i++, path++)\n\t\tif (path->p_bh) {\n\t\t\tbrelse(path->p_bh);\n\t\t\tpath->p_bh = NULL;\n\t\t}\n}", "/*\n * ext4_ext_binsearch_idx:\n * binary search for the closest index of the given block\n * the header must be checked before calling this\n */\nstatic void\next4_ext_binsearch_idx(struct inode *inode,\n\t\t\tstruct ext4_ext_path *path, ext4_lblk_t block)\n{\n\tstruct ext4_extent_header *eh = path->p_hdr;\n\tstruct ext4_extent_idx *r, *l, *m;", "\n\text_debug(\"binsearch for %u(idx): \", block);", "\tl = EXT_FIRST_INDEX(eh) + 1;\n\tr = EXT_LAST_INDEX(eh);\n\twhile (l <= r) {\n\t\tm = l + (r - l) / 2;\n\t\tif (block < le32_to_cpu(m->ei_block))\n\t\t\tr = m - 1;\n\t\telse\n\t\t\tl = m + 1;\n\t\text_debug(\"%p(%u):%p(%u):%p(%u) \", l, le32_to_cpu(l->ei_block),\n\t\t\t\tm, le32_to_cpu(m->ei_block),\n\t\t\t\tr, le32_to_cpu(r->ei_block));\n\t}", "\tpath->p_idx = l - 1;\n\text_debug(\" -> %u->%lld \", le32_to_cpu(path->p_idx->ei_block),\n\t\t ext4_idx_pblock(path->p_idx));", "#ifdef CHECK_BINSEARCH\n\t{\n\t\tstruct ext4_extent_idx *chix, *ix;\n\t\tint k;", "\t\tchix = ix = EXT_FIRST_INDEX(eh);\n\t\tfor (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {\n\t\t if (k != 0 &&\n\t\t le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {\n\t\t\t\tprintk(KERN_DEBUG \"k=%d, ix=0x%p, \"\n\t\t\t\t \"first=0x%p\\n\", k,\n\t\t\t\t ix, EXT_FIRST_INDEX(eh));\n\t\t\t\tprintk(KERN_DEBUG \"%u <= %u\\n\",\n\t\t\t\t le32_to_cpu(ix->ei_block),\n\t\t\t\t le32_to_cpu(ix[-1].ei_block));\n\t\t\t}\n\t\t\tBUG_ON(k && le32_to_cpu(ix->ei_block)\n\t\t\t\t\t <= le32_to_cpu(ix[-1].ei_block));\n\t\t\tif (block < le32_to_cpu(ix->ei_block))\n\t\t\t\tbreak;\n\t\t\tchix = ix;\n\t\t}\n\t\tBUG_ON(chix != path->p_idx);\n\t}\n#endif", "}", "/*\n * ext4_ext_binsearch:\n * binary search for closest extent of the given block\n * the header must be checked before calling this\n */\nstatic void\next4_ext_binsearch(struct inode *inode,\n\t\tstruct ext4_ext_path *path, ext4_lblk_t block)\n{\n\tstruct ext4_extent_header *eh = path->p_hdr;\n\tstruct ext4_extent *r, *l, *m;", "\tif (eh->eh_entries == 0) {\n\t\t/*\n\t\t * this leaf is empty:\n\t\t * we get such a leaf in split/add case\n\t\t */\n\t\treturn;\n\t}", "\text_debug(\"binsearch for %u: \", block);", "\tl = EXT_FIRST_EXTENT(eh) + 1;\n\tr = EXT_LAST_EXTENT(eh);", "\twhile (l <= r) {\n\t\tm = l + (r - l) / 2;\n\t\tif (block < le32_to_cpu(m->ee_block))\n\t\t\tr = m - 1;\n\t\telse\n\t\t\tl = m + 1;\n\t\text_debug(\"%p(%u):%p(%u):%p(%u) \", l, le32_to_cpu(l->ee_block),\n\t\t\t\tm, le32_to_cpu(m->ee_block),\n\t\t\t\tr, le32_to_cpu(r->ee_block));\n\t}", "\tpath->p_ext = l - 1;\n\text_debug(\" -> %d:%llu:[%d]%d \",\n\t\t\tle32_to_cpu(path->p_ext->ee_block),\n\t\t\text4_ext_pblock(path->p_ext),\n\t\t\text4_ext_is_uninitialized(path->p_ext),\n\t\t\text4_ext_get_actual_len(path->p_ext));", "#ifdef CHECK_BINSEARCH\n\t{\n\t\tstruct ext4_extent *chex, *ex;\n\t\tint k;", "\t\tchex = ex = EXT_FIRST_EXTENT(eh);\n\t\tfor (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {\n\t\t\tBUG_ON(k && le32_to_cpu(ex->ee_block)\n\t\t\t\t\t <= le32_to_cpu(ex[-1].ee_block));\n\t\t\tif (block < le32_to_cpu(ex->ee_block))\n\t\t\t\tbreak;\n\t\t\tchex = ex;\n\t\t}\n\t\tBUG_ON(chex != path->p_ext);\n\t}\n#endif", "}", "int ext4_ext_tree_init(handle_t *handle, struct inode *inode)\n{\n\tstruct ext4_extent_header *eh;", "\teh = ext_inode_hdr(inode);\n\teh->eh_depth = 0;\n\teh->eh_entries = 0;\n\teh->eh_magic = EXT4_EXT_MAGIC;\n\teh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));\n\text4_mark_inode_dirty(handle, inode);\n\text4_ext_invalidate_cache(inode);\n\treturn 0;\n}", "struct ext4_ext_path *\next4_ext_find_extent(struct inode *inode, ext4_lblk_t block,\n\t\t\t\t\tstruct ext4_ext_path *path)\n{\n\tstruct ext4_extent_header *eh;\n\tstruct buffer_head *bh;\n\tshort int depth, i, ppos = 0, alloc = 0;", "\teh = ext_inode_hdr(inode);\n\tdepth = ext_depth(inode);", "\t/* account possible depth increase */\n\tif (!path) {\n\t\tpath = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),\n\t\t\t\tGFP_NOFS);\n\t\tif (!path)\n\t\t\treturn ERR_PTR(-ENOMEM);\n\t\talloc = 1;\n\t}\n\tpath[0].p_hdr = eh;\n\tpath[0].p_bh = NULL;", "\ti = depth;\n\t/* walk through the tree */\n\twhile (i) {\n\t\text_debug(\"depth %d: num %d, max %d\\n\",\n\t\t\t ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));", "\t\text4_ext_binsearch_idx(inode, path + ppos, block);\n\t\tpath[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);\n\t\tpath[ppos].p_depth = i;\n\t\tpath[ppos].p_ext = NULL;", "\t\tbh = sb_getblk(inode->i_sb, path[ppos].p_block);\n\t\tif (unlikely(!bh))\n\t\t\tgoto err;\n\t\tif (!bh_uptodate_or_lock(bh)) {\n\t\t\ttrace_ext4_ext_load_extent(inode, block,\n\t\t\t\t\t\tpath[ppos].p_block);\n\t\t\tif (bh_submit_read(bh) < 0) {\n\t\t\t\tput_bh(bh);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t}\n\t\teh = ext_block_hdr(bh);\n\t\tppos++;\n\t\tif (unlikely(ppos > depth)) {\n\t\t\tput_bh(bh);\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"ppos %d > depth %d\", ppos, depth);\n\t\t\tgoto err;\n\t\t}\n\t\tpath[ppos].p_bh = bh;\n\t\tpath[ppos].p_hdr = eh;\n\t\ti--;", "\t\tif (ext4_ext_check_block(inode, eh, i, bh))\n\t\t\tgoto err;\n\t}", "\tpath[ppos].p_depth = i;\n\tpath[ppos].p_ext = NULL;\n\tpath[ppos].p_idx = NULL;", "\t/* find extent */\n\text4_ext_binsearch(inode, path + ppos, block);\n\t/* if not an empty leaf */\n\tif (path[ppos].p_ext)\n\t\tpath[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);", "\text4_ext_show_path(inode, path);", "\treturn path;", "err:\n\text4_ext_drop_refs(path);\n\tif (alloc)\n\t\tkfree(path);\n\treturn ERR_PTR(-EIO);\n}", "/*\n * ext4_ext_insert_index:\n * insert new index [@logical;@ptr] into the block at @curp;\n * check where to insert: before @curp or after @curp\n */\nstatic int ext4_ext_insert_index(handle_t *handle, struct inode *inode,\n\t\t\t\t struct ext4_ext_path *curp,\n\t\t\t\t int logical, ext4_fsblk_t ptr)\n{\n\tstruct ext4_extent_idx *ix;\n\tint len, err;", "\terr = ext4_ext_get_access(handle, inode, curp);\n\tif (err)\n\t\treturn err;", "\tif (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"logical %d == ei_block %d!\",\n\t\t\t\t logical, le32_to_cpu(curp->p_idx->ei_block));\n\t\treturn -EIO;\n\t}", "\tif (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)\n\t\t\t >= le16_to_cpu(curp->p_hdr->eh_max))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"eh_entries %d >= eh_max %d!\",\n\t\t\t\t le16_to_cpu(curp->p_hdr->eh_entries),\n\t\t\t\t le16_to_cpu(curp->p_hdr->eh_max));\n\t\treturn -EIO;\n\t}", "\tif (logical > le32_to_cpu(curp->p_idx->ei_block)) {\n\t\t/* insert after */\n\t\text_debug(\"insert new index %d after: %llu\\n\", logical, ptr);\n\t\tix = curp->p_idx + 1;\n\t} else {\n\t\t/* insert before */\n\t\text_debug(\"insert new index %d before: %llu\\n\", logical, ptr);\n\t\tix = curp->p_idx;\n\t}", "\tlen = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;\n\tBUG_ON(len < 0);\n\tif (len > 0) {\n\t\text_debug(\"insert new index %d: \"\n\t\t\t\t\"move %d indices from 0x%p to 0x%p\\n\",\n\t\t\t\tlogical, len, ix, ix + 1);\n\t\tmemmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));\n\t}", "\tif (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"ix > EXT_MAX_INDEX!\");\n\t\treturn -EIO;\n\t}", "\tix->ei_block = cpu_to_le32(logical);\n\text4_idx_store_pblock(ix, ptr);\n\tle16_add_cpu(&curp->p_hdr->eh_entries, 1);", "\tif (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"ix > EXT_LAST_INDEX!\");\n\t\treturn -EIO;\n\t}", "\terr = ext4_ext_dirty(handle, inode, curp);\n\text4_std_error(inode->i_sb, err);", "\treturn err;\n}", "/*\n * ext4_ext_split:\n * inserts new subtree into the path, using free index entry\n * at depth @at:\n * - allocates all needed blocks (new leaf and all intermediate index blocks)\n * - makes decision where to split\n * - moves remaining extents and index entries (right to the split point)\n * into the newly allocated blocks\n * - initializes subtree\n */\nstatic int ext4_ext_split(handle_t *handle, struct inode *inode,\n\t\t\t unsigned int flags,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t struct ext4_extent *newext, int at)\n{\n\tstruct buffer_head *bh = NULL;\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent_header *neh;\n\tstruct ext4_extent_idx *fidx;\n\tint i = at, k, m, a;\n\text4_fsblk_t newblock, oldblock;\n\t__le32 border;\n\text4_fsblk_t *ablocks = NULL; /* array of allocated blocks */\n\tint err = 0;", "\t/* make decision: where to split? */\n\t/* FIXME: now decision is simplest: at current extent */", "\t/* if current leaf will be split, then we should use\n\t * border from split point */\n\tif (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"p_ext > EXT_MAX_EXTENT!\");\n\t\treturn -EIO;\n\t}\n\tif (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {\n\t\tborder = path[depth].p_ext[1].ee_block;\n\t\text_debug(\"leaf will be split.\"\n\t\t\t\t\" next leaf starts at %d\\n\",\n\t\t\t\t le32_to_cpu(border));\n\t} else {\n\t\tborder = newext->ee_block;\n\t\text_debug(\"leaf will be added.\"\n\t\t\t\t\" next leaf starts at %d\\n\",\n\t\t\t\tle32_to_cpu(border));\n\t}", "\t/*\n\t * If error occurs, then we break processing\n\t * and mark filesystem read-only. index won't\n\t * be inserted and tree will be in consistent\n\t * state. Next mount will repair buffers too.\n\t */", "\t/*\n\t * Get array to track all allocated blocks.\n\t * We need this to handle errors and free blocks\n\t * upon them.\n\t */\n\tablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);\n\tif (!ablocks)\n\t\treturn -ENOMEM;", "\t/* allocate all needed blocks */\n\text_debug(\"allocate %d blocks for indexes/leaf\\n\", depth - at);\n\tfor (a = 0; a < depth - at; a++) {\n\t\tnewblock = ext4_ext_new_meta_block(handle, inode, path,\n\t\t\t\t\t\t newext, &err, flags);\n\t\tif (newblock == 0)\n\t\t\tgoto cleanup;\n\t\tablocks[a] = newblock;\n\t}", "\t/* initialize new leaf */\n\tnewblock = ablocks[--a];\n\tif (unlikely(newblock == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"newblock == 0!\");\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tbh = sb_getblk(inode->i_sb, newblock);\n\tif (!bh) {\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tlock_buffer(bh);", "\terr = ext4_journal_get_create_access(handle, bh);\n\tif (err)\n\t\tgoto cleanup;", "\tneh = ext_block_hdr(bh);\n\tneh->eh_entries = 0;\n\tneh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));\n\tneh->eh_magic = EXT4_EXT_MAGIC;\n\tneh->eh_depth = 0;", "\t/* move remainder of path[depth] to the new leaf */\n\tif (unlikely(path[depth].p_hdr->eh_entries !=\n\t\t path[depth].p_hdr->eh_max)) {\n\t\tEXT4_ERROR_INODE(inode, \"eh_entries %d != eh_max %d!\",\n\t\t\t\t path[depth].p_hdr->eh_entries,\n\t\t\t\t path[depth].p_hdr->eh_max);\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\t/* start copy from next extent */\n\tm = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;\n\text4_ext_show_move(inode, path, newblock, depth);\n\tif (m) {\n\t\tstruct ext4_extent *ex;\n\t\tex = EXT_FIRST_EXTENT(neh);\n\t\tmemmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);\n\t\tle16_add_cpu(&neh->eh_entries, m);\n\t}", "\text4_extent_block_csum_set(inode, neh);\n\tset_buffer_uptodate(bh);\n\tunlock_buffer(bh);", "\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\tif (err)\n\t\tgoto cleanup;\n\tbrelse(bh);\n\tbh = NULL;", "\t/* correct old leaf */\n\tif (m) {\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\t\tle16_add_cpu(&path[depth].p_hdr->eh_entries, -m);\n\t\terr = ext4_ext_dirty(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto cleanup;", "\t}", "\t/* create intermediate indexes */\n\tk = depth - at - 1;\n\tif (unlikely(k < 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"k %d < 0!\", k);\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tif (k)\n\t\text_debug(\"create %d intermediate indices\\n\", k);\n\t/* insert new index into current index block */\n\t/* current depth stored in i var */\n\ti = depth - 1;\n\twhile (k--) {\n\t\toldblock = newblock;\n\t\tnewblock = ablocks[--a];\n\t\tbh = sb_getblk(inode->i_sb, newblock);\n\t\tif (!bh) {\n\t\t\terr = -EIO;\n\t\t\tgoto cleanup;\n\t\t}\n\t\tlock_buffer(bh);", "\t\terr = ext4_journal_get_create_access(handle, bh);\n\t\tif (err)\n\t\t\tgoto cleanup;", "\t\tneh = ext_block_hdr(bh);\n\t\tneh->eh_entries = cpu_to_le16(1);\n\t\tneh->eh_magic = EXT4_EXT_MAGIC;\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));\n\t\tneh->eh_depth = cpu_to_le16(depth - i);\n\t\tfidx = EXT_FIRST_INDEX(neh);\n\t\tfidx->ei_block = border;\n\t\text4_idx_store_pblock(fidx, oldblock);", "\t\text_debug(\"int.index at %d (block %llu): %u -> %llu\\n\",\n\t\t\t\ti, newblock, le32_to_cpu(border), oldblock);", "\t\t/* move remainder of path[i] to the new index block */\n\t\tif (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=\n\t\t\t\t\tEXT_LAST_INDEX(path[i].p_hdr))) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!\",\n\t\t\t\t\t le32_to_cpu(path[i].p_ext->ee_block));\n\t\t\terr = -EIO;\n\t\t\tgoto cleanup;\n\t\t}\n\t\t/* start copy indexes */\n\t\tm = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;\n\t\text_debug(\"cur 0x%p, last 0x%p\\n\", path[i].p_idx,\n\t\t\t\tEXT_MAX_INDEX(path[i].p_hdr));\n\t\text4_ext_show_move(inode, path, newblock, i);\n\t\tif (m) {\n\t\t\tmemmove(++fidx, path[i].p_idx,\n\t\t\t\tsizeof(struct ext4_extent_idx) * m);\n\t\t\tle16_add_cpu(&neh->eh_entries, m);\n\t\t}\n\t\text4_extent_block_csum_set(inode, neh);\n\t\tset_buffer_uptodate(bh);\n\t\tunlock_buffer(bh);", "\t\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\t\tbrelse(bh);\n\t\tbh = NULL;", "\t\t/* correct old index */\n\t\tif (m) {\n\t\t\terr = ext4_ext_get_access(handle, inode, path + i);\n\t\t\tif (err)\n\t\t\t\tgoto cleanup;\n\t\t\tle16_add_cpu(&path[i].p_hdr->eh_entries, -m);\n\t\t\terr = ext4_ext_dirty(handle, inode, path + i);\n\t\t\tif (err)\n\t\t\t\tgoto cleanup;\n\t\t}", "\t\ti--;\n\t}", "\t/* insert new index */\n\terr = ext4_ext_insert_index(handle, inode, path + at,\n\t\t\t\t le32_to_cpu(border), newblock);", "cleanup:\n\tif (bh) {\n\t\tif (buffer_locked(bh))\n\t\t\tunlock_buffer(bh);\n\t\tbrelse(bh);\n\t}", "\tif (err) {\n\t\t/* free all allocated blocks in error case */\n\t\tfor (i = 0; i < depth; i++) {\n\t\t\tif (!ablocks[i])\n\t\t\t\tcontinue;\n\t\t\text4_free_blocks(handle, inode, NULL, ablocks[i], 1,\n\t\t\t\t\t EXT4_FREE_BLOCKS_METADATA);\n\t\t}\n\t}\n\tkfree(ablocks);", "\treturn err;\n}", "/*\n * ext4_ext_grow_indepth:\n * implements tree growing procedure:\n * - allocates new block\n * - moves top-level data (index block or leaf) into the new block\n * - initializes new top-level, creating index that points to the\n * just created block\n */\nstatic int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,\n\t\t\t\t unsigned int flags,\n\t\t\t\t struct ext4_extent *newext)\n{\n\tstruct ext4_extent_header *neh;\n\tstruct buffer_head *bh;\n\text4_fsblk_t newblock;\n\tint err = 0;", "\tnewblock = ext4_ext_new_meta_block(handle, inode, NULL,\n\t\tnewext, &err, flags);\n\tif (newblock == 0)\n\t\treturn err;", "\tbh = sb_getblk(inode->i_sb, newblock);\n\tif (!bh) {\n\t\terr = -EIO;\n\t\text4_std_error(inode->i_sb, err);\n\t\treturn err;\n\t}\n\tlock_buffer(bh);", "\terr = ext4_journal_get_create_access(handle, bh);\n\tif (err) {\n\t\tunlock_buffer(bh);\n\t\tgoto out;\n\t}", "\t/* move top-level index/leaf into new block */\n\tmemmove(bh->b_data, EXT4_I(inode)->i_data,\n\t\tsizeof(EXT4_I(inode)->i_data));", "\t/* set size of new block */\n\tneh = ext_block_hdr(bh);\n\t/* old root could have indexes or leaves\n\t * so calculate e_max right way */\n\tif (ext_depth(inode))\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));\n\telse\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));\n\tneh->eh_magic = EXT4_EXT_MAGIC;\n\text4_extent_block_csum_set(inode, neh);\n\tset_buffer_uptodate(bh);\n\tunlock_buffer(bh);", "\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\tif (err)\n\t\tgoto out;", "\t/* Update top-level index: num,max,pointer */\n\tneh = ext_inode_hdr(inode);\n\tneh->eh_entries = cpu_to_le16(1);\n\text4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);\n\tif (neh->eh_depth == 0) {\n\t\t/* Root extent block becomes index block */\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));\n\t\tEXT_FIRST_INDEX(neh)->ei_block =\n\t\t\tEXT_FIRST_EXTENT(neh)->ee_block;\n\t}\n\text_debug(\"new root: num %d(%d), lblock %d, ptr %llu\\n\",\n\t\t le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),\n\t\t le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),\n\t\t ext4_idx_pblock(EXT_FIRST_INDEX(neh)));", "\tle16_add_cpu(&neh->eh_depth, 1);\n\text4_mark_inode_dirty(handle, inode);\nout:\n\tbrelse(bh);", "\treturn err;\n}", "/*\n * ext4_ext_create_new_leaf:\n * finds empty index and adds new leaf.\n * if no free index is found, then it requests in-depth growing.\n */\nstatic int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,\n\t\t\t\t unsigned int flags,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t struct ext4_extent *newext)\n{\n\tstruct ext4_ext_path *curp;\n\tint depth, i, err = 0;", "repeat:\n\ti = depth = ext_depth(inode);", "\t/* walk up to the tree and look for free index entry */\n\tcurp = path + depth;\n\twhile (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {\n\t\ti--;\n\t\tcurp--;\n\t}", "\t/* we use already allocated block for index block,\n\t * so subsequent data blocks should be contiguous */\n\tif (EXT_HAS_FREE_INDEX(curp)) {\n\t\t/* if we found index with free entry, then use that\n\t\t * entry: create all needed subtree and add new leaf */\n\t\terr = ext4_ext_split(handle, inode, flags, path, newext, i);\n\t\tif (err)\n\t\t\tgoto out;", "\t\t/* refill path */\n\t\text4_ext_drop_refs(path);\n\t\tpath = ext4_ext_find_extent(inode,\n\t\t\t\t (ext4_lblk_t)le32_to_cpu(newext->ee_block),\n\t\t\t\t path);\n\t\tif (IS_ERR(path))\n\t\t\terr = PTR_ERR(path);\n\t} else {\n\t\t/* tree is full, time to grow in depth */\n\t\terr = ext4_ext_grow_indepth(handle, inode, flags, newext);\n\t\tif (err)\n\t\t\tgoto out;", "\t\t/* refill path */\n\t\text4_ext_drop_refs(path);\n\t\tpath = ext4_ext_find_extent(inode,\n\t\t\t\t (ext4_lblk_t)le32_to_cpu(newext->ee_block),\n\t\t\t\t path);\n\t\tif (IS_ERR(path)) {\n\t\t\terr = PTR_ERR(path);\n\t\t\tgoto out;\n\t\t}", "\t\t/*\n\t\t * only first (depth 0 -> 1) produces free space;\n\t\t * in all other cases we have to split the grown tree\n\t\t */\n\t\tdepth = ext_depth(inode);\n\t\tif (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {\n\t\t\t/* now we need to split */\n\t\t\tgoto repeat;\n\t\t}\n\t}", "out:\n\treturn err;\n}", "/*\n * search the closest allocated block to the left for *logical\n * and returns it at @logical + it's physical address at @phys\n * if *logical is the smallest allocated block, the function\n * returns 0 at @phys\n * return value contains 0 (success) or error code\n */\nstatic int ext4_ext_search_left(struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\text4_lblk_t *logical, ext4_fsblk_t *phys)\n{\n\tstruct ext4_extent_idx *ix;\n\tstruct ext4_extent *ex;\n\tint depth, ee_len;", "\tif (unlikely(path == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path == NULL *logical %d!\", *logical);\n\t\treturn -EIO;\n\t}\n\tdepth = path->p_depth;\n\t*phys = 0;", "\tif (depth == 0 && path->p_ext == NULL)\n\t\treturn 0;", "\t/* usually extent in the path covers blocks smaller\n\t * then *logical, but it can be that extent is the\n\t * first one in the file */", "\tex = path[depth].p_ext;\n\tee_len = ext4_ext_get_actual_len(ex);\n\tif (*logical < le32_to_cpu(ex->ee_block)) {\n\t\tif (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"EXT_FIRST_EXTENT != ex *logical %d ee_block %d!\",\n\t\t\t\t\t *logical, le32_to_cpu(ex->ee_block));\n\t\t\treturn -EIO;\n\t\t}\n\t\twhile (--depth >= 0) {\n\t\t\tix = path[depth].p_idx;\n\t\t\tif (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!\",\n\t\t\t\t ix != NULL ? le32_to_cpu(ix->ei_block) : 0,\n\t\t\t\t EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?\n\t\tle32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,\n\t\t\t\t depth);\n\t\t\t\treturn -EIO;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}", "\tif (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"logical %d < ee_block %d + ee_len %d!\",\n\t\t\t\t *logical, le32_to_cpu(ex->ee_block), ee_len);\n\t\treturn -EIO;\n\t}", "\t*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;\n\t*phys = ext4_ext_pblock(ex) + ee_len - 1;\n\treturn 0;\n}", "/*\n * search the closest allocated block to the right for *logical\n * and returns it at @logical + it's physical address at @phys\n * if *logical is the largest allocated block, the function\n * returns 0 at @phys\n * return value contains 0 (success) or error code\n */\nstatic int ext4_ext_search_right(struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t ext4_lblk_t *logical, ext4_fsblk_t *phys,\n\t\t\t\t struct ext4_extent **ret_ex)\n{\n\tstruct buffer_head *bh = NULL;\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent_idx *ix;\n\tstruct ext4_extent *ex;\n\text4_fsblk_t block;\n\tint depth;\t/* Note, NOT eh_depth; depth from top of tree */\n\tint ee_len;", "\tif (unlikely(path == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path == NULL *logical %d!\", *logical);\n\t\treturn -EIO;\n\t}\n\tdepth = path->p_depth;\n\t*phys = 0;", "\tif (depth == 0 && path->p_ext == NULL)\n\t\treturn 0;", "\t/* usually extent in the path covers blocks smaller\n\t * then *logical, but it can be that extent is the\n\t * first one in the file */", "\tex = path[depth].p_ext;\n\tee_len = ext4_ext_get_actual_len(ex);\n\tif (*logical < le32_to_cpu(ex->ee_block)) {\n\t\tif (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"first_extent(path[%d].p_hdr) != ex\",\n\t\t\t\t\t depth);\n\t\t\treturn -EIO;\n\t\t}\n\t\twhile (--depth >= 0) {\n\t\t\tix = path[depth].p_idx;\n\t\t\tif (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t\t \"ix != EXT_FIRST_INDEX *logical %d!\",\n\t\t\t\t\t\t *logical);\n\t\t\t\treturn -EIO;\n\t\t\t}\n\t\t}\n\t\tgoto found_extent;\n\t}", "\tif (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"logical %d < ee_block %d + ee_len %d!\",\n\t\t\t\t *logical, le32_to_cpu(ex->ee_block), ee_len);\n\t\treturn -EIO;\n\t}", "\tif (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {\n\t\t/* next allocated block in this leaf */\n\t\tex++;\n\t\tgoto found_extent;\n\t}", "\t/* go up and search for index to the right */\n\twhile (--depth >= 0) {\n\t\tix = path[depth].p_idx;\n\t\tif (ix != EXT_LAST_INDEX(path[depth].p_hdr))\n\t\t\tgoto got_index;\n\t}", "\t/* we've gone up to the root and found no index to the right */\n\treturn 0;", "got_index:\n\t/* we've found index to the right, let's\n\t * follow it and find the closest allocated\n\t * block to the right */\n\tix++;\n\tblock = ext4_idx_pblock(ix);\n\twhile (++depth < path->p_depth) {\n\t\tbh = sb_bread(inode->i_sb, block);\n\t\tif (bh == NULL)\n\t\t\treturn -EIO;\n\t\teh = ext_block_hdr(bh);\n\t\t/* subtract from p_depth to get proper eh_depth */\n\t\tif (ext4_ext_check_block(inode, eh,\n\t\t\t\t\t path->p_depth - depth, bh)) {\n\t\t\tput_bh(bh);\n\t\t\treturn -EIO;\n\t\t}\n\t\tix = EXT_FIRST_INDEX(eh);\n\t\tblock = ext4_idx_pblock(ix);\n\t\tput_bh(bh);\n\t}", "\tbh = sb_bread(inode->i_sb, block);\n\tif (bh == NULL)\n\t\treturn -EIO;\n\teh = ext_block_hdr(bh);\n\tif (ext4_ext_check_block(inode, eh, path->p_depth - depth, bh)) {\n\t\tput_bh(bh);\n\t\treturn -EIO;\n\t}\n\tex = EXT_FIRST_EXTENT(eh);\nfound_extent:\n\t*logical = le32_to_cpu(ex->ee_block);\n\t*phys = ext4_ext_pblock(ex);\n\t*ret_ex = ex;\n\tif (bh)\n\t\tput_bh(bh);\n\treturn 0;\n}", "/*\n * ext4_ext_next_allocated_block:\n * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.\n * NOTE: it considers block number from index entry as\n * allocated block. Thus, index entries have to be consistent\n * with leaves.\n */\nstatic ext4_lblk_t\next4_ext_next_allocated_block(struct ext4_ext_path *path)\n{\n\tint depth;", "\tBUG_ON(path == NULL);\n\tdepth = path->p_depth;", "\tif (depth == 0 && path->p_ext == NULL)\n\t\treturn EXT_MAX_BLOCKS;", "\twhile (depth >= 0) {\n\t\tif (depth == path->p_depth) {\n\t\t\t/* leaf */\n\t\t\tif (path[depth].p_ext &&\n\t\t\t\tpath[depth].p_ext !=\n\t\t\t\t\tEXT_LAST_EXTENT(path[depth].p_hdr))\n\t\t\t return le32_to_cpu(path[depth].p_ext[1].ee_block);\n\t\t} else {\n\t\t\t/* index */\n\t\t\tif (path[depth].p_idx !=\n\t\t\t\t\tEXT_LAST_INDEX(path[depth].p_hdr))\n\t\t\t return le32_to_cpu(path[depth].p_idx[1].ei_block);\n\t\t}\n\t\tdepth--;\n\t}", "\treturn EXT_MAX_BLOCKS;\n}", "/*\n * ext4_ext_next_leaf_block:\n * returns first allocated block from next leaf or EXT_MAX_BLOCKS\n */\nstatic ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)\n{\n\tint depth;", "\tBUG_ON(path == NULL);\n\tdepth = path->p_depth;", "\t/* zero-tree has no leaf blocks at all */\n\tif (depth == 0)\n\t\treturn EXT_MAX_BLOCKS;", "\t/* go to index block */\n\tdepth--;", "\twhile (depth >= 0) {\n\t\tif (path[depth].p_idx !=\n\t\t\t\tEXT_LAST_INDEX(path[depth].p_hdr))\n\t\t\treturn (ext4_lblk_t)\n\t\t\t\tle32_to_cpu(path[depth].p_idx[1].ei_block);\n\t\tdepth--;\n\t}", "\treturn EXT_MAX_BLOCKS;\n}", "/*\n * ext4_ext_correct_indexes:\n * if leaf gets modified and modified extent is first in the leaf,\n * then we have to correct all indexes above.\n * TODO: do we need to correct tree in all cases?\n */\nstatic int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path)\n{\n\tstruct ext4_extent_header *eh;\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent *ex;\n\t__le32 border;\n\tint k, err = 0;", "\teh = path[depth].p_hdr;\n\tex = path[depth].p_ext;", "\tif (unlikely(ex == NULL || eh == NULL)) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"ex %p == NULL or eh %p == NULL\", ex, eh);\n\t\treturn -EIO;\n\t}", "\tif (depth == 0) {\n\t\t/* there is no tree at all */\n\t\treturn 0;\n\t}", "\tif (ex != EXT_FIRST_EXTENT(eh)) {\n\t\t/* we correct tree if first leaf got modified only */\n\t\treturn 0;\n\t}", "\t/*\n\t * TODO: we need correction if border is smaller than current one\n\t */\n\tk = depth - 1;\n\tborder = path[depth].p_ext->ee_block;\n\terr = ext4_ext_get_access(handle, inode, path + k);\n\tif (err)\n\t\treturn err;\n\tpath[k].p_idx->ei_block = border;\n\terr = ext4_ext_dirty(handle, inode, path + k);\n\tif (err)\n\t\treturn err;", "\twhile (k--) {\n\t\t/* change all left-side indexes */\n\t\tif (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))\n\t\t\tbreak;\n\t\terr = ext4_ext_get_access(handle, inode, path + k);\n\t\tif (err)\n\t\t\tbreak;\n\t\tpath[k].p_idx->ei_block = border;\n\t\terr = ext4_ext_dirty(handle, inode, path + k);\n\t\tif (err)\n\t\t\tbreak;\n\t}", "\treturn err;\n}", "int\next4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,\n\t\t\t\tstruct ext4_extent *ex2)\n{\n\tunsigned short ext1_ee_len, ext2_ee_len, max_len;", "\t/*\n\t * Make sure that either both extents are uninitialized, or\n\t * both are _not_.\n\t */\n\tif (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))\n\t\treturn 0;", "\tif (ext4_ext_is_uninitialized(ex1))\n\t\tmax_len = EXT_UNINIT_MAX_LEN;\n\telse\n\t\tmax_len = EXT_INIT_MAX_LEN;", "\text1_ee_len = ext4_ext_get_actual_len(ex1);\n\text2_ee_len = ext4_ext_get_actual_len(ex2);", "\tif (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=\n\t\t\tle32_to_cpu(ex2->ee_block))\n\t\treturn 0;", "\t/*\n\t * To allow future support for preallocated extents to be added\n\t * as an RO_COMPAT feature, refuse to merge to extents if\n\t * this can result in the top bit of ee_len being set.\n\t */\n\tif (ext1_ee_len + ext2_ee_len > max_len)\n\t\treturn 0;\n#ifdef AGGRESSIVE_TEST\n\tif (ext1_ee_len >= 4)\n\t\treturn 0;\n#endif", "\tif (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))\n\t\treturn 1;\n\treturn 0;\n}", "/*\n * This function tries to merge the \"ex\" extent to the next extent in the tree.\n * It always tries to merge towards right. If you want to merge towards\n * left, pass \"ex - 1\" as argument instead of \"ex\".\n * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns\n * 1 if they got merged.\n */\nstatic int ext4_ext_try_to_merge_right(struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t struct ext4_extent *ex)\n{\n\tstruct ext4_extent_header *eh;\n\tunsigned int depth, len;\n\tint merge_done = 0;\n\tint uninitialized = 0;", "\tdepth = ext_depth(inode);\n\tBUG_ON(path[depth].p_hdr == NULL);\n\teh = path[depth].p_hdr;", "\twhile (ex < EXT_LAST_EXTENT(eh)) {\n\t\tif (!ext4_can_extents_be_merged(inode, ex, ex + 1))\n\t\t\tbreak;\n\t\t/* merge with next extent! */\n\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\tex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)\n\t\t\t\t+ ext4_ext_get_actual_len(ex + 1));\n\t\tif (uninitialized)\n\t\t\text4_ext_mark_uninitialized(ex);", "\t\tif (ex + 1 < EXT_LAST_EXTENT(eh)) {\n\t\t\tlen = (EXT_LAST_EXTENT(eh) - ex - 1)\n\t\t\t\t* sizeof(struct ext4_extent);\n\t\t\tmemmove(ex + 1, ex + 2, len);\n\t\t}\n\t\tle16_add_cpu(&eh->eh_entries, -1);\n\t\tmerge_done = 1;\n\t\tWARN_ON(eh->eh_entries == 0);\n\t\tif (!eh->eh_entries)\n\t\t\tEXT4_ERROR_INODE(inode, \"eh->eh_entries = 0!\");\n\t}", "\treturn merge_done;\n}", "/*\n * This function does a very simple check to see if we can collapse\n * an extent tree with a single extent tree leaf block into the inode.\n */\nstatic void ext4_ext_try_to_merge_up(handle_t *handle,\n\t\t\t\t struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path)\n{\n\tsize_t s;\n\tunsigned max_root = ext4_ext_space_root(inode, 0);\n\text4_fsblk_t blk;", "\tif ((path[0].p_depth != 1) ||\n\t (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||\n\t (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))\n\t\treturn;", "\t/*\n\t * We need to modify the block allocation bitmap and the block\n\t * group descriptor to release the extent tree block. If we\n\t * can't get the journal credits, give up.\n\t */\n\tif (ext4_journal_extend(handle, 2))\n\t\treturn;", "\t/*\n\t * Copy the extent data up to the inode\n\t */\n\tblk = ext4_idx_pblock(path[0].p_idx);\n\ts = le16_to_cpu(path[1].p_hdr->eh_entries) *\n\t\tsizeof(struct ext4_extent_idx);\n\ts += sizeof(struct ext4_extent_header);", "\tmemcpy(path[0].p_hdr, path[1].p_hdr, s);\n\tpath[0].p_depth = 0;\n\tpath[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +\n\t\t(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));\n\tpath[0].p_hdr->eh_max = cpu_to_le16(max_root);", "\tbrelse(path[1].p_bh);\n\text4_free_blocks(handle, inode, NULL, blk, 1,\n\t\t\t EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);\n}", "/*\n * This function tries to merge the @ex extent to neighbours in the tree.\n * return 1 if merge left else 0.\n */\nstatic void ext4_ext_try_to_merge(handle_t *handle,\n\t\t\t\t struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t struct ext4_extent *ex) {\n\tstruct ext4_extent_header *eh;\n\tunsigned int depth;\n\tint merge_done = 0;", "\tdepth = ext_depth(inode);\n\tBUG_ON(path[depth].p_hdr == NULL);\n\teh = path[depth].p_hdr;", "\tif (ex > EXT_FIRST_EXTENT(eh))\n\t\tmerge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);", "\tif (!merge_done)\n\t\t(void) ext4_ext_try_to_merge_right(inode, path, ex);", "\text4_ext_try_to_merge_up(handle, inode, path);\n}", "/*\n * check if a portion of the \"newext\" extent overlaps with an\n * existing extent.\n *\n * If there is an overlap discovered, it updates the length of the newext\n * such that there will be no overlap, and then returns 1.\n * If there is no overlap found, it returns 0.\n */\nstatic unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t struct ext4_extent *newext,\n\t\t\t\t\t struct ext4_ext_path *path)\n{\n\text4_lblk_t b1, b2;\n\tunsigned int depth, len1;\n\tunsigned int ret = 0;", "\tb1 = le32_to_cpu(newext->ee_block);\n\tlen1 = ext4_ext_get_actual_len(newext);\n\tdepth = ext_depth(inode);\n\tif (!path[depth].p_ext)\n\t\tgoto out;\n\tb2 = le32_to_cpu(path[depth].p_ext->ee_block);\n\tb2 &= ~(sbi->s_cluster_ratio - 1);", "\t/*\n\t * get the next allocated block if the extent in the path\n\t * is before the requested block(s)\n\t */\n\tif (b2 < b1) {\n\t\tb2 = ext4_ext_next_allocated_block(path);\n\t\tif (b2 == EXT_MAX_BLOCKS)\n\t\t\tgoto out;\n\t\tb2 &= ~(sbi->s_cluster_ratio - 1);\n\t}", "\t/* check for wrap through zero on extent logical start block*/\n\tif (b1 + len1 < b1) {\n\t\tlen1 = EXT_MAX_BLOCKS - b1;\n\t\tnewext->ee_len = cpu_to_le16(len1);\n\t\tret = 1;\n\t}", "\t/* check for overlap */\n\tif (b1 + len1 > b2) {\n\t\tnewext->ee_len = cpu_to_le16(b2 - b1);\n\t\tret = 1;\n\t}\nout:\n\treturn ret;\n}", "/*\n * ext4_ext_insert_extent:\n * tries to merge requsted extent into the existing extent or\n * inserts requested extent as new one into the tree,\n * creating new leaf in the no-space case.\n */\nint ext4_ext_insert_extent(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\tstruct ext4_extent *newext, int flag)\n{\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *ex, *fex;\n\tstruct ext4_extent *nearex; /* nearest extent */\n\tstruct ext4_ext_path *npath = NULL;\n\tint depth, len, err;\n\text4_lblk_t next;\n\tunsigned uninitialized = 0;\n\tint flags = 0;", "\tif (unlikely(ext4_ext_get_actual_len(newext) == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"ext4_ext_get_actual_len(newext) == 0\");\n\t\treturn -EIO;\n\t}\n\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tif (unlikely(path[depth].p_hdr == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path[%d].p_hdr == NULL\", depth);\n\t\treturn -EIO;\n\t}", "\t/* try to insert block into found extent and return */\n\tif (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)\n\t\t&& ext4_can_extents_be_merged(inode, ex, newext)) {\n\t\text_debug(\"append [%d]%d block to %u:[%d]%d (from %llu)\\n\",\n\t\t\t ext4_ext_is_uninitialized(newext),\n\t\t\t ext4_ext_get_actual_len(newext),\n\t\t\t le32_to_cpu(ex->ee_block),\n\t\t\t ext4_ext_is_uninitialized(ex),\n\t\t\t ext4_ext_get_actual_len(ex),\n\t\t\t ext4_ext_pblock(ex));\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\treturn err;", "\t\t/*\n\t\t * ext4_can_extents_be_merged should have checked that either\n\t\t * both extents are uninitialized, or both aren't. Thus we\n\t\t * need to check only one of them here.\n\t\t */\n\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\tex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)\n\t\t\t\t\t+ ext4_ext_get_actual_len(newext));\n\t\tif (uninitialized)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\teh = path[depth].p_hdr;\n\t\tnearex = ex;\n\t\tgoto merge;\n\t}", "\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\tif (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))\n\t\tgoto has_space;", "\t/* probably next leaf has space for us? */\n\tfex = EXT_LAST_EXTENT(eh);\n\tnext = EXT_MAX_BLOCKS;\n\tif (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))\n\t\tnext = ext4_ext_next_leaf_block(path);\n\tif (next != EXT_MAX_BLOCKS) {\n\t\text_debug(\"next leaf block - %u\\n\", next);\n\t\tBUG_ON(npath != NULL);\n\t\tnpath = ext4_ext_find_extent(inode, next, NULL);\n\t\tif (IS_ERR(npath))\n\t\t\treturn PTR_ERR(npath);\n\t\tBUG_ON(npath->p_depth != path->p_depth);\n\t\teh = npath[depth].p_hdr;\n\t\tif (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {\n\t\t\text_debug(\"next leaf isn't full(%d)\\n\",\n\t\t\t\t le16_to_cpu(eh->eh_entries));\n\t\t\tpath = npath;\n\t\t\tgoto has_space;\n\t\t}\n\t\text_debug(\"next leaf has no free space(%d,%d)\\n\",\n\t\t\t le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));\n\t}", "\t/*\n\t * There is no free space in the found leaf.\n\t * We're gonna add a new leaf in the tree.\n\t */\n\tif (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)\n\t\tflags = EXT4_MB_USE_ROOT_BLOCKS;\n\terr = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);\n\tif (err)\n\t\tgoto cleanup;\n\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;", "has_space:\n\tnearex = path[depth].p_ext;", "\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto cleanup;", "\tif (!nearex) {\n\t\t/* there is no extent in this leaf, create first one */\n\t\text_debug(\"first extent in the leaf: %u:%llu:[%d]%d\\n\",\n\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\text4_ext_pblock(newext),\n\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\text4_ext_get_actual_len(newext));\n\t\tnearex = EXT_FIRST_EXTENT(eh);\n\t} else {\n\t\tif (le32_to_cpu(newext->ee_block)\n\t\t\t > le32_to_cpu(nearex->ee_block)) {\n\t\t\t/* Insert after */\n\t\t\text_debug(\"insert %u:%llu:[%d]%d before: \"\n\t\t\t\t\t\"nearest %p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text4_ext_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tnearex);\n\t\t\tnearex++;\n\t\t} else {\n\t\t\t/* Insert before */\n\t\t\tBUG_ON(newext->ee_block == nearex->ee_block);\n\t\t\text_debug(\"insert %u:%llu:[%d]%d after: \"\n\t\t\t\t\t\"nearest %p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text4_ext_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tnearex);\n\t\t}\n\t\tlen = EXT_LAST_EXTENT(eh) - nearex + 1;\n\t\tif (len > 0) {\n\t\t\text_debug(\"insert %u:%llu:[%d]%d: \"\n\t\t\t\t\t\"move %d extents from 0x%p to 0x%p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text4_ext_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tlen, nearex, nearex + 1);\n\t\t\tmemmove(nearex + 1, nearex,\n\t\t\t\tlen * sizeof(struct ext4_extent));\n\t\t}\n\t}", "\tle16_add_cpu(&eh->eh_entries, 1);\n\tpath[depth].p_ext = nearex;\n\tnearex->ee_block = newext->ee_block;\n\text4_ext_store_pblock(nearex, ext4_ext_pblock(newext));\n\tnearex->ee_len = newext->ee_len;", "merge:\n\t/* try to merge extents */\n\tif (!(flag & EXT4_GET_BLOCKS_PRE_IO))\n\t\text4_ext_try_to_merge(handle, inode, path, nearex);", "\n\t/* time to correct all indexes above */\n\terr = ext4_ext_correct_indexes(handle, inode, path);\n\tif (err)\n\t\tgoto cleanup;", "\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);", "cleanup:\n\tif (npath) {\n\t\text4_ext_drop_refs(npath);\n\t\tkfree(npath);\n\t}\n\text4_ext_invalidate_cache(inode);\n\treturn err;\n}", "static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,\n\t\t\t ext4_lblk_t num, ext_prepare_callback func,\n\t\t\t void *cbdata)\n{\n\tstruct ext4_ext_path *path = NULL;\n\tstruct ext4_ext_cache cbex;\n\tstruct ext4_extent *ex;\n\text4_lblk_t next, start = 0, end = 0;\n\text4_lblk_t last = block + num;\n\tint depth, exists, err = 0;", "\tBUG_ON(func == NULL);\n\tBUG_ON(inode == NULL);", "\twhile (block < last && block != EXT_MAX_BLOCKS) {\n\t\tnum = last - block;\n\t\t/* find extent for this block */\n\t\tdown_read(&EXT4_I(inode)->i_data_sem);\n\t\tpath = ext4_ext_find_extent(inode, block, path);\n\t\tup_read(&EXT4_I(inode)->i_data_sem);\n\t\tif (IS_ERR(path)) {\n\t\t\terr = PTR_ERR(path);\n\t\t\tpath = NULL;\n\t\t\tbreak;\n\t\t}", "\t\tdepth = ext_depth(inode);\n\t\tif (unlikely(path[depth].p_hdr == NULL)) {\n\t\t\tEXT4_ERROR_INODE(inode, \"path[%d].p_hdr == NULL\", depth);\n\t\t\terr = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tex = path[depth].p_ext;\n\t\tnext = ext4_ext_next_allocated_block(path);", "\t\texists = 0;\n\t\tif (!ex) {\n\t\t\t/* there is no extent yet, so try to allocate\n\t\t\t * all requested space */\n\t\t\tstart = block;\n\t\t\tend = block + num;\n\t\t} else if (le32_to_cpu(ex->ee_block) > block) {\n\t\t\t/* need to allocate space before found extent */\n\t\t\tstart = block;\n\t\t\tend = le32_to_cpu(ex->ee_block);\n\t\t\tif (block + num < end)\n\t\t\t\tend = block + num;\n\t\t} else if (block >= le32_to_cpu(ex->ee_block)\n\t\t\t\t\t+ ext4_ext_get_actual_len(ex)) {\n\t\t\t/* need to allocate space after found extent */\n\t\t\tstart = block;\n\t\t\tend = block + num;\n\t\t\tif (end >= next)\n\t\t\t\tend = next;\n\t\t} else if (block >= le32_to_cpu(ex->ee_block)) {\n\t\t\t/*\n\t\t\t * some part of requested space is covered\n\t\t\t * by found extent\n\t\t\t */\n\t\t\tstart = block;\n\t\t\tend = le32_to_cpu(ex->ee_block)\n\t\t\t\t+ ext4_ext_get_actual_len(ex);\n\t\t\tif (block + num < end)\n\t\t\t\tend = block + num;\n\t\t\texists = 1;\n\t\t} else {\n\t\t\tBUG();\n\t\t}\n\t\tBUG_ON(end <= start);", "\t\tif (!exists) {\n\t\t\tcbex.ec_block = start;\n\t\t\tcbex.ec_len = end - start;\n\t\t\tcbex.ec_start = 0;\n\t\t} else {\n\t\t\tcbex.ec_block = le32_to_cpu(ex->ee_block);\n\t\t\tcbex.ec_len = ext4_ext_get_actual_len(ex);\n\t\t\tcbex.ec_start = ext4_ext_pblock(ex);\n\t\t}", "\t\tif (unlikely(cbex.ec_len == 0)) {\n\t\t\tEXT4_ERROR_INODE(inode, \"cbex.ec_len == 0\");\n\t\t\terr = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\terr = func(inode, next, &cbex, ex, cbdata);\n\t\text4_ext_drop_refs(path);", "\t\tif (err < 0)\n\t\t\tbreak;", "\t\tif (err == EXT_REPEAT)\n\t\t\tcontinue;\n\t\telse if (err == EXT_BREAK) {\n\t\t\terr = 0;\n\t\t\tbreak;\n\t\t}", "\t\tif (ext_depth(inode) != depth) {\n\t\t\t/* depth was changed. we have to realloc path */\n\t\t\tkfree(path);\n\t\t\tpath = NULL;\n\t\t}", "\t\tblock = cbex.ec_block + cbex.ec_len;\n\t}", "\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}", "\treturn err;\n}", "static void\next4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,\n\t\t\t__u32 len, ext4_fsblk_t start)\n{\n\tstruct ext4_ext_cache *cex;\n\tBUG_ON(len == 0);\n\tspin_lock(&EXT4_I(inode)->i_block_reservation_lock);\n\ttrace_ext4_ext_put_in_cache(inode, block, len, start);\n\tcex = &EXT4_I(inode)->i_cached_extent;\n\tcex->ec_block = block;\n\tcex->ec_len = len;\n\tcex->ec_start = start;\n\tspin_unlock(&EXT4_I(inode)->i_block_reservation_lock);\n}", "/*\n * ext4_ext_put_gap_in_cache:\n * calculate boundaries of the gap that the requested block fits into\n * and cache this gap\n */\nstatic void\next4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,\n\t\t\t\text4_lblk_t block)\n{\n\tint depth = ext_depth(inode);\n\tunsigned long len;\n\text4_lblk_t lblock;\n\tstruct ext4_extent *ex;", "\tex = path[depth].p_ext;\n\tif (ex == NULL) {\n\t\t/* there is no extent yet, so gap is [0;-] */\n\t\tlblock = 0;\n\t\tlen = EXT_MAX_BLOCKS;\n\t\text_debug(\"cache gap(whole file):\");\n\t} else if (block < le32_to_cpu(ex->ee_block)) {\n\t\tlblock = block;\n\t\tlen = le32_to_cpu(ex->ee_block) - block;\n\t\text_debug(\"cache gap(before): %u [%u:%u]\",\n\t\t\t\tblock,\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\t ext4_ext_get_actual_len(ex));\n\t} else if (block >= le32_to_cpu(ex->ee_block)\n\t\t\t+ ext4_ext_get_actual_len(ex)) {\n\t\text4_lblk_t next;\n\t\tlblock = le32_to_cpu(ex->ee_block)\n\t\t\t+ ext4_ext_get_actual_len(ex);", "\t\tnext = ext4_ext_next_allocated_block(path);\n\t\text_debug(\"cache gap(after): [%u:%u] %u\",\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\text4_ext_get_actual_len(ex),\n\t\t\t\tblock);\n\t\tBUG_ON(next == lblock);\n\t\tlen = next - lblock;\n\t} else {\n\t\tlblock = len = 0;\n\t\tBUG();\n\t}", "\text_debug(\" -> %u:%lu\\n\", lblock, len);\n\text4_ext_put_in_cache(inode, lblock, len, 0);\n}", "/*\n * ext4_ext_in_cache()\n * Checks to see if the given block is in the cache.\n * If it is, the cached extent is stored in the given\n * cache extent pointer.\n *\n * @inode: The files inode\n * @block: The block to look for in the cache\n * @ex: Pointer where the cached extent will be stored\n * if it contains block\n *\n * Return 0 if cache is invalid; 1 if the cache is valid\n */\nstatic int\next4_ext_in_cache(struct inode *inode, ext4_lblk_t block,\n\t\t struct ext4_extent *ex)\n{\n\tstruct ext4_ext_cache *cex;\n\tstruct ext4_sb_info *sbi;\n\tint ret = 0;", "\t/*\n\t * We borrow i_block_reservation_lock to protect i_cached_extent\n\t */\n\tspin_lock(&EXT4_I(inode)->i_block_reservation_lock);\n\tcex = &EXT4_I(inode)->i_cached_extent;\n\tsbi = EXT4_SB(inode->i_sb);", "\t/* has cache valid data? */\n\tif (cex->ec_len == 0)\n\t\tgoto errout;", "\tif (in_range(block, cex->ec_block, cex->ec_len)) {\n\t\tex->ee_block = cpu_to_le32(cex->ec_block);\n\t\text4_ext_store_pblock(ex, cex->ec_start);\n\t\tex->ee_len = cpu_to_le16(cex->ec_len);\n\t\text_debug(\"%u cached by %u:%u:%llu\\n\",\n\t\t\t\tblock,\n\t\t\t\tcex->ec_block, cex->ec_len, cex->ec_start);\n\t\tret = 1;\n\t}\nerrout:\n\ttrace_ext4_ext_in_cache(inode, block, ret);\n\tspin_unlock(&EXT4_I(inode)->i_block_reservation_lock);\n\treturn ret;\n}", "/*\n * ext4_ext_rm_idx:\n * removes index from the index block.\n */\nstatic int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_ext_path *path)\n{\n\tint err;\n\text4_fsblk_t leaf;", "\t/* free index block */\n\tpath--;\n\tleaf = ext4_idx_pblock(path->p_idx);\n\tif (unlikely(path->p_hdr->eh_entries == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"path->p_hdr->eh_entries == 0\");\n\t\treturn -EIO;\n\t}\n\terr = ext4_ext_get_access(handle, inode, path);\n\tif (err)\n\t\treturn err;", "\tif (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {\n\t\tint len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;\n\t\tlen *= sizeof(struct ext4_extent_idx);\n\t\tmemmove(path->p_idx, path->p_idx + 1, len);\n\t}", "\tle16_add_cpu(&path->p_hdr->eh_entries, -1);\n\terr = ext4_ext_dirty(handle, inode, path);\n\tif (err)\n\t\treturn err;\n\text_debug(\"index is empty, remove it, free block %llu\\n\", leaf);\n\ttrace_ext4_ext_rm_idx(inode, leaf);", "\text4_free_blocks(handle, inode, NULL, leaf, 1,\n\t\t\t EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);\n\treturn err;\n}", "/*\n * ext4_ext_calc_credits_for_single_extent:\n * This routine returns max. credits that needed to insert an extent\n * to the extent tree.\n * When pass the actual path, the caller should calculate credits\n * under i_data_sem.\n */\nint ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,\n\t\t\t\t\t\tstruct ext4_ext_path *path)\n{\n\tif (path) {\n\t\tint depth = ext_depth(inode);\n\t\tint ret = 0;", "\t\t/* probably there is space in leaf? */\n\t\tif (le16_to_cpu(path[depth].p_hdr->eh_entries)\n\t\t\t\t< le16_to_cpu(path[depth].p_hdr->eh_max)) {", "\t\t\t/*\n\t\t\t * There are some space in the leaf tree, no\n\t\t\t * need to account for leaf block credit\n\t\t\t *\n\t\t\t * bitmaps and block group descriptor blocks\n\t\t\t * and other metadata blocks still need to be\n\t\t\t * accounted.\n\t\t\t */\n\t\t\t/* 1 bitmap, 1 block group descriptor */\n\t\t\tret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);\n\t\t\treturn ret;\n\t\t}\n\t}", "\treturn ext4_chunk_trans_blocks(inode, nrblocks);\n}", "/*\n * How many index/leaf blocks need to change/allocate to modify nrblocks?\n *\n * if nrblocks are fit in a single extent (chunk flag is 1), then\n * in the worse case, each tree level index/leaf need to be changed\n * if the tree split due to insert a new extent, then the old tree\n * index/leaf need to be updated too\n *\n * If the nrblocks are discontiguous, they could cause\n * the whole tree split more than once, but this is really rare.\n */\nint ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)\n{\n\tint index;\n\tint depth = ext_depth(inode);", "\tif (chunk)\n\t\tindex = depth * 2;\n\telse\n\t\tindex = depth * 3;", "\treturn index;\n}", "static int ext4_remove_blocks(handle_t *handle, struct inode *inode,\n\t\t\t struct ext4_extent *ex,\n\t\t\t ext4_fsblk_t *partial_cluster,\n\t\t\t ext4_lblk_t from, ext4_lblk_t to)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\tunsigned short ee_len = ext4_ext_get_actual_len(ex);\n\text4_fsblk_t pblk;\n\tint flags = 0;", "\tif (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))\n\t\tflags |= EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;\n\telse if (ext4_should_journal_data(inode))\n\t\tflags |= EXT4_FREE_BLOCKS_FORGET;", "\t/*\n\t * For bigalloc file systems, we never free a partial cluster\n\t * at the beginning of the extent. Instead, we make a note\n\t * that we tried freeing the cluster, and check to see if we\n\t * need to free it on a subsequent call to ext4_remove_blocks,\n\t * or at the end of the ext4_truncate() operation.\n\t */\n\tflags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;", "\ttrace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);\n\t/*\n\t * If we have a partial cluster, and it's different from the\n\t * cluster of the last block, we need to explicitly free the\n\t * partial cluster here.\n\t */\n\tpblk = ext4_ext_pblock(ex) + ee_len - 1;\n\tif (*partial_cluster && (EXT4_B2C(sbi, pblk) != *partial_cluster)) {\n\t\text4_free_blocks(handle, inode, NULL,\n\t\t\t\t EXT4_C2B(sbi, *partial_cluster),\n\t\t\t\t sbi->s_cluster_ratio, flags);\n\t\t*partial_cluster = 0;\n\t}", "#ifdef EXTENTS_STATS\n\t{\n\t\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\t\tspin_lock(&sbi->s_ext_stats_lock);\n\t\tsbi->s_ext_blocks += ee_len;\n\t\tsbi->s_ext_extents++;\n\t\tif (ee_len < sbi->s_ext_min)\n\t\t\tsbi->s_ext_min = ee_len;\n\t\tif (ee_len > sbi->s_ext_max)\n\t\t\tsbi->s_ext_max = ee_len;\n\t\tif (ext_depth(inode) > sbi->s_depth_max)\n\t\t\tsbi->s_depth_max = ext_depth(inode);\n\t\tspin_unlock(&sbi->s_ext_stats_lock);\n\t}\n#endif\n\tif (from >= le32_to_cpu(ex->ee_block)\n\t && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {\n\t\t/* tail removal */\n\t\text4_lblk_t num;", "\t\tnum = le32_to_cpu(ex->ee_block) + ee_len - from;\n\t\tpblk = ext4_ext_pblock(ex) + ee_len - num;\n\t\text_debug(\"free last %u blocks starting %llu\\n\", num, pblk);\n\t\text4_free_blocks(handle, inode, NULL, pblk, num, flags);\n\t\t/*\n\t\t * If the block range to be freed didn't start at the\n\t\t * beginning of a cluster, and we removed the entire\n\t\t * extent, save the partial cluster here, since we\n\t\t * might need to delete if we determine that the\n\t\t * truncate operation has removed all of the blocks in\n\t\t * the cluster.\n\t\t */\n\t\tif (pblk & (sbi->s_cluster_ratio - 1) &&\n\t\t (ee_len == num))\n\t\t\t*partial_cluster = EXT4_B2C(sbi, pblk);\n\t\telse\n\t\t\t*partial_cluster = 0;\n\t} else if (from == le32_to_cpu(ex->ee_block)\n\t\t && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {\n\t\t/* head removal */\n\t\text4_lblk_t num;\n\t\text4_fsblk_t start;", "\t\tnum = to - from;\n\t\tstart = ext4_ext_pblock(ex);", "\t\text_debug(\"free first %u blocks starting %llu\\n\", num, start);\n\t\text4_free_blocks(handle, inode, NULL, start, num, flags);", "\t} else {\n\t\tprintk(KERN_INFO \"strange request: removal(2) \"\n\t\t\t\t\"%u-%u from %u:%u\\n\",\n\t\t\t\tfrom, to, le32_to_cpu(ex->ee_block), ee_len);\n\t}\n\treturn 0;\n}", "\n/*\n * ext4_ext_rm_leaf() Removes the extents associated with the\n * blocks appearing between \"start\" and \"end\", and splits the extents\n * if \"start\" and \"end\" appear in the same extent\n *\n * @handle: The journal handle\n * @inode: The files inode\n * @path: The path to the leaf\n * @start: The first block to remove\n * @end: The last block to remove\n */\nstatic int\next4_ext_rm_leaf(handle_t *handle, struct inode *inode,\n\t\t struct ext4_ext_path *path, ext4_fsblk_t *partial_cluster,\n\t\t ext4_lblk_t start, ext4_lblk_t end)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\tint err = 0, correct_index = 0;\n\tint depth = ext_depth(inode), credits;\n\tstruct ext4_extent_header *eh;\n\text4_lblk_t a, b;\n\tunsigned num;\n\text4_lblk_t ex_ee_block;\n\tunsigned short ex_ee_len;\n\tunsigned uninitialized = 0;\n\tstruct ext4_extent *ex;", "\t/* the header must be checked already in ext4_ext_remove_space() */\n\text_debug(\"truncate since %u in leaf to %u\\n\", start, end);\n\tif (!path[depth].p_hdr)\n\t\tpath[depth].p_hdr = ext_block_hdr(path[depth].p_bh);\n\teh = path[depth].p_hdr;\n\tif (unlikely(path[depth].p_hdr == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path[%d].p_hdr == NULL\", depth);\n\t\treturn -EIO;\n\t}\n\t/* find where to start removing */\n\tex = EXT_LAST_EXTENT(eh);", "\tex_ee_block = le32_to_cpu(ex->ee_block);\n\tex_ee_len = ext4_ext_get_actual_len(ex);", "\ttrace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);", "\twhile (ex >= EXT_FIRST_EXTENT(eh) &&\n\t\t\tex_ee_block + ex_ee_len > start) {", "\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\telse\n\t\t\tuninitialized = 0;", "\t\text_debug(\"remove ext %u:[%d]%d\\n\", ex_ee_block,\n\t\t\t uninitialized, ex_ee_len);\n\t\tpath[depth].p_ext = ex;", "\t\ta = ex_ee_block > start ? ex_ee_block : start;\n\t\tb = ex_ee_block+ex_ee_len - 1 < end ?\n\t\t\tex_ee_block+ex_ee_len - 1 : end;", "\t\text_debug(\" border %u:%u\\n\", a, b);", "\t\t/* If this extent is beyond the end of the hole, skip it */\n\t\tif (end < ex_ee_block) {\n\t\t\tex--;\n\t\t\tex_ee_block = le32_to_cpu(ex->ee_block);\n\t\t\tex_ee_len = ext4_ext_get_actual_len(ex);\n\t\t\tcontinue;\n\t\t} else if (b != ex_ee_block + ex_ee_len - 1) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"can not handle truncate %u:%u \"\n\t\t\t\t\t \"on extent %u:%u\",\n\t\t\t\t\t start, end, ex_ee_block,\n\t\t\t\t\t ex_ee_block + ex_ee_len - 1);\n\t\t\terr = -EIO;\n\t\t\tgoto out;\n\t\t} else if (a != ex_ee_block) {\n\t\t\t/* remove tail of the extent */\n\t\t\tnum = a - ex_ee_block;\n\t\t} else {\n\t\t\t/* remove whole extent: excellent! */\n\t\t\tnum = 0;\n\t\t}\n\t\t/*\n\t\t * 3 for leaf, sb, and inode plus 2 (bmap and group\n\t\t * descriptor) for each block group; assume two block\n\t\t * groups plus ex_ee_len/blocks_per_block_group for\n\t\t * the worst case\n\t\t */\n\t\tcredits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));\n\t\tif (ex == EXT_FIRST_EXTENT(eh)) {\n\t\t\tcorrect_index = 1;\n\t\t\tcredits += (ext_depth(inode)) + 1;\n\t\t}\n\t\tcredits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);", "\t\terr = ext4_ext_truncate_extend_restart(handle, inode, credits);\n\t\tif (err)\n\t\t\tgoto out;", "\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;", "\t\terr = ext4_remove_blocks(handle, inode, ex, partial_cluster,\n\t\t\t\t\t a, b);\n\t\tif (err)\n\t\t\tgoto out;", "\t\tif (num == 0)\n\t\t\t/* this extent is removed; mark slot entirely unused */\n\t\t\text4_ext_store_pblock(ex, 0);", "\t\tex->ee_len = cpu_to_le16(num);\n\t\t/*\n\t\t * Do not mark uninitialized if all the blocks in the\n\t\t * extent have been removed.\n\t\t */\n\t\tif (uninitialized && num)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\t/*\n\t\t * If the extent was completely released,\n\t\t * we need to remove it from the leaf\n\t\t */\n\t\tif (num == 0) {\n\t\t\tif (end != EXT_MAX_BLOCKS - 1) {\n\t\t\t\t/*\n\t\t\t\t * For hole punching, we need to scoot all the\n\t\t\t\t * extents up when an extent is removed so that\n\t\t\t\t * we dont have blank extents in the middle\n\t\t\t\t */\n\t\t\t\tmemmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *\n\t\t\t\t\tsizeof(struct ext4_extent));", "\t\t\t\t/* Now get rid of the one at the end */\n\t\t\t\tmemset(EXT_LAST_EXTENT(eh), 0,\n\t\t\t\t\tsizeof(struct ext4_extent));\n\t\t\t}\n\t\t\tle16_add_cpu(&eh->eh_entries, -1);\n\t\t} else\n\t\t\t*partial_cluster = 0;", "\t\terr = ext4_ext_dirty(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;", "\t\text_debug(\"new extent: %u:%u:%llu\\n\", ex_ee_block, num,\n\t\t\t\text4_ext_pblock(ex));\n\t\tex--;\n\t\tex_ee_block = le32_to_cpu(ex->ee_block);\n\t\tex_ee_len = ext4_ext_get_actual_len(ex);\n\t}", "\tif (correct_index && eh->eh_entries)\n\t\terr = ext4_ext_correct_indexes(handle, inode, path);", "\t/*\n\t * If there is still a entry in the leaf node, check to see if\n\t * it references the partial cluster. This is the only place\n\t * where it could; if it doesn't, we can free the cluster.\n\t */\n\tif (*partial_cluster && ex >= EXT_FIRST_EXTENT(eh) &&\n\t (EXT4_B2C(sbi, ext4_ext_pblock(ex) + ex_ee_len - 1) !=\n\t *partial_cluster)) {\n\t\tint flags = EXT4_FREE_BLOCKS_FORGET;", "\t\tif (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))\n\t\t\tflags |= EXT4_FREE_BLOCKS_METADATA;", "\t\text4_free_blocks(handle, inode, NULL,\n\t\t\t\t EXT4_C2B(sbi, *partial_cluster),\n\t\t\t\t sbi->s_cluster_ratio, flags);\n\t\t*partial_cluster = 0;\n\t}", "\t/* if this leaf is free, then we should\n\t * remove it from index block above */\n\tif (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)\n\t\terr = ext4_ext_rm_idx(handle, inode, path + depth);", "out:\n\treturn err;\n}", "/*\n * ext4_ext_more_to_rm:\n * returns 1 if current index has to be freed (even partial)\n */\nstatic int\next4_ext_more_to_rm(struct ext4_ext_path *path)\n{\n\tBUG_ON(path->p_idx == NULL);", "\tif (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))\n\t\treturn 0;", "\t/*\n\t * if truncate on deeper level happened, it wasn't partial,\n\t * so we have to consider current index for truncation\n\t */\n\tif (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)\n\t\treturn 0;\n\treturn 1;\n}", "static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,\n\t\t\t\t ext4_lblk_t end)\n{\n\tstruct super_block *sb = inode->i_sb;\n\tint depth = ext_depth(inode);\n\tstruct ext4_ext_path *path = NULL;\n\text4_fsblk_t partial_cluster = 0;\n\thandle_t *handle;\n\tint i = 0, err = 0;", "\text_debug(\"truncate since %u to %u\\n\", start, end);", "\t/* probably first extent we're gonna free will be last in block */\n\thandle = ext4_journal_start(inode, depth + 1);\n\tif (IS_ERR(handle))\n\t\treturn PTR_ERR(handle);", "again:\n\text4_ext_invalidate_cache(inode);", "\ttrace_ext4_ext_remove_space(inode, start, depth);", "\t/*\n\t * Check if we are removing extents inside the extent tree. If that\n\t * is the case, we are going to punch a hole inside the extent tree\n\t * so we have to check whether we need to split the extent covering\n\t * the last block to remove so we can easily remove the part of it\n\t * in ext4_ext_rm_leaf().\n\t */\n\tif (end < EXT_MAX_BLOCKS - 1) {\n\t\tstruct ext4_extent *ex;\n\t\text4_lblk_t ee_block;", "\t\t/* find extent for this block */\n\t\tpath = ext4_ext_find_extent(inode, end, NULL);\n\t\tif (IS_ERR(path)) {\n\t\t\text4_journal_stop(handle);\n\t\t\treturn PTR_ERR(path);\n\t\t}\n\t\tdepth = ext_depth(inode);\n\t\t/* Leaf not may not exist only if inode has no blocks at all */\n\t\tex = path[depth].p_ext;\n\t\tif (!ex) {\n\t\t\tif (depth) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t\t \"path[%d].p_hdr == NULL\",\n\t\t\t\t\t\t depth);\n\t\t\t\terr = -EIO;\n\t\t\t}\n\t\t\tgoto out;\n\t\t}", "\t\tee_block = le32_to_cpu(ex->ee_block);", "\t\t/*\n\t\t * See if the last block is inside the extent, if so split\n\t\t * the extent at 'end' block so we can easily remove the\n\t\t * tail of the first part of the split extent in\n\t\t * ext4_ext_rm_leaf().\n\t\t */\n\t\tif (end >= ee_block &&\n\t\t end < ee_block + ext4_ext_get_actual_len(ex) - 1) {\n\t\t\tint split_flag = 0;", "\t\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\t\tsplit_flag = EXT4_EXT_MARK_UNINIT1 |\n\t\t\t\t\t EXT4_EXT_MARK_UNINIT2;", "\t\t\t/*\n\t\t\t * Split the extent in two so that 'end' is the last\n\t\t\t * block in the first new extent\n\t\t\t */\n\t\t\terr = ext4_split_extent_at(handle, inode, path,\n\t\t\t\t\t\tend + 1, split_flag,\n\t\t\t\t\t\tEXT4_GET_BLOCKS_PRE_IO |\n\t\t\t\t\t\tEXT4_GET_BLOCKS_PUNCH_OUT_EXT);", "\t\t\tif (err < 0)\n\t\t\t\tgoto out;\n\t\t}\n\t}\n\t/*\n\t * We start scanning from right side, freeing all the blocks\n\t * after i_size and walking into the tree depth-wise.\n\t */\n\tdepth = ext_depth(inode);\n\tif (path) {\n\t\tint k = i = depth;\n\t\twhile (--k > 0)\n\t\t\tpath[k].p_block =\n\t\t\t\tle16_to_cpu(path[k].p_hdr->eh_entries)+1;\n\t} else {\n\t\tpath = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),\n\t\t\t GFP_NOFS);\n\t\tif (path == NULL) {\n\t\t\text4_journal_stop(handle);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tpath[0].p_depth = depth;\n\t\tpath[0].p_hdr = ext_inode_hdr(inode);\n\t\ti = 0;", "\t\tif (ext4_ext_check(inode, path[0].p_hdr, depth)) {\n\t\t\terr = -EIO;\n\t\t\tgoto out;\n\t\t}\n\t}\n\terr = 0;", "\twhile (i >= 0 && err == 0) {\n\t\tif (i == depth) {\n\t\t\t/* this is leaf block */\n\t\t\terr = ext4_ext_rm_leaf(handle, inode, path,\n\t\t\t\t\t &partial_cluster, start,\n\t\t\t\t\t end);\n\t\t\t/* root level has p_bh == NULL, brelse() eats this */\n\t\t\tbrelse(path[i].p_bh);\n\t\t\tpath[i].p_bh = NULL;\n\t\t\ti--;\n\t\t\tcontinue;\n\t\t}", "\t\t/* this is index block */\n\t\tif (!path[i].p_hdr) {\n\t\t\text_debug(\"initialize header\\n\");\n\t\t\tpath[i].p_hdr = ext_block_hdr(path[i].p_bh);\n\t\t}", "\t\tif (!path[i].p_idx) {\n\t\t\t/* this level hasn't been touched yet */\n\t\t\tpath[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);\n\t\t\tpath[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;\n\t\t\text_debug(\"init index ptr: hdr 0x%p, num %d\\n\",\n\t\t\t\t path[i].p_hdr,\n\t\t\t\t le16_to_cpu(path[i].p_hdr->eh_entries));\n\t\t} else {\n\t\t\t/* we were already here, see at next index */\n\t\t\tpath[i].p_idx--;\n\t\t}", "\t\text_debug(\"level %d - index, first 0x%p, cur 0x%p\\n\",\n\t\t\t\ti, EXT_FIRST_INDEX(path[i].p_hdr),\n\t\t\t\tpath[i].p_idx);\n\t\tif (ext4_ext_more_to_rm(path + i)) {\n\t\t\tstruct buffer_head *bh;\n\t\t\t/* go to the next level */\n\t\t\text_debug(\"move to level %d (block %llu)\\n\",\n\t\t\t\t i + 1, ext4_idx_pblock(path[i].p_idx));\n\t\t\tmemset(path + i + 1, 0, sizeof(*path));\n\t\t\tbh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));\n\t\t\tif (!bh) {\n\t\t\t\t/* should we reset i_size? */\n\t\t\t\terr = -EIO;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (WARN_ON(i + 1 > depth)) {\n\t\t\t\terr = -EIO;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ext4_ext_check_block(inode, ext_block_hdr(bh),\n\t\t\t\t\t\t\tdepth - i - 1, bh)) {\n\t\t\t\terr = -EIO;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpath[i + 1].p_bh = bh;", "\t\t\t/* save actual number of indexes since this\n\t\t\t * number is changed at the next iteration */\n\t\t\tpath[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);\n\t\t\ti++;\n\t\t} else {\n\t\t\t/* we finished processing this index, go up */\n\t\t\tif (path[i].p_hdr->eh_entries == 0 && i > 0) {\n\t\t\t\t/* index is empty, remove it;\n\t\t\t\t * handle must be already prepared by the\n\t\t\t\t * truncatei_leaf() */\n\t\t\t\terr = ext4_ext_rm_idx(handle, inode, path + i);\n\t\t\t}\n\t\t\t/* root level has p_bh == NULL, brelse() eats this */\n\t\t\tbrelse(path[i].p_bh);\n\t\t\tpath[i].p_bh = NULL;\n\t\t\ti--;\n\t\t\text_debug(\"return to level %d\\n\", i);\n\t\t}\n\t}", "\ttrace_ext4_ext_remove_space_done(inode, start, depth, partial_cluster,\n\t\t\tpath->p_hdr->eh_entries);", "\t/* If we still have something in the partial cluster and we have removed\n\t * even the first extent, then we should free the blocks in the partial\n\t * cluster as well. */\n\tif (partial_cluster && path->p_hdr->eh_entries == 0) {\n\t\tint flags = EXT4_FREE_BLOCKS_FORGET;", "\t\tif (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))\n\t\t\tflags |= EXT4_FREE_BLOCKS_METADATA;", "\t\text4_free_blocks(handle, inode, NULL,\n\t\t\t\t EXT4_C2B(EXT4_SB(sb), partial_cluster),\n\t\t\t\t EXT4_SB(sb)->s_cluster_ratio, flags);\n\t\tpartial_cluster = 0;\n\t}", "\t/* TODO: flexible tree reduction should be here */\n\tif (path->p_hdr->eh_entries == 0) {\n\t\t/*\n\t\t * truncate to zero freed all the tree,\n\t\t * so we need to correct eh_depth\n\t\t */\n\t\terr = ext4_ext_get_access(handle, inode, path);\n\t\tif (err == 0) {\n\t\t\text_inode_hdr(inode)->eh_depth = 0;\n\t\t\text_inode_hdr(inode)->eh_max =\n\t\t\t\tcpu_to_le16(ext4_ext_space_root(inode, 0));\n\t\t\terr = ext4_ext_dirty(handle, inode, path);\n\t\t}\n\t}\nout:\n\text4_ext_drop_refs(path);\n\tkfree(path);\n\tif (err == -EAGAIN) {\n\t\tpath = NULL;\n\t\tgoto again;\n\t}\n\text4_journal_stop(handle);", "\treturn err;\n}", "/*\n * called at mount time\n */\nvoid ext4_ext_init(struct super_block *sb)\n{\n\t/*\n\t * possible initialization would be here\n\t */", "\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {\n#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)\n\t\tprintk(KERN_INFO \"EXT4-fs: file extents enabled\"\n#ifdef AGGRESSIVE_TEST\n\t\t \", aggressive tests\"\n#endif\n#ifdef CHECK_BINSEARCH\n\t\t \", check binsearch\"\n#endif\n#ifdef EXTENTS_STATS\n\t\t \", stats\"\n#endif\n\t\t \"\\n\");\n#endif\n#ifdef EXTENTS_STATS\n\t\tspin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);\n\t\tEXT4_SB(sb)->s_ext_min = 1 << 30;\n\t\tEXT4_SB(sb)->s_ext_max = 0;\n#endif\n\t}\n}", "/*\n * called at umount time\n */\nvoid ext4_ext_release(struct super_block *sb)\n{\n\tif (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))\n\t\treturn;", "#ifdef EXTENTS_STATS\n\tif (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {\n\t\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\t\tprintk(KERN_ERR \"EXT4-fs: %lu blocks in %lu extents (%lu ave)\\n\",\n\t\t\tsbi->s_ext_blocks, sbi->s_ext_extents,\n\t\t\tsbi->s_ext_blocks / sbi->s_ext_extents);\n\t\tprintk(KERN_ERR \"EXT4-fs: extents: %lu min, %lu max, max depth %lu\\n\",\n\t\t\tsbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);\n\t}\n#endif\n}", "/* FIXME!! we need to try to merge to left or right after zero-out */\nstatic int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)\n{\n\text4_fsblk_t ee_pblock;\n\tunsigned int ee_len;\n\tint ret;", "\tee_len = ext4_ext_get_actual_len(ex);\n\tee_pblock = ext4_ext_pblock(ex);", "\tret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);\n\tif (ret > 0)\n\t\tret = 0;", "\treturn ret;\n}", "/*\n * ext4_split_extent_at() splits an extent at given block.\n *\n * @handle: the journal handle\n * @inode: the file inode\n * @path: the path to the extent\n * @split: the logical block where the extent is splitted.\n * @split_flags: indicates if the extent could be zeroout if split fails, and\n *\t\t the states(init or uninit) of new extents.\n * @flags: flags used to insert new extent to extent tree.\n *\n *\n * Splits extent [a, b] into two extents [a, @split) and [@split, b], states\n * of which are deterimined by split_flag.\n *\n * There are two cases:\n * a> the extent are splitted into two extent.\n * b> split is not needed, and just mark the extent.\n *\n * return 0 on success.\n */\nstatic int ext4_split_extent_at(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t split,\n\t\t\t int split_flag,\n\t\t\t int flags)\n{\n\text4_fsblk_t newblock;\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex, newex, orig_ex;\n\tstruct ext4_extent *ex2 = NULL;\n\tunsigned int ee_len, depth;\n\tint err = 0;\n", "", "\text_debug(\"ext4_split_extents_at: inode %lu, logical\"\n\t\t\"block %llu\\n\", inode->i_ino, (unsigned long long)split);", "\text4_ext_show_leaf(inode, path);", "\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tnewblock = split - ee_block + ext4_ext_pblock(ex);", "\tBUG_ON(split < ee_block || split >= (ee_block + ee_len));", "\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;", "\tif (split == ee_block) {\n\t\t/*\n\t\t * case b: block @split is the block that the extent begins with\n\t\t * then we just change the state of the extent, and splitting\n\t\t * is not needed.\n\t\t */\n\t\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\telse\n\t\t\text4_ext_mark_initialized(ex);", "\t\tif (!(flags & EXT4_GET_BLOCKS_PRE_IO))\n\t\t\text4_ext_try_to_merge(handle, inode, path, ex);", "\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t}", "\t/* case a */\n\tmemcpy(&orig_ex, ex, sizeof(orig_ex));\n\tex->ee_len = cpu_to_le16(split - ee_block);\n\tif (split_flag & EXT4_EXT_MARK_UNINIT1)\n\t\text4_ext_mark_uninitialized(ex);", "\t/*\n\t * path may lead to new leaf, not to original leaf any more\n\t * after ext4_ext_insert_extent() returns,\n\t */\n\terr = ext4_ext_dirty(handle, inode, path + depth);\n\tif (err)\n\t\tgoto fix_extent_len;", "\tex2 = &newex;\n\tex2->ee_block = cpu_to_le32(split);\n\tex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));\n\text4_ext_store_pblock(ex2, newblock);\n\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\text4_ext_mark_uninitialized(ex2);", "\terr = ext4_ext_insert_extent(handle, inode, path, &newex, flags);\n\tif (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {", "\t\terr = ext4_ext_zeroout(inode, &orig_ex);", "\t\tif (err)\n\t\t\tgoto fix_extent_len;\n\t\t/* update the extent length and mark as initialized */\n\t\tex->ee_len = cpu_to_le16(ee_len);\n\t\text4_ext_try_to_merge(handle, inode, path, ex);\n\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t} else if (err)\n\t\tgoto fix_extent_len;", "out:\n\text4_ext_show_leaf(inode, path);\n\treturn err;", "fix_extent_len:\n\tex->ee_len = orig_ex.ee_len;\n\text4_ext_dirty(handle, inode, path + depth);\n\treturn err;\n}", "/*\n * ext4_split_extents() splits an extent and mark extent which is covered\n * by @map as split_flags indicates\n *\n * It may result in splitting the extent into multiple extents (upto three)\n * There are three possibilities:\n * a> There is no split required\n * b> Splits in two extents: Split is happening at either end of the extent\n * c> Splits in three extents: Somone is splitting in middle of the extent\n *\n */\nstatic int ext4_split_extent(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t struct ext4_map_blocks *map,\n\t\t\t int split_flag,\n\t\t\t int flags)\n{\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex;\n\tunsigned int ee_len, depth;\n\tint err = 0;\n\tint uninitialized;\n\tint split_flag1, flags1;", "\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tuninitialized = ext4_ext_is_uninitialized(ex);", "\tif (map->m_lblk + map->m_len < ee_block + ee_len) {", "\t\tsplit_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?\n\t\t\t EXT4_EXT_MAY_ZEROOUT : 0;", "\t\tflags1 = flags | EXT4_GET_BLOCKS_PRE_IO;\n\t\tif (uninitialized)\n\t\t\tsplit_flag1 |= EXT4_EXT_MARK_UNINIT1 |\n\t\t\t\t EXT4_EXT_MARK_UNINIT2;", "", "\t\terr = ext4_split_extent_at(handle, inode, path,\n\t\t\t\tmap->m_lblk + map->m_len, split_flag1, flags1);\n\t\tif (err)\n\t\t\tgoto out;\n\t}", "\text4_ext_drop_refs(path);\n\tpath = ext4_ext_find_extent(inode, map->m_lblk, path);\n\tif (IS_ERR(path))\n\t\treturn PTR_ERR(path);", "\tif (map->m_lblk >= ee_block) {", "\t\tsplit_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT ?\n\t\t\t EXT4_EXT_MAY_ZEROOUT : 0;", "\t\tif (uninitialized)\n\t\t\tsplit_flag1 |= EXT4_EXT_MARK_UNINIT1;\n\t\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\t\tsplit_flag1 |= EXT4_EXT_MARK_UNINIT2;\n\t\terr = ext4_split_extent_at(handle, inode, path,\n\t\t\t\tmap->m_lblk, split_flag1, flags);\n\t\tif (err)\n\t\t\tgoto out;\n\t}", "\text4_ext_show_leaf(inode, path);\nout:\n\treturn err ? err : map->m_len;\n}", "/*\n * This function is called by ext4_ext_map_blocks() if someone tries to write\n * to an uninitialized extent. It may result in splitting the uninitialized\n * extent into multiple extents (up to three - one initialized and two\n * uninitialized).\n * There are three possibilities:\n * a> There is no split required: Entire extent should be initialized\n * b> Splits in two extents: Write is happening at either end of the extent\n * c> Splits in three extents: Somone is writing in middle of the extent\n *\n * Pre-conditions:\n * - The extent pointed to by 'path' is uninitialized.\n * - The extent pointed to by 'path' contains a superset\n * of the logical span [map->m_lblk, map->m_lblk + map->m_len).\n *\n * Post-conditions on success:\n * - the returned value is the number of blocks beyond map->l_lblk\n * that are allocated and initialized.\n * It is guaranteed to be >= map->m_len.\n */\nstatic int ext4_ext_convert_to_initialized(handle_t *handle,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t struct ext4_map_blocks *map,\n\t\t\t\t\t struct ext4_ext_path *path)\n{\n\tstruct ext4_sb_info *sbi;\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_map_blocks split_map;\n\tstruct ext4_extent zero_ex;\n\tstruct ext4_extent *ex;\n\text4_lblk_t ee_block, eof_block;\n\tunsigned int ee_len, depth;\n\tint allocated, max_zeroout = 0;\n\tint err = 0;\n\tint split_flag = 0;", "\text_debug(\"ext4_ext_convert_to_initialized: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,\n\t\t(unsigned long long)map->m_lblk, map->m_len);", "\tsbi = EXT4_SB(inode->i_sb);\n\teof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>\n\t\tinode->i_sb->s_blocksize_bits;\n\tif (eof_block < map->m_lblk + map->m_len)\n\t\teof_block = map->m_lblk + map->m_len;", "\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tallocated = ee_len - (map->m_lblk - ee_block);", "\ttrace_ext4_ext_convert_to_initialized_enter(inode, map, ex);", "\t/* Pre-conditions */\n\tBUG_ON(!ext4_ext_is_uninitialized(ex));\n\tBUG_ON(!in_range(map->m_lblk, ee_block, ee_len));", "\t/*\n\t * Attempt to transfer newly initialized blocks from the currently\n\t * uninitialized extent to its left neighbor. This is much cheaper\n\t * than an insertion followed by a merge as those involve costly\n\t * memmove() calls. This is the common case in steady state for\n\t * workloads doing fallocate(FALLOC_FL_KEEP_SIZE) followed by append\n\t * writes.\n\t *\n\t * Limitations of the current logic:\n\t * - L1: we only deal with writes at the start of the extent.\n\t * The approach could be extended to writes at the end\n\t * of the extent but this scenario was deemed less common.\n\t * - L2: we do not deal with writes covering the whole extent.\n\t * This would require removing the extent if the transfer\n\t * is possible.\n\t * - L3: we only attempt to merge with an extent stored in the\n\t * same extent tree node.\n\t */\n\tif ((map->m_lblk == ee_block) &&\t/*L1*/\n\t\t(map->m_len < ee_len) &&\t/*L2*/\n\t\t(ex > EXT_FIRST_EXTENT(eh))) {\t/*L3*/\n\t\tstruct ext4_extent *prev_ex;\n\t\text4_lblk_t prev_lblk;\n\t\text4_fsblk_t prev_pblk, ee_pblk;\n\t\tunsigned int prev_len, write_len;", "\t\tprev_ex = ex - 1;\n\t\tprev_lblk = le32_to_cpu(prev_ex->ee_block);\n\t\tprev_len = ext4_ext_get_actual_len(prev_ex);\n\t\tprev_pblk = ext4_ext_pblock(prev_ex);\n\t\tee_pblk = ext4_ext_pblock(ex);\n\t\twrite_len = map->m_len;", "\t\t/*\n\t\t * A transfer of blocks from 'ex' to 'prev_ex' is allowed\n\t\t * upon those conditions:\n\t\t * - C1: prev_ex is initialized,\n\t\t * - C2: prev_ex is logically abutting ex,\n\t\t * - C3: prev_ex is physically abutting ex,\n\t\t * - C4: prev_ex can receive the additional blocks without\n\t\t * overflowing the (initialized) length limit.\n\t\t */\n\t\tif ((!ext4_ext_is_uninitialized(prev_ex)) &&\t\t/*C1*/\n\t\t\t((prev_lblk + prev_len) == ee_block) &&\t\t/*C2*/\n\t\t\t((prev_pblk + prev_len) == ee_pblk) &&\t\t/*C3*/\n\t\t\t(prev_len < (EXT_INIT_MAX_LEN - write_len))) {\t/*C4*/\n\t\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\t\tif (err)\n\t\t\t\tgoto out;", "\t\t\ttrace_ext4_ext_convert_to_initialized_fastpath(inode,\n\t\t\t\tmap, ex, prev_ex);", "\t\t\t/* Shift the start of ex by 'write_len' blocks */\n\t\t\tex->ee_block = cpu_to_le32(ee_block + write_len);\n\t\t\text4_ext_store_pblock(ex, ee_pblk + write_len);\n\t\t\tex->ee_len = cpu_to_le16(ee_len - write_len);\n\t\t\text4_ext_mark_uninitialized(ex); /* Restore the flag */", "\t\t\t/* Extend prev_ex by 'write_len' blocks */\n\t\t\tprev_ex->ee_len = cpu_to_le16(prev_len + write_len);", "\t\t\t/* Mark the block containing both extents as dirty */\n\t\t\text4_ext_dirty(handle, inode, path + depth);", "\t\t\t/* Update path to point to the right extent */\n\t\t\tpath[depth].p_ext = prev_ex;", "\t\t\t/* Result: number of initialized blocks past m_lblk */\n\t\t\tallocated = write_len;\n\t\t\tgoto out;\n\t\t}\n\t}", "\tWARN_ON(map->m_lblk < ee_block);\n\t/*\n\t * It is safe to convert extent to initialized via explicit\n\t * zeroout only if extent is fully insde i_size or new_size.\n\t */\n\tsplit_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;", "\tif (EXT4_EXT_MAY_ZEROOUT & split_flag)\n\t\tmax_zeroout = sbi->s_extent_max_zeroout_kb >>\n\t\t\tinode->i_sb->s_blocksize_bits;", "\t/* If extent is less than s_max_zeroout_kb, zeroout directly */\n\tif (max_zeroout && (ee_len <= max_zeroout)) {\n\t\terr = ext4_ext_zeroout(inode, ex);\n\t\tif (err)\n\t\t\tgoto out;", "\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;\n\t\text4_ext_mark_initialized(ex);\n\t\text4_ext_try_to_merge(handle, inode, path, ex);\n\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t}", "\t/*\n\t * four cases:\n\t * 1. split the extent into three extents.\n\t * 2. split the extent into two extents, zeroout the first half.\n\t * 3. split the extent into two extents, zeroout the second half.\n\t * 4. split the extent into two extents with out zeroout.\n\t */\n\tsplit_map.m_lblk = map->m_lblk;\n\tsplit_map.m_len = map->m_len;", "\tif (max_zeroout && (allocated > map->m_len)) {\n\t\tif (allocated <= max_zeroout) {\n\t\t\t/* case 3 */\n\t\t\tzero_ex.ee_block =\n\t\t\t\t\t cpu_to_le32(map->m_lblk);\n\t\t\tzero_ex.ee_len = cpu_to_le16(allocated);\n\t\t\text4_ext_store_pblock(&zero_ex,\n\t\t\t\text4_ext_pblock(ex) + map->m_lblk - ee_block);\n\t\t\terr = ext4_ext_zeroout(inode, &zero_ex);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t\tsplit_map.m_lblk = map->m_lblk;\n\t\t\tsplit_map.m_len = allocated;\n\t\t} else if (map->m_lblk - ee_block + map->m_len < max_zeroout) {\n\t\t\t/* case 2 */\n\t\t\tif (map->m_lblk != ee_block) {\n\t\t\t\tzero_ex.ee_block = ex->ee_block;\n\t\t\t\tzero_ex.ee_len = cpu_to_le16(map->m_lblk -\n\t\t\t\t\t\t\tee_block);\n\t\t\t\text4_ext_store_pblock(&zero_ex,\n\t\t\t\t\t\t ext4_ext_pblock(ex));\n\t\t\t\terr = ext4_ext_zeroout(inode, &zero_ex);\n\t\t\t\tif (err)\n\t\t\t\t\tgoto out;\n\t\t\t}", "\t\t\tsplit_map.m_lblk = ee_block;\n\t\t\tsplit_map.m_len = map->m_lblk - ee_block + map->m_len;\n\t\t\tallocated = map->m_len;\n\t\t}\n\t}", "\tallocated = ext4_split_extent(handle, inode, path,\n\t\t\t\t &split_map, split_flag, 0);\n\tif (allocated < 0)\n\t\terr = allocated;", "out:\n\treturn err ? err : allocated;\n}", "/*\n * This function is called by ext4_ext_map_blocks() from\n * ext4_get_blocks_dio_write() when DIO to write\n * to an uninitialized extent.\n *\n * Writing to an uninitialized extent may result in splitting the uninitialized\n * extent into multiple initialized/uninitialized extents (up to three)\n * There are three possibilities:\n * a> There is no split required: Entire extent should be uninitialized\n * b> Splits in two extents: Write is happening at either end of the extent\n * c> Splits in three extents: Somone is writing in middle of the extent\n *\n * One of more index blocks maybe needed if the extent tree grow after\n * the uninitialized extent split. To prevent ENOSPC occur at the IO\n * complete, we need to split the uninitialized extent before DIO submit\n * the IO. The uninitialized extent called at this time will be split\n * into three uninitialized extent(at most). After IO complete, the part\n * being filled will be convert to initialized by the end_io callback function\n * via ext4_convert_unwritten_extents().\n *\n * Returns the size of uninitialized extent to be written on success.\n */\nstatic int ext4_split_unwritten_extents(handle_t *handle,\n\t\t\t\t\tstruct inode *inode,\n\t\t\t\t\tstruct ext4_map_blocks *map,\n\t\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\t\tint flags)\n{\n\text4_lblk_t eof_block;\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex;\n\tunsigned int ee_len;\n\tint split_flag = 0, depth;", "\text_debug(\"ext4_split_unwritten_extents: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,\n\t\t(unsigned long long)map->m_lblk, map->m_len);", "\teof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>\n\t\tinode->i_sb->s_blocksize_bits;\n\tif (eof_block < map->m_lblk + map->m_len)\n\t\teof_block = map->m_lblk + map->m_len;\n\t/*\n\t * It is safe to convert extent to initialized via explicit\n\t * zeroout only if extent is fully insde i_size or new_size.\n\t */\n\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);", "\tsplit_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;\n\tsplit_flag |= EXT4_EXT_MARK_UNINIT2;", "", "\tflags |= EXT4_GET_BLOCKS_PRE_IO;\n\treturn ext4_split_extent(handle, inode, path, map, split_flag, flags);\n}", "static int ext4_convert_unwritten_extents_endio(handle_t *handle,", "\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t struct ext4_ext_path *path)", "{\n\tstruct ext4_extent *ex;", "", "\tint depth;\n\tint err = 0;", "\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;", "", "\n\text_debug(\"ext4_convert_unwritten_extents_endio: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,", "\t\t(unsigned long long)le32_to_cpu(ex->ee_block),\n\t\text4_ext_get_actual_len(ex));", "\n\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;\n\t/* first mark the extent as initialized */\n\text4_ext_mark_initialized(ex);", "\t/* note: ext4_ext_correct_indexes() isn't needed here because\n\t * borders are not changed\n\t */\n\text4_ext_try_to_merge(handle, inode, path, ex);", "\t/* Mark modified extent as dirty */\n\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\nout:\n\text4_ext_show_leaf(inode, path);\n\treturn err;\n}", "static void unmap_underlying_metadata_blocks(struct block_device *bdev,\n\t\t\tsector_t block, int count)\n{\n\tint i;\n\tfor (i = 0; i < count; i++)\n unmap_underlying_metadata(bdev, block + i);\n}", "/*\n * Handle EOFBLOCKS_FL flag, clearing it if necessary\n */\nstatic int check_eofblocks_fl(handle_t *handle, struct inode *inode,\n\t\t\t ext4_lblk_t lblk,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t unsigned int len)\n{\n\tint i, depth;\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *last_ex;", "\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))\n\t\treturn 0;", "\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;", "\t/*\n\t * We're going to remove EOFBLOCKS_FL entirely in future so we\n\t * do not care for this case anymore. Simply remove the flag\n\t * if there are no extents.\n\t */\n\tif (unlikely(!eh->eh_entries))\n\t\tgoto out;\n\tlast_ex = EXT_LAST_EXTENT(eh);\n\t/*\n\t * We should clear the EOFBLOCKS_FL flag if we are writing the\n\t * last block in the last extent in the file. We test this by\n\t * first checking to see if the caller to\n\t * ext4_ext_get_blocks() was interested in the last block (or\n\t * a block beyond the last block) in the current extent. If\n\t * this turns out to be false, we can bail out from this\n\t * function immediately.\n\t */\n\tif (lblk + len < le32_to_cpu(last_ex->ee_block) +\n\t ext4_ext_get_actual_len(last_ex))\n\t\treturn 0;\n\t/*\n\t * If the caller does appear to be planning to write at or\n\t * beyond the end of the current extent, we then test to see\n\t * if the current extent is the last extent in the file, by\n\t * checking to make sure it was reached via the rightmost node\n\t * at each level of the tree.\n\t */\n\tfor (i = depth-1; i >= 0; i--)\n\t\tif (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))\n\t\t\treturn 0;\nout:\n\text4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);\n\treturn ext4_mark_inode_dirty(handle, inode);\n}", "/**\n * ext4_find_delalloc_range: find delayed allocated block in the given range.\n *\n * Goes through the buffer heads in the range [lblk_start, lblk_end] and returns\n * whether there are any buffers marked for delayed allocation. It returns '1'\n * on the first delalloc'ed buffer head found. If no buffer head in the given\n * range is marked for delalloc, it returns 0.\n * lblk_start should always be <= lblk_end.\n * search_hint_reverse is to indicate that searching in reverse from lblk_end to\n * lblk_start might be more efficient (i.e., we will likely hit the delalloc'ed\n * block sooner). This is useful when blocks are truncated sequentially from\n * lblk_start towards lblk_end.\n */\nstatic int ext4_find_delalloc_range(struct inode *inode,\n\t\t\t\t ext4_lblk_t lblk_start,\n\t\t\t\t ext4_lblk_t lblk_end,\n\t\t\t\t int search_hint_reverse)\n{\n\tstruct address_space *mapping = inode->i_mapping;\n\tstruct buffer_head *head, *bh = NULL;\n\tstruct page *page;\n\text4_lblk_t i, pg_lblk;\n\tpgoff_t index;", "\tif (!test_opt(inode->i_sb, DELALLOC))\n\t\treturn 0;", "\t/* reverse search wont work if fs block size is less than page size */\n\tif (inode->i_blkbits < PAGE_CACHE_SHIFT)\n\t\tsearch_hint_reverse = 0;", "\tif (search_hint_reverse)\n\t\ti = lblk_end;\n\telse\n\t\ti = lblk_start;", "\tindex = i >> (PAGE_CACHE_SHIFT - inode->i_blkbits);", "\twhile ((i >= lblk_start) && (i <= lblk_end)) {\n\t\tpage = find_get_page(mapping, index);\n\t\tif (!page)\n\t\t\tgoto nextpage;", "\t\tif (!page_has_buffers(page))\n\t\t\tgoto nextpage;", "\t\thead = page_buffers(page);\n\t\tif (!head)\n\t\t\tgoto nextpage;", "\t\tbh = head;\n\t\tpg_lblk = index << (PAGE_CACHE_SHIFT -\n\t\t\t\t\t\tinode->i_blkbits);\n\t\tdo {\n\t\t\tif (unlikely(pg_lblk < lblk_start)) {\n\t\t\t\t/*\n\t\t\t\t * This is possible when fs block size is less\n\t\t\t\t * than page size and our cluster starts/ends in\n\t\t\t\t * middle of the page. So we need to skip the\n\t\t\t\t * initial few blocks till we reach the 'lblk'\n\t\t\t\t */\n\t\t\t\tpg_lblk++;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\t/* Check if the buffer is delayed allocated and that it\n\t\t\t * is not yet mapped. (when da-buffers are mapped during\n\t\t\t * their writeout, their da_mapped bit is set.)\n\t\t\t */\n\t\t\tif (buffer_delay(bh) && !buffer_da_mapped(bh)) {\n\t\t\t\tpage_cache_release(page);\n\t\t\t\ttrace_ext4_find_delalloc_range(inode,\n\t\t\t\t\t\tlblk_start, lblk_end,\n\t\t\t\t\t\tsearch_hint_reverse,\n\t\t\t\t\t\t1, i);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (search_hint_reverse)\n\t\t\t\ti--;\n\t\t\telse\n\t\t\t\ti++;\n\t\t} while ((i >= lblk_start) && (i <= lblk_end) &&\n\t\t\t\t((bh = bh->b_this_page) != head));\nnextpage:\n\t\tif (page)\n\t\t\tpage_cache_release(page);\n\t\t/*\n\t\t * Move to next page. 'i' will be the first lblk in the next\n\t\t * page.\n\t\t */\n\t\tif (search_hint_reverse)\n\t\t\tindex--;\n\t\telse\n\t\t\tindex++;\n\t\ti = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);\n\t}", "\ttrace_ext4_find_delalloc_range(inode, lblk_start, lblk_end,\n\t\t\t\t\tsearch_hint_reverse, 0, 0);\n\treturn 0;\n}", "int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk,\n\t\t\t int search_hint_reverse)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\text4_lblk_t lblk_start, lblk_end;\n\tlblk_start = lblk & (~(sbi->s_cluster_ratio - 1));\n\tlblk_end = lblk_start + sbi->s_cluster_ratio - 1;", "\treturn ext4_find_delalloc_range(inode, lblk_start, lblk_end,\n\t\t\t\t\tsearch_hint_reverse);\n}", "/**\n * Determines how many complete clusters (out of those specified by the 'map')\n * are under delalloc and were reserved quota for.\n * This function is called when we are writing out the blocks that were\n * originally written with their allocation delayed, but then the space was\n * allocated using fallocate() before the delayed allocation could be resolved.\n * The cases to look for are:\n * ('=' indicated delayed allocated blocks\n * '-' indicates non-delayed allocated blocks)\n * (a) partial clusters towards beginning and/or end outside of allocated range\n * are not delalloc'ed.\n *\tEx:\n *\t|----c---=|====c====|====c====|===-c----|\n *\t |++++++ allocated ++++++|\n *\t==> 4 complete clusters in above example\n *\n * (b) partial cluster (outside of allocated range) towards either end is\n * marked for delayed allocation. In this case, we will exclude that\n * cluster.\n *\tEx:\n *\t|----====c========|========c========|\n *\t |++++++ allocated ++++++|\n *\t==> 1 complete clusters in above example\n *\n *\tEx:\n *\t|================c================|\n * |++++++ allocated ++++++|\n *\t==> 0 complete clusters in above example\n *\n * The ext4_da_update_reserve_space will be called only if we\n * determine here that there were some \"entire\" clusters that span\n * this 'allocated' range.\n * In the non-bigalloc case, this function will just end up returning num_blks\n * without ever calling ext4_find_delalloc_range.\n */\nstatic unsigned int\nget_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,\n\t\t\t unsigned int num_blks)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\text4_lblk_t alloc_cluster_start, alloc_cluster_end;\n\text4_lblk_t lblk_from, lblk_to, c_offset;\n\tunsigned int allocated_clusters = 0;", "\talloc_cluster_start = EXT4_B2C(sbi, lblk_start);\n\talloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);", "\t/* max possible clusters for this allocation */\n\tallocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;", "\ttrace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);", "\t/* Check towards left side */\n\tc_offset = lblk_start & (sbi->s_cluster_ratio - 1);\n\tif (c_offset) {\n\t\tlblk_from = lblk_start & (~(sbi->s_cluster_ratio - 1));\n\t\tlblk_to = lblk_from + c_offset - 1;", "\t\tif (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))\n\t\t\tallocated_clusters--;\n\t}", "\t/* Now check towards right. */\n\tc_offset = (lblk_start + num_blks) & (sbi->s_cluster_ratio - 1);\n\tif (allocated_clusters && c_offset) {\n\t\tlblk_from = lblk_start + num_blks;\n\t\tlblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;", "\t\tif (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))\n\t\t\tallocated_clusters--;\n\t}", "\treturn allocated_clusters;\n}", "static int\next4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_map_blocks *map,\n\t\t\tstruct ext4_ext_path *path, int flags,\n\t\t\tunsigned int allocated, ext4_fsblk_t newblock)\n{\n\tint ret = 0;\n\tint err = 0;\n\text4_io_end_t *io = ext4_inode_aio(inode);", "\text_debug(\"ext4_ext_handle_uninitialized_extents: inode %lu, logical \"\n\t\t \"block %llu, max_blocks %u, flags %x, allocated %u\\n\",\n\t\t inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,\n\t\t flags, allocated);\n\text4_ext_show_leaf(inode, path);", "\ttrace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,\n\t\t\t\t\t\t newblock);", "\t/* get_block() before submit the IO, split the extent */\n\tif ((flags & EXT4_GET_BLOCKS_PRE_IO)) {\n\t\tret = ext4_split_unwritten_extents(handle, inode, map,\n\t\t\t\t\t\t path, flags);\n\t\tif (ret <= 0)\n\t\t\tgoto out;\n\t\t/*\n\t\t * Flag the inode(non aio case) or end_io struct (aio case)\n\t\t * that this IO needs to conversion to written when IO is\n\t\t * completed\n\t\t */\n\t\tif (io)\n\t\t\text4_set_io_unwritten_flag(inode, io);\n\t\telse\n\t\t\text4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);\n\t\tif (ext4_should_dioread_nolock(inode))\n\t\t\tmap->m_flags |= EXT4_MAP_UNINIT;\n\t\tgoto out;\n\t}\n\t/* IO end_io complete, convert the filled extent to written */\n\tif ((flags & EXT4_GET_BLOCKS_CONVERT)) {", "\t\tret = ext4_convert_unwritten_extents_endio(handle, inode,", "\t\t\t\t\t\t\tpath);\n\t\tif (ret >= 0) {\n\t\t\text4_update_inode_fsync_trans(handle, inode, 1);\n\t\t\terr = check_eofblocks_fl(handle, inode, map->m_lblk,\n\t\t\t\t\t\t path, map->m_len);\n\t\t} else\n\t\t\terr = ret;\n\t\tgoto out2;\n\t}\n\t/* buffered IO case */\n\t/*\n\t * repeat fallocate creation request\n\t * we already have an unwritten extent\n\t */\n\tif (flags & EXT4_GET_BLOCKS_UNINIT_EXT)\n\t\tgoto map_out;", "\t/* buffered READ or buffered write_begin() lookup */\n\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t/*\n\t\t * We have blocks reserved already. We\n\t\t * return allocated blocks so that delalloc\n\t\t * won't do block reservation for us. But\n\t\t * the buffer head will be unmapped so that\n\t\t * a read from the block returns 0s.\n\t\t */\n\t\tmap->m_flags |= EXT4_MAP_UNWRITTEN;\n\t\tgoto out1;\n\t}", "\t/* buffered write, writepage time, convert*/\n\tret = ext4_ext_convert_to_initialized(handle, inode, map, path);\n\tif (ret >= 0)\n\t\text4_update_inode_fsync_trans(handle, inode, 1);\nout:\n\tif (ret <= 0) {\n\t\terr = ret;\n\t\tgoto out2;\n\t} else\n\t\tallocated = ret;\n\tmap->m_flags |= EXT4_MAP_NEW;\n\t/*\n\t * if we allocated more blocks than requested\n\t * we need to make sure we unmap the extra block\n\t * allocated. The actual needed block will get\n\t * unmapped later when we find the buffer_head marked\n\t * new.\n\t */\n\tif (allocated > map->m_len) {\n\t\tunmap_underlying_metadata_blocks(inode->i_sb->s_bdev,\n\t\t\t\t\tnewblock + map->m_len,\n\t\t\t\t\tallocated - map->m_len);\n\t\tallocated = map->m_len;\n\t}", "\t/*\n\t * If we have done fallocate with the offset that is already\n\t * delayed allocated, we would have block reservation\n\t * and quota reservation done in the delayed write path.\n\t * But fallocate would have already updated quota and block\n\t * count for this offset. So cancel these reservation\n\t */\n\tif (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {\n\t\tunsigned int reserved_clusters;\n\t\treserved_clusters = get_reserved_cluster_alloc(inode,\n\t\t\t\tmap->m_lblk, map->m_len);\n\t\tif (reserved_clusters)\n\t\t\text4_da_update_reserve_space(inode,\n\t\t\t\t\t\t reserved_clusters,\n\t\t\t\t\t\t 0);\n\t}", "map_out:\n\tmap->m_flags |= EXT4_MAP_MAPPED;\n\tif ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {\n\t\terr = check_eofblocks_fl(handle, inode, map->m_lblk, path,\n\t\t\t\t\t map->m_len);\n\t\tif (err < 0)\n\t\t\tgoto out2;\n\t}\nout1:\n\tif (allocated > map->m_len)\n\t\tallocated = map->m_len;\n\text4_ext_show_leaf(inode, path);\n\tmap->m_pblk = newblock;\n\tmap->m_len = allocated;\nout2:\n\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}\n\treturn err ? err : allocated;\n}", "/*\n * get_implied_cluster_alloc - check to see if the requested\n * allocation (in the map structure) overlaps with a cluster already\n * allocated in an extent.\n *\t@sb\tThe filesystem superblock structure\n *\t@map\tThe requested lblk->pblk mapping\n *\t@ex\tThe extent structure which might contain an implied\n *\t\t\tcluster allocation\n *\n * This function is called by ext4_ext_map_blocks() after we failed to\n * find blocks that were already in the inode's extent tree. Hence,\n * we know that the beginning of the requested region cannot overlap\n * the extent from the inode's extent tree. There are three cases we\n * want to catch. The first is this case:\n *\n *\t\t |--- cluster # N--|\n * |--- extent ---|\t|---- requested region ---|\n *\t\t\t|==========|\n *\n * The second case that we need to test for is this one:\n *\n * |--------- cluster # N ----------------|\n *\t |--- requested region --| |------- extent ----|\n *\t |=======================|\n *\n * The third case is when the requested region lies between two extents\n * within the same cluster:\n * |------------- cluster # N-------------|\n * |----- ex -----| |---- ex_right ----|\n * |------ requested region ------|\n * |================|\n *\n * In each of the above cases, we need to set the map->m_pblk and\n * map->m_len so it corresponds to the return the extent labelled as\n * \"|====|\" from cluster #N, since it is already in use for data in\n * cluster EXT4_B2C(sbi, map->m_lblk).\tWe will then return 1 to\n * signal to ext4_ext_map_blocks() that map->m_pblk should be treated\n * as a new \"allocated\" block region. Otherwise, we will return 0 and\n * ext4_ext_map_blocks() will then allocate one or more new clusters\n * by calling ext4_mb_new_blocks().\n */\nstatic int get_implied_cluster_alloc(struct super_block *sb,\n\t\t\t\t struct ext4_map_blocks *map,\n\t\t\t\t struct ext4_extent *ex,\n\t\t\t\t struct ext4_ext_path *path)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\text4_lblk_t c_offset = map->m_lblk & (sbi->s_cluster_ratio-1);\n\text4_lblk_t ex_cluster_start, ex_cluster_end;\n\text4_lblk_t rr_cluster_start;\n\text4_lblk_t ee_block = le32_to_cpu(ex->ee_block);\n\text4_fsblk_t ee_start = ext4_ext_pblock(ex);\n\tunsigned short ee_len = ext4_ext_get_actual_len(ex);", "\t/* The extent passed in that we are trying to match */\n\tex_cluster_start = EXT4_B2C(sbi, ee_block);\n\tex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);", "\t/* The requested region passed into ext4_map_blocks() */\n\trr_cluster_start = EXT4_B2C(sbi, map->m_lblk);", "\tif ((rr_cluster_start == ex_cluster_end) ||\n\t (rr_cluster_start == ex_cluster_start)) {\n\t\tif (rr_cluster_start == ex_cluster_end)\n\t\t\tee_start += ee_len - 1;\n\t\tmap->m_pblk = (ee_start & ~(sbi->s_cluster_ratio - 1)) +\n\t\t\tc_offset;\n\t\tmap->m_len = min(map->m_len,\n\t\t\t\t (unsigned) sbi->s_cluster_ratio - c_offset);\n\t\t/*\n\t\t * Check for and handle this case:\n\t\t *\n\t\t * |--------- cluster # N-------------|\n\t\t *\t\t |------- extent ----|\n\t\t *\t |--- requested region ---|\n\t\t *\t |===========|\n\t\t */", "\t\tif (map->m_lblk < ee_block)\n\t\t\tmap->m_len = min(map->m_len, ee_block - map->m_lblk);", "\t\t/*\n\t\t * Check for the case where there is already another allocated\n\t\t * block to the right of 'ex' but before the end of the cluster.\n\t\t *\n\t\t * |------------- cluster # N-------------|\n\t\t * |----- ex -----| |---- ex_right ----|\n\t\t * |------ requested region ------|\n\t\t * |================|\n\t\t */\n\t\tif (map->m_lblk > ee_block) {\n\t\t\text4_lblk_t next = ext4_ext_next_allocated_block(path);\n\t\t\tmap->m_len = min(map->m_len, next - map->m_lblk);\n\t\t}", "\t\ttrace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);\n\t\treturn 1;\n\t}", "\ttrace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);\n\treturn 0;\n}", "\n/*\n * Block allocation/map/preallocation routine for extents based files\n *\n *\n * Need to be called with\n * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block\n * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)\n *\n * return > 0, number of of blocks already mapped/allocated\n * if create == 0 and these are pre-allocated blocks\n * \tbuffer head is unmapped\n * otherwise blocks are mapped\n *\n * return = 0, if plain look up failed (blocks have not been allocated)\n * buffer head is unmapped\n *\n * return < 0, error case.\n */\nint ext4_ext_map_blocks(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_map_blocks *map, int flags)\n{\n\tstruct ext4_ext_path *path = NULL;\n\tstruct ext4_extent newex, *ex, *ex2;\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\text4_fsblk_t newblock = 0;\n\tint free_on_err = 0, err = 0, depth, ret;\n\tunsigned int allocated = 0, offset = 0;\n\tunsigned int allocated_clusters = 0;\n\tstruct ext4_allocation_request ar;\n\text4_io_end_t *io = ext4_inode_aio(inode);\n\text4_lblk_t cluster_offset;\n\tint set_unwritten = 0;", "\text_debug(\"blocks %u/%u requested for inode %lu\\n\",\n\t\t map->m_lblk, map->m_len, inode->i_ino);\n\ttrace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);", "\t/* check in cache */\n\tif (ext4_ext_in_cache(inode, map->m_lblk, &newex)) {\n\t\tif (!newex.ee_start_lo && !newex.ee_start_hi) {\n\t\t\tif ((sbi->s_cluster_ratio > 1) &&\n\t\t\t ext4_find_delalloc_cluster(inode, map->m_lblk, 0))\n\t\t\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;", "\t\t\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t\t\t/*\n\t\t\t\t * block isn't allocated yet and\n\t\t\t\t * user doesn't want to allocate it\n\t\t\t\t */\n\t\t\t\tgoto out2;\n\t\t\t}\n\t\t\t/* we should allocate requested block */\n\t\t} else {\n\t\t\t/* block is already allocated */\n\t\t\tif (sbi->s_cluster_ratio > 1)\n\t\t\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;\n\t\t\tnewblock = map->m_lblk\n\t\t\t\t - le32_to_cpu(newex.ee_block)\n\t\t\t\t + ext4_ext_pblock(&newex);\n\t\t\t/* number of remaining blocks in the extent */\n\t\t\tallocated = ext4_ext_get_actual_len(&newex) -\n\t\t\t\t(map->m_lblk - le32_to_cpu(newex.ee_block));\n\t\t\tgoto out;\n\t\t}\n\t}", "\t/* find extent for this block */\n\tpath = ext4_ext_find_extent(inode, map->m_lblk, NULL);\n\tif (IS_ERR(path)) {\n\t\terr = PTR_ERR(path);\n\t\tpath = NULL;\n\t\tgoto out2;\n\t}", "\tdepth = ext_depth(inode);", "\t/*\n\t * consistent leaf must not be empty;\n\t * this situation is possible, though, _during_ tree modification;\n\t * this is why assert can't be put in ext4_ext_find_extent()\n\t */\n\tif (unlikely(path[depth].p_ext == NULL && depth != 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"bad extent address \"\n\t\t\t\t \"lblock: %lu, depth: %d pblock %lld\",\n\t\t\t\t (unsigned long) map->m_lblk, depth,\n\t\t\t\t path[depth].p_block);\n\t\terr = -EIO;\n\t\tgoto out2;\n\t}", "\tex = path[depth].p_ext;\n\tif (ex) {\n\t\text4_lblk_t ee_block = le32_to_cpu(ex->ee_block);\n\t\text4_fsblk_t ee_start = ext4_ext_pblock(ex);\n\t\tunsigned short ee_len;", "\t\t/*\n\t\t * Uninitialized extents are treated as holes, except that\n\t\t * we split out initialized portions during a write.\n\t\t */\n\t\tee_len = ext4_ext_get_actual_len(ex);", "\t\ttrace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);", "\t\t/* if found extent covers block, simply return it */\n\t\tif (in_range(map->m_lblk, ee_block, ee_len)) {\n\t\t\tnewblock = map->m_lblk - ee_block + ee_start;\n\t\t\t/* number of remaining blocks in the extent */\n\t\t\tallocated = ee_len - (map->m_lblk - ee_block);\n\t\t\text_debug(\"%u fit into %u:%d -> %llu\\n\", map->m_lblk,\n\t\t\t\t ee_block, ee_len, newblock);", "\t\t\t/*\n\t\t\t * Do not put uninitialized extent\n\t\t\t * in the cache\n\t\t\t */\n\t\t\tif (!ext4_ext_is_uninitialized(ex)) {\n\t\t\t\text4_ext_put_in_cache(inode, ee_block,\n\t\t\t\t\tee_len, ee_start);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tret = ext4_ext_handle_uninitialized_extents(\n\t\t\t\thandle, inode, map, path, flags,\n\t\t\t\tallocated, newblock);\n\t\t\treturn ret;\n\t\t}\n\t}", "\tif ((sbi->s_cluster_ratio > 1) &&\n\t ext4_find_delalloc_cluster(inode, map->m_lblk, 0))\n\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;", "\t/*\n\t * requested block isn't allocated yet;\n\t * we couldn't try to create block if create flag is zero\n\t */\n\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t/*\n\t\t * put just found gap into cache to speed up\n\t\t * subsequent requests\n\t\t */\n\t\text4_ext_put_gap_in_cache(inode, path, map->m_lblk);\n\t\tgoto out2;\n\t}", "\t/*\n\t * Okay, we need to do block allocation.\n\t */\n\tmap->m_flags &= ~EXT4_MAP_FROM_CLUSTER;\n\tnewex.ee_block = cpu_to_le32(map->m_lblk);\n\tcluster_offset = map->m_lblk & (sbi->s_cluster_ratio-1);", "\t/*\n\t * If we are doing bigalloc, check to see if the extent returned\n\t * by ext4_ext_find_extent() implies a cluster we can use.\n\t */\n\tif (cluster_offset && ex &&\n\t get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {\n\t\tar.len = allocated = map->m_len;\n\t\tnewblock = map->m_pblk;\n\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;\n\t\tgoto got_allocated_blocks;\n\t}", "\t/* find neighbour allocated blocks */\n\tar.lleft = map->m_lblk;\n\terr = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);\n\tif (err)\n\t\tgoto out2;\n\tar.lright = map->m_lblk;\n\tex2 = NULL;\n\terr = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);\n\tif (err)\n\t\tgoto out2;", "\t/* Check if the extent after searching to the right implies a\n\t * cluster we can use. */\n\tif ((sbi->s_cluster_ratio > 1) && ex2 &&\n\t get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {\n\t\tar.len = allocated = map->m_len;\n\t\tnewblock = map->m_pblk;\n\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;\n\t\tgoto got_allocated_blocks;\n\t}", "\t/*\n\t * See if request is beyond maximum number of blocks we can have in\n\t * a single extent. For an initialized extent this limit is\n\t * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is\n\t * EXT_UNINIT_MAX_LEN.\n\t */\n\tif (map->m_len > EXT_INIT_MAX_LEN &&\n\t !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))\n\t\tmap->m_len = EXT_INIT_MAX_LEN;\n\telse if (map->m_len > EXT_UNINIT_MAX_LEN &&\n\t\t (flags & EXT4_GET_BLOCKS_UNINIT_EXT))\n\t\tmap->m_len = EXT_UNINIT_MAX_LEN;", "\t/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */\n\tnewex.ee_len = cpu_to_le16(map->m_len);\n\terr = ext4_ext_check_overlap(sbi, inode, &newex, path);\n\tif (err)\n\t\tallocated = ext4_ext_get_actual_len(&newex);\n\telse\n\t\tallocated = map->m_len;", "\t/* allocate new block */\n\tar.inode = inode;\n\tar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);\n\tar.logical = map->m_lblk;\n\t/*\n\t * We calculate the offset from the beginning of the cluster\n\t * for the logical block number, since when we allocate a\n\t * physical cluster, the physical block should start at the\n\t * same offset from the beginning of the cluster. This is\n\t * needed so that future calls to get_implied_cluster_alloc()\n\t * work correctly.\n\t */\n\toffset = map->m_lblk & (sbi->s_cluster_ratio - 1);\n\tar.len = EXT4_NUM_B2C(sbi, offset+allocated);\n\tar.goal -= offset;\n\tar.logical -= offset;\n\tif (S_ISREG(inode->i_mode))\n\t\tar.flags = EXT4_MB_HINT_DATA;\n\telse\n\t\t/* disable in-core preallocation for non-regular files */\n\t\tar.flags = 0;\n\tif (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)\n\t\tar.flags |= EXT4_MB_HINT_NOPREALLOC;\n\tnewblock = ext4_mb_new_blocks(handle, &ar, &err);\n\tif (!newblock)\n\t\tgoto out2;\n\text_debug(\"allocate new block: goal %llu, found %llu/%u\\n\",\n\t\t ar.goal, newblock, allocated);\n\tfree_on_err = 1;\n\tallocated_clusters = ar.len;\n\tar.len = EXT4_C2B(sbi, ar.len) - offset;\n\tif (ar.len > allocated)\n\t\tar.len = allocated;", "got_allocated_blocks:\n\t/* try to insert new extent into found leaf and return */\n\text4_ext_store_pblock(&newex, newblock + offset);\n\tnewex.ee_len = cpu_to_le16(ar.len);\n\t/* Mark uninitialized */\n\tif (flags & EXT4_GET_BLOCKS_UNINIT_EXT){\n\t\text4_ext_mark_uninitialized(&newex);\n\t\t/*\n\t\t * io_end structure was created for every IO write to an\n\t\t * uninitialized extent. To avoid unnecessary conversion,\n\t\t * here we flag the IO that really needs the conversion.\n\t\t * For non asycn direct IO case, flag the inode state\n\t\t * that we need to perform conversion when IO is done.\n\t\t */\n\t\tif ((flags & EXT4_GET_BLOCKS_PRE_IO))\n\t\t\tset_unwritten = 1;\n\t\tif (ext4_should_dioread_nolock(inode))\n\t\t\tmap->m_flags |= EXT4_MAP_UNINIT;\n\t}", "\terr = 0;\n\tif ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)\n\t\terr = check_eofblocks_fl(handle, inode, map->m_lblk,\n\t\t\t\t\t path, ar.len);\n\tif (!err)\n\t\terr = ext4_ext_insert_extent(handle, inode, path,\n\t\t\t\t\t &newex, flags);", "\tif (!err && set_unwritten) {\n\t\tif (io)\n\t\t\text4_set_io_unwritten_flag(inode, io);\n\t\telse\n\t\t\text4_set_inode_state(inode,\n\t\t\t\t\t EXT4_STATE_DIO_UNWRITTEN);\n\t}", "\tif (err && free_on_err) {\n\t\tint fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?\n\t\t\tEXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;\n\t\t/* free data blocks we just allocated */\n\t\t/* not a good idea to call discard here directly,\n\t\t * but otherwise we'd need to call it every free() */\n\t\text4_discard_preallocations(inode);\n\t\text4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),\n\t\t\t\t ext4_ext_get_actual_len(&newex), fb_flags);\n\t\tgoto out2;\n\t}", "\t/* previous routine could use block we allocated */\n\tnewblock = ext4_ext_pblock(&newex);\n\tallocated = ext4_ext_get_actual_len(&newex);\n\tif (allocated > map->m_len)\n\t\tallocated = map->m_len;\n\tmap->m_flags |= EXT4_MAP_NEW;", "\t/*\n\t * Update reserved blocks/metadata blocks after successful\n\t * block allocation which had been deferred till now.\n\t */\n\tif (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {\n\t\tunsigned int reserved_clusters;\n\t\t/*\n\t\t * Check how many clusters we had reserved this allocated range\n\t\t */\n\t\treserved_clusters = get_reserved_cluster_alloc(inode,\n\t\t\t\t\t\tmap->m_lblk, allocated);\n\t\tif (map->m_flags & EXT4_MAP_FROM_CLUSTER) {\n\t\t\tif (reserved_clusters) {\n\t\t\t\t/*\n\t\t\t\t * We have clusters reserved for this range.\n\t\t\t\t * But since we are not doing actual allocation\n\t\t\t\t * and are simply using blocks from previously\n\t\t\t\t * allocated cluster, we should release the\n\t\t\t\t * reservation and not claim quota.\n\t\t\t\t */\n\t\t\t\text4_da_update_reserve_space(inode,\n\t\t\t\t\t\treserved_clusters, 0);\n\t\t\t}\n\t\t} else {\n\t\t\tBUG_ON(allocated_clusters < reserved_clusters);\n\t\t\t/* We will claim quota for all newly allocated blocks.*/\n\t\t\text4_da_update_reserve_space(inode, allocated_clusters,\n\t\t\t\t\t\t\t1);\n\t\t\tif (reserved_clusters < allocated_clusters) {\n\t\t\t\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\t\t\t\tint reservation = allocated_clusters -\n\t\t\t\t\t\t reserved_clusters;\n\t\t\t\t/*\n\t\t\t\t * It seems we claimed few clusters outside of\n\t\t\t\t * the range of this allocation. We should give\n\t\t\t\t * it back to the reservation pool. This can\n\t\t\t\t * happen in the following case:\n\t\t\t\t *\n\t\t\t\t * * Suppose s_cluster_ratio is 4 (i.e., each\n\t\t\t\t * cluster has 4 blocks. Thus, the clusters\n\t\t\t\t * are [0-3],[4-7],[8-11]...\n\t\t\t\t * * First comes delayed allocation write for\n\t\t\t\t * logical blocks 10 & 11. Since there were no\n\t\t\t\t * previous delayed allocated blocks in the\n\t\t\t\t * range [8-11], we would reserve 1 cluster\n\t\t\t\t * for this write.\n\t\t\t\t * * Next comes write for logical blocks 3 to 8.\n\t\t\t\t * In this case, we will reserve 2 clusters\n\t\t\t\t * (for [0-3] and [4-7]; and not for [8-11] as\n\t\t\t\t * that range has a delayed allocated blocks.\n\t\t\t\t * Thus total reserved clusters now becomes 3.\n\t\t\t\t * * Now, during the delayed allocation writeout\n\t\t\t\t * time, we will first write blocks [3-8] and\n\t\t\t\t * allocate 3 clusters for writing these\n\t\t\t\t * blocks. Also, we would claim all these\n\t\t\t\t * three clusters above.\n\t\t\t\t * * Now when we come here to writeout the\n\t\t\t\t * blocks [10-11], we would expect to claim\n\t\t\t\t * the reservation of 1 cluster we had made\n\t\t\t\t * (and we would claim it since there are no\n\t\t\t\t * more delayed allocated blocks in the range\n\t\t\t\t * [8-11]. But our reserved cluster count had\n\t\t\t\t * already gone to 0.\n\t\t\t\t *\n\t\t\t\t * Thus, at the step 4 above when we determine\n\t\t\t\t * that there are still some unwritten delayed\n\t\t\t\t * allocated blocks outside of our current\n\t\t\t\t * block range, we should increment the\n\t\t\t\t * reserved clusters count so that when the\n\t\t\t\t * remaining blocks finally gets written, we\n\t\t\t\t * could claim them.\n\t\t\t\t */\n\t\t\t\tdquot_reserve_block(inode,\n\t\t\t\t\t\tEXT4_C2B(sbi, reservation));\n\t\t\t\tspin_lock(&ei->i_block_reservation_lock);\n\t\t\t\tei->i_reserved_data_blocks += reservation;\n\t\t\t\tspin_unlock(&ei->i_block_reservation_lock);\n\t\t\t}\n\t\t}\n\t}", "\t/*\n\t * Cache the extent and update transaction to commit on fdatasync only\n\t * when it is _not_ an uninitialized extent.\n\t */\n\tif ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {\n\t\text4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);\n\t\text4_update_inode_fsync_trans(handle, inode, 1);\n\t} else\n\t\text4_update_inode_fsync_trans(handle, inode, 0);\nout:\n\tif (allocated > map->m_len)\n\t\tallocated = map->m_len;\n\text4_ext_show_leaf(inode, path);\n\tmap->m_flags |= EXT4_MAP_MAPPED;\n\tmap->m_pblk = newblock;\n\tmap->m_len = allocated;\nout2:\n\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}", "\ttrace_ext4_ext_map_blocks_exit(inode, map->m_lblk,\n\t\tnewblock, map->m_len, err ? err : allocated);", "\treturn err ? err : allocated;\n}", "void ext4_ext_truncate(struct inode *inode)\n{\n\tstruct address_space *mapping = inode->i_mapping;\n\tstruct super_block *sb = inode->i_sb;\n\text4_lblk_t last_block;\n\thandle_t *handle;\n\tloff_t page_len;\n\tint err = 0;", "\t/*\n\t * finish any pending end_io work so we won't run the risk of\n\t * converting any truncated blocks to initialized later\n\t */\n\text4_flush_unwritten_io(inode);", "\t/*\n\t * probably first extent we're gonna free will be last in block\n\t */\n\terr = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, err);\n\tif (IS_ERR(handle))\n\t\treturn;", "\tif (inode->i_size % PAGE_CACHE_SIZE != 0) {\n\t\tpage_len = PAGE_CACHE_SIZE -\n\t\t\t(inode->i_size & (PAGE_CACHE_SIZE - 1));", "\t\terr = ext4_discard_partial_page_buffers(handle,\n\t\t\tmapping, inode->i_size, page_len, 0);", "\t\tif (err)\n\t\t\tgoto out_stop;\n\t}", "\tif (ext4_orphan_add(handle, inode))\n\t\tgoto out_stop;", "\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_ext_invalidate_cache(inode);", "\text4_discard_preallocations(inode);", "\t/*\n\t * TODO: optimization is possible here.\n\t * Probably we need not scan at all,\n\t * because page truncation is enough.\n\t */", "\t/* we have to know where to truncate from in crash case */\n\tEXT4_I(inode)->i_disksize = inode->i_size;\n\text4_mark_inode_dirty(handle, inode);", "\tlast_block = (inode->i_size + sb->s_blocksize - 1)\n\t\t\t>> EXT4_BLOCK_SIZE_BITS(sb);\n\terr = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);", "\t/* In a multi-transaction truncate, we only make the final\n\t * transaction synchronous.\n\t */\n\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);", "\tup_write(&EXT4_I(inode)->i_data_sem);", "out_stop:\n\t/*\n\t * If this was a simple ftruncate() and the file will remain alive,\n\t * then we need to clear up the orphan record which we created above.\n\t * However, if this was a real unlink then we were called by\n\t * ext4_delete_inode(), and we allow that function to clean up the\n\t * orphan info for us.\n\t */\n\tif (inode->i_nlink)\n\t\text4_orphan_del(handle, inode);", "\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\text4_mark_inode_dirty(handle, inode);\n\text4_journal_stop(handle);\n}", "static void ext4_falloc_update_inode(struct inode *inode,\n\t\t\t\tint mode, loff_t new_size, int update_ctime)\n{\n\tstruct timespec now;", "\tif (update_ctime) {\n\t\tnow = current_fs_time(inode->i_sb);\n\t\tif (!timespec_equal(&inode->i_ctime, &now))\n\t\t\tinode->i_ctime = now;\n\t}\n\t/*\n\t * Update only when preallocation was requested beyond\n\t * the file size.\n\t */\n\tif (!(mode & FALLOC_FL_KEEP_SIZE)) {\n\t\tif (new_size > i_size_read(inode))\n\t\t\ti_size_write(inode, new_size);\n\t\tif (new_size > EXT4_I(inode)->i_disksize)\n\t\t\text4_update_i_disksize(inode, new_size);\n\t} else {\n\t\t/*\n\t\t * Mark that we allocate beyond EOF so the subsequent truncate\n\t\t * can proceed even if the new size is the same as i_size.\n\t\t */\n\t\tif (new_size > i_size_read(inode))\n\t\t\text4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);\n\t}", "}", "/*\n * preallocate space for a file. This implements ext4's fallocate file\n * operation, which gets called from sys_fallocate system call.\n * For block-mapped files, posix_fallocate should fall back to the method\n * of writing zeroes to the required new blocks (the same behavior which is\n * expected for file systems which do not support fallocate() system call).\n */\nlong ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)\n{\n\tstruct inode *inode = file->f_path.dentry->d_inode;\n\thandle_t *handle;\n\tloff_t new_size;\n\tunsigned int max_blocks;\n\tint ret = 0;\n\tint ret2 = 0;\n\tint retries = 0;\n\tint flags;\n\tstruct ext4_map_blocks map;\n\tunsigned int credits, blkbits = inode->i_blkbits;", "\t/*\n\t * currently supporting (pre)allocate mode for extent-based\n\t * files _only_\n\t */\n\tif (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))\n\t\treturn -EOPNOTSUPP;", "\t/* Return error if mode is not supported */\n\tif (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))\n\t\treturn -EOPNOTSUPP;", "\tif (mode & FALLOC_FL_PUNCH_HOLE)\n\t\treturn ext4_punch_hole(file, offset, len);", "\ttrace_ext4_fallocate_enter(inode, offset, len, mode);\n\tmap.m_lblk = offset >> blkbits;\n\t/*\n\t * We can't just convert len to max_blocks because\n\t * If blocksize = 4096 offset = 3072 and len = 2048\n\t */\n\tmax_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)\n\t\t- map.m_lblk;\n\t/*\n\t * credits to insert 1 extent into extent tree\n\t */\n\tcredits = ext4_chunk_trans_blocks(inode, max_blocks);\n\tmutex_lock(&inode->i_mutex);\n\tret = inode_newsize_ok(inode, (len + offset));\n\tif (ret) {\n\t\tmutex_unlock(&inode->i_mutex);\n\t\ttrace_ext4_fallocate_exit(inode, offset, max_blocks, ret);\n\t\treturn ret;\n\t}\n\tflags = EXT4_GET_BLOCKS_CREATE_UNINIT_EXT;\n\tif (mode & FALLOC_FL_KEEP_SIZE)\n\t\tflags |= EXT4_GET_BLOCKS_KEEP_SIZE;\n\t/*\n\t * Don't normalize the request if it can fit in one extent so\n\t * that it doesn't get unnecessarily split into multiple\n\t * extents.\n\t */\n\tif (len <= EXT_UNINIT_MAX_LEN << blkbits)\n\t\tflags |= EXT4_GET_BLOCKS_NO_NORMALIZE;", "\t/* Prevent race condition between unwritten */\n\text4_flush_unwritten_io(inode);\nretry:\n\twhile (ret >= 0 && ret < max_blocks) {\n\t\tmap.m_lblk = map.m_lblk + ret;\n\t\tmap.m_len = max_blocks = max_blocks - ret;\n\t\thandle = ext4_journal_start(inode, credits);\n\t\tif (IS_ERR(handle)) {\n\t\t\tret = PTR_ERR(handle);\n\t\t\tbreak;\n\t\t}\n\t\tret = ext4_map_blocks(handle, inode, &map, flags);\n\t\tif (ret <= 0) {\n#ifdef EXT4FS_DEBUG\n\t\t\tWARN_ON(ret <= 0);\n\t\t\tprintk(KERN_ERR \"%s: ext4_ext_map_blocks \"\n\t\t\t\t \"returned error inode#%lu, block=%u, \"\n\t\t\t\t \"max_blocks=%u\", __func__,\n\t\t\t\t inode->i_ino, map.m_lblk, max_blocks);\n#endif\n\t\t\text4_mark_inode_dirty(handle, inode);\n\t\t\tret2 = ext4_journal_stop(handle);\n\t\t\tbreak;\n\t\t}\n\t\tif ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,\n\t\t\t\t\t\tblkbits) >> blkbits))\n\t\t\tnew_size = offset + len;\n\t\telse\n\t\t\tnew_size = ((loff_t) map.m_lblk + ret) << blkbits;", "\t\text4_falloc_update_inode(inode, mode, new_size,\n\t\t\t\t\t (map.m_flags & EXT4_MAP_NEW));\n\t\text4_mark_inode_dirty(handle, inode);\n\t\tif ((file->f_flags & O_SYNC) && ret >= max_blocks)\n\t\t\text4_handle_sync(handle);\n\t\tret2 = ext4_journal_stop(handle);\n\t\tif (ret2)\n\t\t\tbreak;\n\t}\n\tif (ret == -ENOSPC &&\n\t\t\text4_should_retry_alloc(inode->i_sb, &retries)) {\n\t\tret = 0;\n\t\tgoto retry;\n\t}\n\tmutex_unlock(&inode->i_mutex);\n\ttrace_ext4_fallocate_exit(inode, offset, max_blocks,\n\t\t\t\tret > 0 ? ret2 : ret);\n\treturn ret > 0 ? ret2 : ret;\n}", "/*\n * This function convert a range of blocks to written extents\n * The caller of this function will pass the start offset and the size.\n * all unwritten extents within this range will be converted to\n * written extents.\n *\n * This function is called from the direct IO end io call back\n * function, to convert the fallocated extents after IO is completed.\n * Returns 0 on success.\n */\nint ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,\n\t\t\t\t ssize_t len)\n{\n\thandle_t *handle;\n\tunsigned int max_blocks;\n\tint ret = 0;\n\tint ret2 = 0;\n\tstruct ext4_map_blocks map;\n\tunsigned int credits, blkbits = inode->i_blkbits;", "\tmap.m_lblk = offset >> blkbits;\n\t/*\n\t * We can't just convert len to max_blocks because\n\t * If blocksize = 4096 offset = 3072 and len = 2048\n\t */\n\tmax_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -\n\t\t map.m_lblk);\n\t/*\n\t * credits to insert 1 extent into extent tree\n\t */\n\tcredits = ext4_chunk_trans_blocks(inode, max_blocks);\n\twhile (ret >= 0 && ret < max_blocks) {\n\t\tmap.m_lblk += ret;\n\t\tmap.m_len = (max_blocks -= ret);\n\t\thandle = ext4_journal_start(inode, credits);\n\t\tif (IS_ERR(handle)) {\n\t\t\tret = PTR_ERR(handle);\n\t\t\tbreak;\n\t\t}\n\t\tret = ext4_map_blocks(handle, inode, &map,\n\t\t\t\t EXT4_GET_BLOCKS_IO_CONVERT_EXT);\n\t\tif (ret <= 0) {\n\t\t\tWARN_ON(ret <= 0);\n\t\t\text4_msg(inode->i_sb, KERN_ERR,\n\t\t\t\t \"%s:%d: inode #%lu: block %u: len %u: \"\n\t\t\t\t \"ext4_ext_map_blocks returned %d\",\n\t\t\t\t __func__, __LINE__, inode->i_ino, map.m_lblk,\n\t\t\t\t map.m_len, ret);\n\t\t}\n\t\text4_mark_inode_dirty(handle, inode);\n\t\tret2 = ext4_journal_stop(handle);\n\t\tif (ret <= 0 || ret2 )\n\t\t\tbreak;\n\t}\n\treturn ret > 0 ? ret2 : ret;\n}", "/*\n * Callback function called for each extent to gather FIEMAP information.\n */\nstatic int ext4_ext_fiemap_cb(struct inode *inode, ext4_lblk_t next,\n\t\t struct ext4_ext_cache *newex, struct ext4_extent *ex,\n\t\t void *data)\n{\n\t__u64\tlogical;\n\t__u64\tphysical;\n\t__u64\tlength;\n\t__u32\tflags = 0;\n\tint\t\tret = 0;\n\tstruct fiemap_extent_info *fieinfo = data;\n\tunsigned char blksize_bits;", "\tblksize_bits = inode->i_sb->s_blocksize_bits;\n\tlogical = (__u64)newex->ec_block << blksize_bits;", "\tif (newex->ec_start == 0) {\n\t\t/*\n\t\t * No extent in extent-tree contains block @newex->ec_start,\n\t\t * then the block may stay in 1)a hole or 2)delayed-extent.\n\t\t *\n\t\t * Holes or delayed-extents are processed as follows.\n\t\t * 1. lookup dirty pages with specified range in pagecache.\n\t\t * If no page is got, then there is no delayed-extent and\n\t\t * return with EXT_CONTINUE.\n\t\t * 2. find the 1st mapped buffer,\n\t\t * 3. check if the mapped buffer is both in the request range\n\t\t * and a delayed buffer. If not, there is no delayed-extent,\n\t\t * then return.\n\t\t * 4. a delayed-extent is found, the extent will be collected.\n\t\t */\n\t\text4_lblk_t\tend = 0;\n\t\tpgoff_t\t\tlast_offset;\n\t\tpgoff_t\t\toffset;\n\t\tpgoff_t\t\tindex;\n\t\tpgoff_t\t\tstart_index = 0;\n\t\tstruct page\t**pages = NULL;\n\t\tstruct buffer_head *bh = NULL;\n\t\tstruct buffer_head *head = NULL;\n\t\tunsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);", "\t\tpages = kmalloc(PAGE_SIZE, GFP_KERNEL);\n\t\tif (pages == NULL)\n\t\t\treturn -ENOMEM;", "\t\toffset = logical >> PAGE_SHIFT;\nrepeat:\n\t\tlast_offset = offset;\n\t\thead = NULL;\n\t\tret = find_get_pages_tag(inode->i_mapping, &offset,\n\t\t\t\t\tPAGECACHE_TAG_DIRTY, nr_pages, pages);", "\t\tif (!(flags & FIEMAP_EXTENT_DELALLOC)) {\n\t\t\t/* First time, try to find a mapped buffer. */\n\t\t\tif (ret == 0) {\nout:\n\t\t\t\tfor (index = 0; index < ret; index++)\n\t\t\t\t\tpage_cache_release(pages[index]);\n\t\t\t\t/* just a hole. */\n\t\t\t\tkfree(pages);\n\t\t\t\treturn EXT_CONTINUE;\n\t\t\t}\n\t\t\tindex = 0;", "next_page:\n\t\t\t/* Try to find the 1st mapped buffer. */\n\t\t\tend = ((__u64)pages[index]->index << PAGE_SHIFT) >>\n\t\t\t\t blksize_bits;\n\t\t\tif (!page_has_buffers(pages[index]))\n\t\t\t\tgoto out;\n\t\t\thead = page_buffers(pages[index]);\n\t\t\tif (!head)\n\t\t\t\tgoto out;", "\t\t\tindex++;\n\t\t\tbh = head;\n\t\t\tdo {\n\t\t\t\tif (end >= newex->ec_block +\n\t\t\t\t\tnewex->ec_len)\n\t\t\t\t\t/* The buffer is out of\n\t\t\t\t\t * the request range.\n\t\t\t\t\t */\n\t\t\t\t\tgoto out;", "\t\t\t\tif (buffer_mapped(bh) &&\n\t\t\t\t end >= newex->ec_block) {\n\t\t\t\t\tstart_index = index - 1;\n\t\t\t\t\t/* get the 1st mapped buffer. */\n\t\t\t\t\tgoto found_mapped_buffer;\n\t\t\t\t}", "\t\t\t\tbh = bh->b_this_page;\n\t\t\t\tend++;\n\t\t\t} while (bh != head);", "\t\t\t/* No mapped buffer in the range found in this page,\n\t\t\t * We need to look up next page.\n\t\t\t */\n\t\t\tif (index >= ret) {\n\t\t\t\t/* There is no page left, but we need to limit\n\t\t\t\t * newex->ec_len.\n\t\t\t\t */\n\t\t\t\tnewex->ec_len = end - newex->ec_block;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tgoto next_page;\n\t\t} else {\n\t\t\t/*Find contiguous delayed buffers. */\n\t\t\tif (ret > 0 && pages[0]->index == last_offset)\n\t\t\t\thead = page_buffers(pages[0]);\n\t\t\tbh = head;\n\t\t\tindex = 1;\n\t\t\tstart_index = 0;\n\t\t}", "found_mapped_buffer:\n\t\tif (bh != NULL && buffer_delay(bh)) {\n\t\t\t/* 1st or contiguous delayed buffer found. */\n\t\t\tif (!(flags & FIEMAP_EXTENT_DELALLOC)) {\n\t\t\t\t/*\n\t\t\t\t * 1st delayed buffer found, record\n\t\t\t\t * the start of extent.\n\t\t\t\t */\n\t\t\t\tflags |= FIEMAP_EXTENT_DELALLOC;\n\t\t\t\tnewex->ec_block = end;\n\t\t\t\tlogical = (__u64)end << blksize_bits;\n\t\t\t}\n\t\t\t/* Find contiguous delayed buffers. */\n\t\t\tdo {\n\t\t\t\tif (!buffer_delay(bh))\n\t\t\t\t\tgoto found_delayed_extent;\n\t\t\t\tbh = bh->b_this_page;\n\t\t\t\tend++;\n\t\t\t} while (bh != head);", "\t\t\tfor (; index < ret; index++) {\n\t\t\t\tif (!page_has_buffers(pages[index])) {\n\t\t\t\t\tbh = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\thead = page_buffers(pages[index]);\n\t\t\t\tif (!head) {\n\t\t\t\t\tbh = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}", "\t\t\t\tif (pages[index]->index !=\n\t\t\t\t pages[start_index]->index + index\n\t\t\t\t - start_index) {\n\t\t\t\t\t/* Blocks are not contiguous. */\n\t\t\t\t\tbh = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbh = head;\n\t\t\t\tdo {\n\t\t\t\t\tif (!buffer_delay(bh))\n\t\t\t\t\t\t/* Delayed-extent ends. */\n\t\t\t\t\t\tgoto found_delayed_extent;\n\t\t\t\t\tbh = bh->b_this_page;\n\t\t\t\t\tend++;\n\t\t\t\t} while (bh != head);\n\t\t\t}\n\t\t} else if (!(flags & FIEMAP_EXTENT_DELALLOC))\n\t\t\t/* a hole found. */\n\t\t\tgoto out;", "found_delayed_extent:\n\t\tnewex->ec_len = min(end - newex->ec_block,\n\t\t\t\t\t\t(ext4_lblk_t)EXT_INIT_MAX_LEN);\n\t\tif (ret == nr_pages && bh != NULL &&\n\t\t\tnewex->ec_len < EXT_INIT_MAX_LEN &&\n\t\t\tbuffer_delay(bh)) {\n\t\t\t/* Have not collected an extent and continue. */\n\t\t\tfor (index = 0; index < ret; index++)\n\t\t\t\tpage_cache_release(pages[index]);\n\t\t\tgoto repeat;\n\t\t}", "\t\tfor (index = 0; index < ret; index++)\n\t\t\tpage_cache_release(pages[index]);\n\t\tkfree(pages);\n\t}", "\tphysical = (__u64)newex->ec_start << blksize_bits;\n\tlength = (__u64)newex->ec_len << blksize_bits;", "\tif (ex && ext4_ext_is_uninitialized(ex))\n\t\tflags |= FIEMAP_EXTENT_UNWRITTEN;", "\tif (next == EXT_MAX_BLOCKS)\n\t\tflags |= FIEMAP_EXTENT_LAST;", "\tret = fiemap_fill_next_extent(fieinfo, logical, physical,\n\t\t\t\t\tlength, flags);\n\tif (ret < 0)\n\t\treturn ret;\n\tif (ret == 1)\n\t\treturn EXT_BREAK;\n\treturn EXT_CONTINUE;\n}\n/* fiemap flags we can handle specified here */\n#define EXT4_FIEMAP_FLAGS\t(FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)", "static int ext4_xattr_fiemap(struct inode *inode,\n\t\t\t\tstruct fiemap_extent_info *fieinfo)\n{\n\t__u64 physical = 0;\n\t__u64 length;\n\t__u32 flags = FIEMAP_EXTENT_LAST;\n\tint blockbits = inode->i_sb->s_blocksize_bits;\n\tint error = 0;", "\t/* in-inode? */\n\tif (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {\n\t\tstruct ext4_iloc iloc;\n\t\tint offset;\t/* offset of xattr in inode */", "\t\terror = ext4_get_inode_loc(inode, &iloc);\n\t\tif (error)\n\t\t\treturn error;\n\t\tphysical = iloc.bh->b_blocknr << blockbits;\n\t\toffset = EXT4_GOOD_OLD_INODE_SIZE +\n\t\t\t\tEXT4_I(inode)->i_extra_isize;\n\t\tphysical += offset;\n\t\tlength = EXT4_SB(inode->i_sb)->s_inode_size - offset;\n\t\tflags |= FIEMAP_EXTENT_DATA_INLINE;\n\t\tbrelse(iloc.bh);\n\t} else { /* external block */\n\t\tphysical = EXT4_I(inode)->i_file_acl << blockbits;\n\t\tlength = inode->i_sb->s_blocksize;\n\t}", "\tif (physical)\n\t\terror = fiemap_fill_next_extent(fieinfo, 0, physical,\n\t\t\t\t\t\tlength, flags);\n\treturn (error < 0 ? error : 0);\n}", "/*\n * ext4_ext_punch_hole\n *\n * Punches a hole of \"length\" bytes in a file starting\n * at byte \"offset\"\n *\n * @inode: The inode of the file to punch a hole in\n * @offset: The starting byte offset of the hole\n * @length: The length of the hole\n *\n * Returns the number of blocks removed or negative on err\n */\nint ext4_ext_punch_hole(struct file *file, loff_t offset, loff_t length)\n{\n\tstruct inode *inode = file->f_path.dentry->d_inode;\n\tstruct super_block *sb = inode->i_sb;\n\text4_lblk_t first_block, stop_block;\n\tstruct address_space *mapping = inode->i_mapping;\n\thandle_t *handle;\n\tloff_t first_page, last_page, page_len;\n\tloff_t first_page_offset, last_page_offset;\n\tint credits, err = 0;", "\t/*\n\t * Write out all dirty pages to avoid race conditions\n\t * Then release them.\n\t */\n\tif (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {\n\t\terr = filemap_write_and_wait_range(mapping,\n\t\t\toffset, offset + length - 1);", "\t\tif (err)\n\t\t\treturn err;\n\t}", "\tmutex_lock(&inode->i_mutex);\n\t/* It's not possible punch hole on append only file */\n\tif (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {\n\t\terr = -EPERM;\n\t\tgoto out_mutex;\n\t}\n\tif (IS_SWAPFILE(inode)) {\n\t\terr = -ETXTBSY;\n\t\tgoto out_mutex;\n\t}", "\t/* No need to punch hole beyond i_size */\n\tif (offset >= inode->i_size)\n\t\tgoto out_mutex;", "\t/*\n\t * If the hole extends beyond i_size, set the hole\n\t * to end after the page that contains i_size\n\t */\n\tif (offset + length > inode->i_size) {\n\t\tlength = inode->i_size +\n\t\t PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -\n\t\t offset;\n\t}", "\tfirst_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;\n\tlast_page = (offset + length) >> PAGE_CACHE_SHIFT;", "\tfirst_page_offset = first_page << PAGE_CACHE_SHIFT;\n\tlast_page_offset = last_page << PAGE_CACHE_SHIFT;", "\t/* Now release the pages */\n\tif (last_page_offset > first_page_offset) {\n\t\ttruncate_pagecache_range(inode, first_page_offset,\n\t\t\t\t\t last_page_offset - 1);\n\t}", "\t/* Wait all existing dio workers, newcomers will block on i_mutex */\n\text4_inode_block_unlocked_dio(inode);\n\terr = ext4_flush_unwritten_io(inode);\n\tif (err)\n\t\tgoto out_dio;\n\tinode_dio_wait(inode);", "\tcredits = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, credits);\n\tif (IS_ERR(handle)) {\n\t\terr = PTR_ERR(handle);\n\t\tgoto out_dio;\n\t}", "\n\t/*\n\t * Now we need to zero out the non-page-aligned data in the\n\t * pages at the start and tail of the hole, and unmap the buffer\n\t * heads for the block aligned regions of the page that were\n\t * completely zeroed.\n\t */\n\tif (first_page > last_page) {\n\t\t/*\n\t\t * If the file space being truncated is contained within a page\n\t\t * just zero out and unmap the middle of that page\n\t\t */\n\t\terr = ext4_discard_partial_page_buffers(handle,\n\t\t\tmapping, offset, length, 0);", "\t\tif (err)\n\t\t\tgoto out;\n\t} else {\n\t\t/*\n\t\t * zero out and unmap the partial page that contains\n\t\t * the start of the hole\n\t\t */\n\t\tpage_len = first_page_offset - offset;\n\t\tif (page_len > 0) {\n\t\t\terr = ext4_discard_partial_page_buffers(handle, mapping,\n\t\t\t\t\t\t offset, page_len, 0);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}", "\t\t/*\n\t\t * zero out and unmap the partial page that contains\n\t\t * the end of the hole\n\t\t */\n\t\tpage_len = offset + length - last_page_offset;\n\t\tif (page_len > 0) {\n\t\t\terr = ext4_discard_partial_page_buffers(handle, mapping,\n\t\t\t\t\tlast_page_offset, page_len, 0);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}\n\t}", "\t/*\n\t * If i_size is contained in the last page, we need to\n\t * unmap and zero the partial page after i_size\n\t */\n\tif (inode->i_size >> PAGE_CACHE_SHIFT == last_page &&\n\t inode->i_size % PAGE_CACHE_SIZE != 0) {", "\t\tpage_len = PAGE_CACHE_SIZE -\n\t\t\t(inode->i_size & (PAGE_CACHE_SIZE - 1));", "\t\tif (page_len > 0) {\n\t\t\terr = ext4_discard_partial_page_buffers(handle,\n\t\t\t mapping, inode->i_size, page_len, 0);", "\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}\n\t}", "\tfirst_block = (offset + sb->s_blocksize - 1) >>\n\t\tEXT4_BLOCK_SIZE_BITS(sb);\n\tstop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);", "\t/* If there are no blocks to remove, return now */\n\tif (first_block >= stop_block)\n\t\tgoto out;", "\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_ext_invalidate_cache(inode);\n\text4_discard_preallocations(inode);", "\terr = ext4_ext_remove_space(inode, first_block, stop_block - 1);", "\text4_ext_invalidate_cache(inode);\n\text4_discard_preallocations(inode);", "\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);", "\tup_write(&EXT4_I(inode)->i_data_sem);", "out:\n\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\text4_mark_inode_dirty(handle, inode);\n\text4_journal_stop(handle);\nout_dio:\n\text4_inode_resume_unlocked_dio(inode);\nout_mutex:\n\tmutex_unlock(&inode->i_mutex);\n\treturn err;\n}\nint ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,\n\t\t__u64 start, __u64 len)\n{\n\text4_lblk_t start_blk;\n\tint error = 0;", "\t/* fallback to generic here if not in extents fmt */\n\tif (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))\n\t\treturn generic_block_fiemap(inode, fieinfo, start, len,\n\t\t\text4_get_block);", "\tif (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))\n\t\treturn -EBADR;", "\tif (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {\n\t\terror = ext4_xattr_fiemap(inode, fieinfo);\n\t} else {\n\t\text4_lblk_t len_blks;\n\t\t__u64 last_blk;", "\t\tstart_blk = start >> inode->i_sb->s_blocksize_bits;\n\t\tlast_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;\n\t\tif (last_blk >= EXT_MAX_BLOCKS)\n\t\t\tlast_blk = EXT_MAX_BLOCKS-1;\n\t\tlen_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;", "\t\t/*\n\t\t * Walk the extent tree gathering extent information.\n\t\t * ext4_ext_fiemap_cb will push extents back to user.\n\t\t */\n\t\terror = ext4_ext_walk_space(inode, start_blk, len_blks,\n\t\t\t\t\t ext4_ext_fiemap_cb, fieinfo);\n\t}", "\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [3656], "buggy_code_start_loc": [53], "filenames": ["fs/ext4/extents.c"], "fixing_code_end_loc": [3691], "fixing_code_start_loc": [54], "message": "Race condition in fs/ext4/extents.c in the Linux kernel before 3.4.16 allows local users to obtain sensitive information from a deleted file by reading an extent that was not properly marked as uninitialized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F399128-7646-4F7C-83D5-1C9461024AF6", "versionEndExcluding": null, "versionEndIncluding": "3.4.15", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "D30AEC07-3CBD-4F4F-9646-BEAA1D98750B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C2AA8E68-691B-499C-AEDD-3C0BFFE70044", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "9440475B-5960-4066-A204-F30AAFC87846", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc4:*:*:*:*:*:*", "matchCriteriaId": "53BCFBFB-6AF0-4525-8623-7633CC5E17DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc5:*:*:*:*:*:*", "matchCriteriaId": "6ED4E86A-74F0-436A-BEB4-3F4EE93A5421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc6:*:*:*:*:*:*", "matchCriteriaId": "BF0365B0-8E16-4F30-BD92-5DD538CC8135", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc7:*:*:*:*:*:*", "matchCriteriaId": "079505E8-2942-4C33-93D1-35ADA4C39E72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "38989541-2360-4E0A-AE5A-3D6144AA6114", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4E51646B-7A0E-40F3-B8C9-239C1DA81DD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "42A8A507-F8E2-491C-A144-B2448A1DB26E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "901FC6F3-2C2A-4112-AE27-AB102BBE8DEE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "203AD334-DB9F-41B0-A4D1-A6C158EF8C40", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "B3611753-E440-410F-8250-600C996A4B8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "9739BB47-EEAF-42F1-A557-2AE2EA9526A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "5A95E3BB-0AFC-4C2E-B9BE-C975E902A266", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "482A6C9A-9B8E-4D1C-917A-F16370745E7C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "C6D87357-63E0-41D0-9F02-1BCBF9A77E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.11:*:*:*:*:*:*:*", "matchCriteriaId": "3765A2D6-2D78-4FB1-989E-D5106BFA3F5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.12:*:*:*:*:*:*:*", "matchCriteriaId": "F54257DB-7023-43C4-AC4D-9590B815CD92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.13:*:*:*:*:*:*:*", "matchCriteriaId": "61FF5FCD-A4A1-4803-AC53-320A4C838AF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.14:*:*:*:*:*:*:*", "matchCriteriaId": "9F096553-064F-46A2-877B-F32F163A0F49", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.15:*:*:*:*:*:*:*", "matchCriteriaId": "C0D762D1-E3AD-40EA-8D39-83EEB51B5E85", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.16:*:*:*:*:*:*:*", "matchCriteriaId": "A6187D19-7148-4B87-AD7E-244FF9EE0FA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.17:*:*:*:*:*:*:*", "matchCriteriaId": "99AC64C2-E391-485C-9CD7-BA09C8FA5E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.18:*:*:*:*:*:*:*", "matchCriteriaId": "8CDA5E95-7805-441B-BEF7-4448EA45E964", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.19:*:*:*:*:*:*:*", "matchCriteriaId": "51561053-6C28-4F38-BC9B-3F7A7508EB72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.20:*:*:*:*:*:*:*", "matchCriteriaId": "118F4A5B-C498-4FC3-BE28-50D18EBE4F22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.21:*:*:*:*:*:*:*", "matchCriteriaId": "BD38EBE6-FE1A-4B55-9FB5-07952253B7A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.22:*:*:*:*:*:*:*", "matchCriteriaId": "3A491E47-82AD-4055-9444-2EC0D6715326", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.23:*:*:*:*:*:*:*", "matchCriteriaId": "13C5FD16-23B6-467F-9438-5B554922F974", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.24:*:*:*:*:*:*:*", "matchCriteriaId": "9C67235F-5B51-4BF7-89EC-4810F720246F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.25:*:*:*:*:*:*:*", "matchCriteriaId": "08405DEF-05F4-45F0-AC95-DBF914A36D93", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.26:*:*:*:*:*:*:*", "matchCriteriaId": "1A7B9C4B-4A41-4175-9F07-191C1EE98C1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.27:*:*:*:*:*:*:*", "matchCriteriaId": "B306E0A8-4D4A-4895-8128-A500D30A7E0C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.28:*:*:*:*:*:*:*", "matchCriteriaId": "295C839A-F34E-4853-A926-55EABC639412", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.29:*:*:*:*:*:*:*", "matchCriteriaId": "2AFD5F49-7EF9-4CFE-95BD-8FD19B500B0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.30:*:*:*:*:*:*:*", "matchCriteriaId": "00B3DDDD-B2F6-4753-BA38-65A24017857D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.31:*:*:*:*:*:*:*", "matchCriteriaId": "33FCD39E-F4BF-432D-9CF9-F195CF5844F3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.32:*:*:*:*:*:*:*", "matchCriteriaId": "C7308690-CB0D-4758-B80F-D2ADCD2A9D66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.33:*:*:*:*:*:*:*", "matchCriteriaId": "313A470B-8A2B-478A-82B5-B27D2718331C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.34:*:*:*:*:*:*:*", "matchCriteriaId": "83FF021E-07E3-41CC-AAE8-D99D7FF24B9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.35:*:*:*:*:*:*:*", "matchCriteriaId": "F72412E3-8DA9-4CC9-A426-B534202ADBA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.36:*:*:*:*:*:*:*", "matchCriteriaId": "FCAA9D7A-3C3E-4C0B-9D38-EA80E68C2E46", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.37:*:*:*:*:*:*:*", "matchCriteriaId": "4A9E3AE5-3FCF-4CBB-A30B-082BCFBFB0CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.38:*:*:*:*:*:*:*", "matchCriteriaId": "CF715657-4C3A-4392-B85D-1BBF4DE45D89", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.39:*:*:*:*:*:*:*", "matchCriteriaId": "4B63C618-AC3D-4EF7-AFDF-27B9BF482B78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.40:*:*:*:*:*:*:*", "matchCriteriaId": "C33DA5A9-5E40-4365-9602-82FB4DCD15B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.41:*:*:*:*:*:*:*", "matchCriteriaId": "EFAFDB74-40BD-46FA-89AC-617EB2C7160B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.42:*:*:*:*:*:*:*", "matchCriteriaId": "CF5F17DA-30A7-40CF-BD7C-CEDF06D64617", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.43:*:*:*:*:*:*:*", "matchCriteriaId": "71A276F5-BD9D-4C1B-90DF-9B0C15B6F7DF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.44:*:*:*:*:*:*:*", "matchCriteriaId": "F8F6EBEC-3C29-444B-BB85-6EF239B59EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:*:*:*:*:*:*:*", "matchCriteriaId": "3DFFE5A6-6A67-4992-84A3-C0F05FACDEAD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "13BBD2A3-AE10-48B9-8776-4FB1CAC37D44", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc2:*:*:*:*:*:*", "matchCriteriaId": "B25680CC-8918-4F27-8D7E-A6579215450B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc3:*:*:*:*:*:*", "matchCriteriaId": "92C48B4C-410C-4BA8-A28A-B2E928320FCC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc4:*:*:*:*:*:*", "matchCriteriaId": "CB447523-855B-461E-8197-95169BE86EB0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "B155BBDF-6DF6-4FF5-9C41-D8A5266DCC67", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "28476DEC-9630-4B40-9D4D-9BC151DC4CA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "5646880A-2355-4BDD-89E7-825863A0311F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "7FF99148-267A-46F8-9927-A9082269BAF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "A783C083-5D9C-48F9-B5A6-A97A9604FB19", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "2B817A24-03AC-46CD-BEFA-505457FD2A5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.7:*:*:*:*:*:*:*", "matchCriteriaId": "51CF1BCE-090E-4B70-BA16-ACB74411293B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.8:*:*:*:*:*:*:*", "matchCriteriaId": "187AAD67-10D7-4B57-B4C6-00443E246AF3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.9:*:*:*:*:*:*:*", "matchCriteriaId": "F341CE88-C5BC-4CDD-9CB5-B6BAD7152E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.10:*:*:*:*:*:*:*", "matchCriteriaId": "37ACE2A6-C229-4236-8E9F-235F008F3AA0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:*:*", "matchCriteriaId": "D3220B70-917F-4F9F-8A3B-2BF581281E8D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:x86:*", "matchCriteriaId": "7D47A395-821D-4BFF-996E-E849D9A40217", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc2:*:*:*:*:*:*", "matchCriteriaId": "99372D07-C06A-41FA-9843-6D57F99AB5AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc3:*:*:*:*:*:*", "matchCriteriaId": "2B9DC110-D260-4DB4-B8B0-EF1D160ADA07", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc4:*:*:*:*:*:*", "matchCriteriaId": "6192FE84-4D53-40D4-AF61-78CE7136141A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc5:*:*:*:*:*:*", "matchCriteriaId": "42FEF3CF-1302-45EB-89CC-3786FE4BAC1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc6:*:*:*:*:*:*", "matchCriteriaId": "AE6A6B58-2C89-4DE4-BA57-78100818095C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc7:*:*:*:*:*:*", "matchCriteriaId": "1D467F87-2F13-4D26-9A93-E0BA526FEA24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "FE348F7B-02DE-47D5-8011-F83DA9426021", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:x86:*", "matchCriteriaId": "8A603291-33B4-4195-B52D-D2A9938089C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "E91594EA-F0A3-41B3-A9C6-F7864FC2F229", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "9E1ECCDB-0208-48F6-B44F-16CC0ECE3503", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "FBA8B5DE-372E-47E0-A0F6-BE286D509CC3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "9A1CA083-2CF8-45AE-9E15-1AA3A8352E3B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "19D69A49-5290-4C5F-8157-719AD58D253D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "290BD969-42E7-47B0-B21B-06DE4865432C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "23A9E29E-DE78-4C73-9FBD-C2410F5FC8B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "018434C9-E75F-45CB-A169-DAB4B1D864D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.10:*:*:*:*:*:*:*", "matchCriteriaId": "DC0AC68F-EC58-4C4F-8CBC-A59ECC00CCDE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.11:*:*:*:*:*:*:*", "matchCriteriaId": "C123C844-F6D7-471E-A62E-F756042FB1CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.12:*:*:*:*:*:*:*", "matchCriteriaId": "A11C38BB-7FA2-49B0-AAC9-83DB387A06DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.13:*:*:*:*:*:*:*", "matchCriteriaId": "61F3733C-E5F6-4855-B471-DF3FB823613B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.14:*:*:*:*:*:*:*", "matchCriteriaId": "1DDCA75F-9A06-4457-9A45-38A38E7F7086", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.15:*:*:*:*:*:*:*", "matchCriteriaId": "7AEA837E-7864-4003-8DB7-111ED710A7E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.16:*:*:*:*:*:*:*", "matchCriteriaId": "B6FE471F-2D1F-4A1D-A197-7E46B75787E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.17:*:*:*:*:*:*:*", "matchCriteriaId": "FDA9E6AB-58DC-4EC5-A25C-11F9D0B38BF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.18:*:*:*:*:*:*:*", "matchCriteriaId": "DC6B8DB3-B05B-41A2-B091-342D66AAE8F5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.19:*:*:*:*:*:*:*", "matchCriteriaId": "958F0FF8-33EF-4A71-A0BD-572C85211DBA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.20:*:*:*:*:*:*:*", "matchCriteriaId": "FBA39F48-B02F-4C48-B304-DA9CCA055244", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.21:*:*:*:*:*:*:*", "matchCriteriaId": "1FF841F3-48A7-41D7-9C45-A8170435A5EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.22:*:*:*:*:*:*:*", "matchCriteriaId": "EF506916-A6DC-4B1E-90E5-959492AF55F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.23:*:*:*:*:*:*:*", "matchCriteriaId": "B3CDAD1F-2C6A-48C0-8FAB-C2659373FA25", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.24:*:*:*:*:*:*:*", "matchCriteriaId": "4FFE4B22-C96A-43D0-B993-F51EDD9C5E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.25:*:*:*:*:*:*:*", "matchCriteriaId": "F571CC8B-B212-4553-B463-1DB01D616E8A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.26:*:*:*:*:*:*:*", "matchCriteriaId": "84E3E151-D437-48ED-A529-731EEFF88567", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.27:*:*:*:*:*:*:*", "matchCriteriaId": "E9E3EA3C-CCA5-4433-86E0-3D02C4757A0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.28:*:*:*:*:*:*:*", "matchCriteriaId": "F7AC4F7D-9FA6-4CF1-B2E9-70BF7D4D177C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.29:*:*:*:*:*:*:*", "matchCriteriaId": "3CE3A80D-9648-43CC-8F99-D741ED6552BF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.30:*:*:*:*:*:*:*", "matchCriteriaId": "C8A98C03-A465-41B4-A551-A26FEC7FFD94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "AFB76697-1C2F-48C0-9B14-517EC053D4B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc1:*:*:*:*:*:*", "matchCriteriaId": "BED88DFD-1DC5-4505-A441-44ECDEF0252D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc2:*:*:*:*:*:*", "matchCriteriaId": "DBFD2ACD-728A-4082-BB6A-A1EF6E58E47D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc3:*:*:*:*:*:*", "matchCriteriaId": "C31B0E51-F62D-4053-B04F-FC4D5BC373D2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc4:*:*:*:*:*:*", "matchCriteriaId": "A914303E-1CB6-4AAD-9F5F-DE5433C4E814", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc5:*:*:*:*:*:*", "matchCriteriaId": "203BBA69-90B2-4C5E-8023-C14180742421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc6:*:*:*:*:*:*", "matchCriteriaId": "0DBFAB53-B889-4028-AC0E-7E165B152A18", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc7:*:*:*:*:*:*", "matchCriteriaId": "FE409AEC-F677-4DEF-8EB7-2C35809043CE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "578EC12B-402F-4AD4-B8F8-C9B2CAB06891", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "877002ED-8097-4BB4-BB88-6FC6306C38B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "76294CE3-D72C-41D5-9E0F-B693D0042699", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "916E97D4-1FAB-42F5-826B-653B1C0909A8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "33FD2217-C5D0-48C1-AD74-3527127FEF9C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "2E92971F-B629-4E0A-9A50-8B235F9704B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.7:*:*:*:*:*:*:*", "matchCriteriaId": "EDD3A069-3829-4EE2-9D5A-29459F29D4C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.8:*:*:*:*:*:*:*", "matchCriteriaId": "A4A0964C-CEB2-41D7-A69C-1599B05B6171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:*:*", "matchCriteriaId": "0F960FA6-F904-4A4E-B483-44C70090E9A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:x86:*", "matchCriteriaId": "8C3D9C66-933A-469E-9073-75015A8AD17D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:*:*", "matchCriteriaId": "261C1B41-C9E0-414F-8368-51C0C0B8AD38", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:x86:*", "matchCriteriaId": "C92F29A0-DEFF-49E4-AE86-5DBDAD51C677", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:*:*", "matchCriteriaId": "5CCA261D-2B97-492F-89A0-5F209A804350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:x86:*", "matchCriteriaId": "5690A703-390D-4D8A-9258-2F47116DAB4F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:*:*", "matchCriteriaId": "1B1C0C68-9194-473F-BE5E-EC7F184899FA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:x86:*", "matchCriteriaId": "AB1EDDA7-15AF-4B45-A931-DFCBB1EEB701", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:*:*", "matchCriteriaId": "D7A6AC9E-BEA6-44B0-B3B3-F0F94E32424A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:x86:*", "matchCriteriaId": "952FE0DC-B2ED-4080-BF29-A2C265E83FEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:*:*", "matchCriteriaId": "16038328-9399-4B85-B777-BA4757D02C9B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:x86:*", "matchCriteriaId": "1CE7ABDB-6572-40E8-B952-CBE52C999858", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:*:*", "matchCriteriaId": "16CA2757-FA8D-43D9-96E8-D3C0EB6E1DEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:x86:*", "matchCriteriaId": "0F417186-D1ED-4A31-92B2-83DEDA1AF272", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:*:*", "matchCriteriaId": "E8CB5481-5EAE-401E-BD7E-D3095CCA9E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:x86:*", "matchCriteriaId": "3D4FCFAE-918C-4886-9A17-08A5B94D35F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "A0F36FAC-141D-476D-84C5-A558C199F904", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:x86:*", "matchCriteriaId": "830D2914-C9FE-406F-AFCE-7A04BB9E2896", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "51D64824-25F6-4761-BD6A-29038A143744", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:x86:*", "matchCriteriaId": "F4B791B5-2EB5-403A-90CC-B219F6277D1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "E284C8A1-740F-454D-A774-99CD3A21B594", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:x86:*", "matchCriteriaId": "2BA5F34D-7490-4B2B-A7E6-8450F9C1FC31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "C70D72AE-0CBF-4324-9935-57E28EC6279C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:x86:*", "matchCriteriaId": "B803FE64-FC8D-4650-9FB9-FEEED4340416", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "F674B06B-7E86-4E41-9126-8152D0DDABAE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:x86:*", "matchCriteriaId": "4C560A9A-2388-4980-9E88-118C5EB806B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "7DA94F50-2A62-4300-BF4D-A342AAE35629", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.11:*:*:*:*:*:*:*", "matchCriteriaId": "252D937B-50DC-444F-AE73-5FCF6203DF27", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.12:*:*:*:*:*:*:*", "matchCriteriaId": "F6D8EE51-02C1-47BC-A92C-0A8ABEFD28FF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.13:*:*:*:*:*:*:*", "matchCriteriaId": "7F20A5D7-3B38-4911-861A-04C8310D5916", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.14:*:*:*:*:*:*:*", "matchCriteriaId": "D472DE3A-71D8-4F40-9DDE-85929A2B047D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Race condition in fs/ext4/extents.c in the Linux kernel before 3.4.16 allows local users to obtain sensitive information from a deleted file by reading an extent that was not properly marked as uninitialized."}, {"lang": "es", "value": "Condici\u00f3n de carrera en fs/ext4/extents.c. En el kernel Linux antes de v3.4.16 permite a usuarios locales obtener informaci\u00f3n sensible de un archivo eliminado mediante la lectura de un 'extent' que no fue correctamente marcado como 'no inicializado' .\r\n"}], "evaluatorComment": null, "id": "CVE-2012-4508", "lastModified": "2023-02-13T04:34:36.667", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 1.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2012-12-21T11:47:36.580", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=dee1f973ca341c266229faa5a1a5bb268bed3531"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://lists.fedoraproject.org/pipermail/package-announce/2012-November/091110.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2012-1540.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2013-0496.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2013-1519.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2013-1783.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.kernel.org/pub/linux/kernel/v3.x/ChangeLog-3.4.16"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2012/10/25/1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-1645-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-1899-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-1900-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://bugzilla.redhat.com/show_bug.cgi?id=869904"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "https://github.com/torvalds/linux/commit/dee1f973ca341c266229faa5a1a5bb268bed3531"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://www.suse.com/support/update/announcement/2012/suse-su-20121679-1.html"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/dee1f973ca341c266229faa5a1a5bb268bed3531"}, "type": "CWE-362"}
33
Determine whether the {function_name} code is vulnerable or not.
[ "/*\n * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com\n * Written by Alex Tomas <alex@clusterfs.com>\n *\n * Architecture independence:\n * Copyright (c) 2005, Bull S.A.\n * Written by Pierre Peiffer <pierre.peiffer@bull.net>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License version 2 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public Licens\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-\n */", "/*\n * Extents support for EXT4\n *\n * TODO:\n * - ext4*_error() should be used in some situations\n * - analyze all BUG()/BUG_ON(), use -EIO where appropriate\n * - smart tree reduction\n */", "#include <linux/fs.h>\n#include <linux/time.h>\n#include <linux/jbd2.h>\n#include <linux/highuid.h>\n#include <linux/pagemap.h>\n#include <linux/quotaops.h>\n#include <linux/string.h>\n#include <linux/slab.h>\n#include <linux/falloc.h>\n#include <asm/uaccess.h>\n#include <linux/fiemap.h>\n#include \"ext4_jbd2.h\"", "#include <trace/events/ext4.h>", "/*\n * used by extent splitting.\n */\n#define EXT4_EXT_MAY_ZEROOUT\t0x1 /* safe to zeroout if split fails \\\n\t\t\t\t\tdue to ENOSPC */\n#define EXT4_EXT_MARK_UNINIT1\t0x2 /* mark first half uninitialized */\n#define EXT4_EXT_MARK_UNINIT2\t0x4 /* mark second half uninitialized */", "\n#define EXT4_EXT_DATA_VALID1\t0x8 /* first half contains valid data */\n#define EXT4_EXT_DATA_VALID2\t0x10 /* second half contains valid data */", "\nstatic __le32 ext4_extent_block_csum(struct inode *inode,\n\t\t\t\t struct ext4_extent_header *eh)\n{\n\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\t__u32 csum;", "\tcsum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)eh,\n\t\t\t EXT4_EXTENT_TAIL_OFFSET(eh));\n\treturn cpu_to_le32(csum);\n}", "static int ext4_extent_block_csum_verify(struct inode *inode,\n\t\t\t\t\t struct ext4_extent_header *eh)\n{\n\tstruct ext4_extent_tail *et;", "\tif (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,\n\t\tEXT4_FEATURE_RO_COMPAT_METADATA_CSUM))\n\t\treturn 1;", "\tet = find_ext4_extent_tail(eh);\n\tif (et->et_checksum != ext4_extent_block_csum(inode, eh))\n\t\treturn 0;\n\treturn 1;\n}", "static void ext4_extent_block_csum_set(struct inode *inode,\n\t\t\t\t struct ext4_extent_header *eh)\n{\n\tstruct ext4_extent_tail *et;", "\tif (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,\n\t\tEXT4_FEATURE_RO_COMPAT_METADATA_CSUM))\n\t\treturn;", "\tet = find_ext4_extent_tail(eh);\n\tet->et_checksum = ext4_extent_block_csum(inode, eh);\n}", "static int ext4_split_extent(handle_t *handle,\n\t\t\t\tstruct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\tstruct ext4_map_blocks *map,\n\t\t\t\tint split_flag,\n\t\t\t\tint flags);", "static int ext4_split_extent_at(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t split,\n\t\t\t int split_flag,\n\t\t\t int flags);", "static int ext4_ext_truncate_extend_restart(handle_t *handle,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t int needed)\n{\n\tint err;", "\tif (!ext4_handle_valid(handle))\n\t\treturn 0;\n\tif (handle->h_buffer_credits > needed)\n\t\treturn 0;\n\terr = ext4_journal_extend(handle, needed);\n\tif (err <= 0)\n\t\treturn err;\n\terr = ext4_truncate_restart_trans(handle, inode, needed);\n\tif (err == 0)\n\t\terr = -EAGAIN;", "\treturn err;\n}", "/*\n * could return:\n * - EROFS\n * - ENOMEM\n */\nstatic int ext4_ext_get_access(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path)\n{\n\tif (path->p_bh) {\n\t\t/* path points to block */\n\t\treturn ext4_journal_get_write_access(handle, path->p_bh);\n\t}\n\t/* path points to leaf/index in inode body */\n\t/* we use in-core data, no need to protect them */\n\treturn 0;\n}", "/*\n * could return:\n * - EROFS\n * - ENOMEM\n * - EIO\n */\n#define ext4_ext_dirty(handle, inode, path) \\\n\t\t__ext4_ext_dirty(__func__, __LINE__, (handle), (inode), (path))\nstatic int __ext4_ext_dirty(const char *where, unsigned int line,\n\t\t\t handle_t *handle, struct inode *inode,\n\t\t\t struct ext4_ext_path *path)\n{\n\tint err;\n\tif (path->p_bh) {\n\t\text4_extent_block_csum_set(inode, ext_block_hdr(path->p_bh));\n\t\t/* path points to block */\n\t\terr = __ext4_handle_dirty_metadata(where, line, handle,\n\t\t\t\t\t\t inode, path->p_bh);\n\t} else {\n\t\t/* path points to leaf/index in inode body */\n\t\terr = ext4_mark_inode_dirty(handle, inode);\n\t}\n\treturn err;\n}", "static ext4_fsblk_t ext4_ext_find_goal(struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t block)\n{\n\tif (path) {\n\t\tint depth = path->p_depth;\n\t\tstruct ext4_extent *ex;", "\t\t/*\n\t\t * Try to predict block placement assuming that we are\n\t\t * filling in a file which will eventually be\n\t\t * non-sparse --- i.e., in the case of libbfd writing\n\t\t * an ELF object sections out-of-order but in a way\n\t\t * the eventually results in a contiguous object or\n\t\t * executable file, or some database extending a table\n\t\t * space file. However, this is actually somewhat\n\t\t * non-ideal if we are writing a sparse file such as\n\t\t * qemu or KVM writing a raw image file that is going\n\t\t * to stay fairly sparse, since it will end up\n\t\t * fragmenting the file system's free space. Maybe we\n\t\t * should have some hueristics or some way to allow\n\t\t * userspace to pass a hint to file system,\n\t\t * especially if the latter case turns out to be\n\t\t * common.\n\t\t */\n\t\tex = path[depth].p_ext;\n\t\tif (ex) {\n\t\t\text4_fsblk_t ext_pblk = ext4_ext_pblock(ex);\n\t\t\text4_lblk_t ext_block = le32_to_cpu(ex->ee_block);", "\t\t\tif (block > ext_block)\n\t\t\t\treturn ext_pblk + (block - ext_block);\n\t\t\telse\n\t\t\t\treturn ext_pblk - (ext_block - block);\n\t\t}", "\t\t/* it looks like index is empty;\n\t\t * try to find starting block from index itself */\n\t\tif (path[depth].p_bh)\n\t\t\treturn path[depth].p_bh->b_blocknr;\n\t}", "\t/* OK. use inode's group */\n\treturn ext4_inode_to_goal_block(inode);\n}", "/*\n * Allocation for a meta data block\n */\nstatic ext4_fsblk_t\next4_ext_new_meta_block(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_ext_path *path,\n\t\t\tstruct ext4_extent *ex, int *err, unsigned int flags)\n{\n\text4_fsblk_t goal, newblock;", "\tgoal = ext4_ext_find_goal(inode, path, le32_to_cpu(ex->ee_block));\n\tnewblock = ext4_new_meta_blocks(handle, inode, goal, flags,\n\t\t\t\t\tNULL, err);\n\treturn newblock;\n}", "static inline int ext4_ext_space_block(struct inode *inode, int check)\n{\n\tint size;", "\tsize = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))\n\t\t\t/ sizeof(struct ext4_extent);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 6)\n\t\tsize = 6;\n#endif\n\treturn size;\n}", "static inline int ext4_ext_space_block_idx(struct inode *inode, int check)\n{\n\tint size;", "\tsize = (inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))\n\t\t\t/ sizeof(struct ext4_extent_idx);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 5)\n\t\tsize = 5;\n#endif\n\treturn size;\n}", "static inline int ext4_ext_space_root(struct inode *inode, int check)\n{\n\tint size;", "\tsize = sizeof(EXT4_I(inode)->i_data);\n\tsize -= sizeof(struct ext4_extent_header);\n\tsize /= sizeof(struct ext4_extent);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 3)\n\t\tsize = 3;\n#endif\n\treturn size;\n}", "static inline int ext4_ext_space_root_idx(struct inode *inode, int check)\n{\n\tint size;", "\tsize = sizeof(EXT4_I(inode)->i_data);\n\tsize -= sizeof(struct ext4_extent_header);\n\tsize /= sizeof(struct ext4_extent_idx);\n#ifdef AGGRESSIVE_TEST\n\tif (!check && size > 4)\n\t\tsize = 4;\n#endif\n\treturn size;\n}", "/*\n * Calculate the number of metadata blocks needed\n * to allocate @blocks\n * Worse case is one block per extent\n */\nint ext4_ext_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)\n{\n\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\tint idxs;", "\tidxs = ((inode->i_sb->s_blocksize - sizeof(struct ext4_extent_header))\n\t\t/ sizeof(struct ext4_extent_idx));", "\t/*\n\t * If the new delayed allocation block is contiguous with the\n\t * previous da block, it can share index blocks with the\n\t * previous block, so we only need to allocate a new index\n\t * block every idxs leaf blocks. At ldxs**2 blocks, we need\n\t * an additional index block, and at ldxs**3 blocks, yet\n\t * another index blocks.\n\t */\n\tif (ei->i_da_metadata_calc_len &&\n\t ei->i_da_metadata_calc_last_lblock+1 == lblock) {\n\t\tint num = 0;", "\t\tif ((ei->i_da_metadata_calc_len % idxs) == 0)\n\t\t\tnum++;\n\t\tif ((ei->i_da_metadata_calc_len % (idxs*idxs)) == 0)\n\t\t\tnum++;\n\t\tif ((ei->i_da_metadata_calc_len % (idxs*idxs*idxs)) == 0) {\n\t\t\tnum++;\n\t\t\tei->i_da_metadata_calc_len = 0;\n\t\t} else\n\t\t\tei->i_da_metadata_calc_len++;\n\t\tei->i_da_metadata_calc_last_lblock++;\n\t\treturn num;\n\t}", "\t/*\n\t * In the worst case we need a new set of index blocks at\n\t * every level of the inode's extent tree.\n\t */\n\tei->i_da_metadata_calc_len = 1;\n\tei->i_da_metadata_calc_last_lblock = lblock;\n\treturn ext_depth(inode) + 1;\n}", "static int\next4_ext_max_entries(struct inode *inode, int depth)\n{\n\tint max;", "\tif (depth == ext_depth(inode)) {\n\t\tif (depth == 0)\n\t\t\tmax = ext4_ext_space_root(inode, 1);\n\t\telse\n\t\t\tmax = ext4_ext_space_root_idx(inode, 1);\n\t} else {\n\t\tif (depth == 0)\n\t\t\tmax = ext4_ext_space_block(inode, 1);\n\t\telse\n\t\t\tmax = ext4_ext_space_block_idx(inode, 1);\n\t}", "\treturn max;\n}", "static int ext4_valid_extent(struct inode *inode, struct ext4_extent *ext)\n{\n\text4_fsblk_t block = ext4_ext_pblock(ext);\n\tint len = ext4_ext_get_actual_len(ext);", "\tif (len == 0)\n\t\treturn 0;\n\treturn ext4_data_block_valid(EXT4_SB(inode->i_sb), block, len);\n}", "static int ext4_valid_extent_idx(struct inode *inode,\n\t\t\t\tstruct ext4_extent_idx *ext_idx)\n{\n\text4_fsblk_t block = ext4_idx_pblock(ext_idx);", "\treturn ext4_data_block_valid(EXT4_SB(inode->i_sb), block, 1);\n}", "static int ext4_valid_extent_entries(struct inode *inode,\n\t\t\t\tstruct ext4_extent_header *eh,\n\t\t\t\tint depth)\n{\n\tunsigned short entries;\n\tif (eh->eh_entries == 0)\n\t\treturn 1;", "\tentries = le16_to_cpu(eh->eh_entries);", "\tif (depth == 0) {\n\t\t/* leaf entries */\n\t\tstruct ext4_extent *ext = EXT_FIRST_EXTENT(eh);\n\t\twhile (entries) {\n\t\t\tif (!ext4_valid_extent(inode, ext))\n\t\t\t\treturn 0;\n\t\t\text++;\n\t\t\tentries--;\n\t\t}\n\t} else {\n\t\tstruct ext4_extent_idx *ext_idx = EXT_FIRST_INDEX(eh);\n\t\twhile (entries) {\n\t\t\tif (!ext4_valid_extent_idx(inode, ext_idx))\n\t\t\t\treturn 0;\n\t\t\text_idx++;\n\t\t\tentries--;\n\t\t}\n\t}\n\treturn 1;\n}", "static int __ext4_ext_check(const char *function, unsigned int line,\n\t\t\t struct inode *inode, struct ext4_extent_header *eh,\n\t\t\t int depth)\n{\n\tconst char *error_msg;\n\tint max = 0;", "\tif (unlikely(eh->eh_magic != EXT4_EXT_MAGIC)) {\n\t\terror_msg = \"invalid magic\";\n\t\tgoto corrupted;\n\t}\n\tif (unlikely(le16_to_cpu(eh->eh_depth) != depth)) {\n\t\terror_msg = \"unexpected eh_depth\";\n\t\tgoto corrupted;\n\t}\n\tif (unlikely(eh->eh_max == 0)) {\n\t\terror_msg = \"invalid eh_max\";\n\t\tgoto corrupted;\n\t}\n\tmax = ext4_ext_max_entries(inode, depth);\n\tif (unlikely(le16_to_cpu(eh->eh_max) > max)) {\n\t\terror_msg = \"too large eh_max\";\n\t\tgoto corrupted;\n\t}\n\tif (unlikely(le16_to_cpu(eh->eh_entries) > le16_to_cpu(eh->eh_max))) {\n\t\terror_msg = \"invalid eh_entries\";\n\t\tgoto corrupted;\n\t}\n\tif (!ext4_valid_extent_entries(inode, eh, depth)) {\n\t\terror_msg = \"invalid extent entries\";\n\t\tgoto corrupted;\n\t}\n\t/* Verify checksum on non-root extent tree nodes */\n\tif (ext_depth(inode) != depth &&\n\t !ext4_extent_block_csum_verify(inode, eh)) {\n\t\terror_msg = \"extent tree corrupted\";\n\t\tgoto corrupted;\n\t}\n\treturn 0;", "corrupted:\n\text4_error_inode(inode, function, line, 0,\n\t\t\t\"bad header/extent: %s - magic %x, \"\n\t\t\t\"entries %u, max %u(%u), depth %u(%u)\",\n\t\t\terror_msg, le16_to_cpu(eh->eh_magic),\n\t\t\tle16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max),\n\t\t\tmax, le16_to_cpu(eh->eh_depth), depth);", "\treturn -EIO;\n}", "#define ext4_ext_check(inode, eh, depth)\t\\\n\t__ext4_ext_check(__func__, __LINE__, inode, eh, depth)", "int ext4_ext_check_inode(struct inode *inode)\n{\n\treturn ext4_ext_check(inode, ext_inode_hdr(inode), ext_depth(inode));\n}", "static int __ext4_ext_check_block(const char *function, unsigned int line,\n\t\t\t\t struct inode *inode,\n\t\t\t\t struct ext4_extent_header *eh,\n\t\t\t\t int depth,\n\t\t\t\t struct buffer_head *bh)\n{\n\tint ret;", "\tif (buffer_verified(bh))\n\t\treturn 0;\n\tret = ext4_ext_check(inode, eh, depth);\n\tif (ret)\n\t\treturn ret;\n\tset_buffer_verified(bh);\n\treturn ret;\n}", "#define ext4_ext_check_block(inode, eh, depth, bh)\t\\\n\t__ext4_ext_check_block(__func__, __LINE__, inode, eh, depth, bh)", "#ifdef EXT_DEBUG\nstatic void ext4_ext_show_path(struct inode *inode, struct ext4_ext_path *path)\n{\n\tint k, l = path->p_depth;", "\text_debug(\"path:\");\n\tfor (k = 0; k <= l; k++, path++) {\n\t\tif (path->p_idx) {\n\t\t ext_debug(\" %d->%llu\", le32_to_cpu(path->p_idx->ei_block),\n\t\t\t ext4_idx_pblock(path->p_idx));\n\t\t} else if (path->p_ext) {\n\t\t\text_debug(\" %d:[%d]%d:%llu \",\n\t\t\t\t le32_to_cpu(path->p_ext->ee_block),\n\t\t\t\t ext4_ext_is_uninitialized(path->p_ext),\n\t\t\t\t ext4_ext_get_actual_len(path->p_ext),\n\t\t\t\t ext4_ext_pblock(path->p_ext));\n\t\t} else\n\t\t\text_debug(\" []\");\n\t}\n\text_debug(\"\\n\");\n}", "static void ext4_ext_show_leaf(struct inode *inode, struct ext4_ext_path *path)\n{\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *ex;\n\tint i;", "\tif (!path)\n\t\treturn;", "\teh = path[depth].p_hdr;\n\tex = EXT_FIRST_EXTENT(eh);", "\text_debug(\"Displaying leaf extents for inode %lu\\n\", inode->i_ino);", "\tfor (i = 0; i < le16_to_cpu(eh->eh_entries); i++, ex++) {\n\t\text_debug(\"%d:[%d]%d:%llu \", le32_to_cpu(ex->ee_block),\n\t\t\t ext4_ext_is_uninitialized(ex),\n\t\t\t ext4_ext_get_actual_len(ex), ext4_ext_pblock(ex));\n\t}\n\text_debug(\"\\n\");\n}", "static void ext4_ext_show_move(struct inode *inode, struct ext4_ext_path *path,\n\t\t\text4_fsblk_t newblock, int level)\n{\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent *ex;", "\tif (depth != level) {\n\t\tstruct ext4_extent_idx *idx;\n\t\tidx = path[level].p_idx;\n\t\twhile (idx <= EXT_MAX_INDEX(path[level].p_hdr)) {\n\t\t\text_debug(\"%d: move %d:%llu in new index %llu\\n\", level,\n\t\t\t\t\tle32_to_cpu(idx->ei_block),\n\t\t\t\t\text4_idx_pblock(idx),\n\t\t\t\t\tnewblock);\n\t\t\tidx++;\n\t\t}", "\t\treturn;\n\t}", "\tex = path[depth].p_ext;\n\twhile (ex <= EXT_MAX_EXTENT(path[depth].p_hdr)) {\n\t\text_debug(\"move %d:%llu:[%d]%d in new leaf %llu\\n\",\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\text4_ext_pblock(ex),\n\t\t\t\text4_ext_is_uninitialized(ex),\n\t\t\t\text4_ext_get_actual_len(ex),\n\t\t\t\tnewblock);\n\t\tex++;\n\t}\n}", "#else\n#define ext4_ext_show_path(inode, path)\n#define ext4_ext_show_leaf(inode, path)\n#define ext4_ext_show_move(inode, path, newblock, level)\n#endif", "void ext4_ext_drop_refs(struct ext4_ext_path *path)\n{\n\tint depth = path->p_depth;\n\tint i;", "\tfor (i = 0; i <= depth; i++, path++)\n\t\tif (path->p_bh) {\n\t\t\tbrelse(path->p_bh);\n\t\t\tpath->p_bh = NULL;\n\t\t}\n}", "/*\n * ext4_ext_binsearch_idx:\n * binary search for the closest index of the given block\n * the header must be checked before calling this\n */\nstatic void\next4_ext_binsearch_idx(struct inode *inode,\n\t\t\tstruct ext4_ext_path *path, ext4_lblk_t block)\n{\n\tstruct ext4_extent_header *eh = path->p_hdr;\n\tstruct ext4_extent_idx *r, *l, *m;", "\n\text_debug(\"binsearch for %u(idx): \", block);", "\tl = EXT_FIRST_INDEX(eh) + 1;\n\tr = EXT_LAST_INDEX(eh);\n\twhile (l <= r) {\n\t\tm = l + (r - l) / 2;\n\t\tif (block < le32_to_cpu(m->ei_block))\n\t\t\tr = m - 1;\n\t\telse\n\t\t\tl = m + 1;\n\t\text_debug(\"%p(%u):%p(%u):%p(%u) \", l, le32_to_cpu(l->ei_block),\n\t\t\t\tm, le32_to_cpu(m->ei_block),\n\t\t\t\tr, le32_to_cpu(r->ei_block));\n\t}", "\tpath->p_idx = l - 1;\n\text_debug(\" -> %u->%lld \", le32_to_cpu(path->p_idx->ei_block),\n\t\t ext4_idx_pblock(path->p_idx));", "#ifdef CHECK_BINSEARCH\n\t{\n\t\tstruct ext4_extent_idx *chix, *ix;\n\t\tint k;", "\t\tchix = ix = EXT_FIRST_INDEX(eh);\n\t\tfor (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ix++) {\n\t\t if (k != 0 &&\n\t\t le32_to_cpu(ix->ei_block) <= le32_to_cpu(ix[-1].ei_block)) {\n\t\t\t\tprintk(KERN_DEBUG \"k=%d, ix=0x%p, \"\n\t\t\t\t \"first=0x%p\\n\", k,\n\t\t\t\t ix, EXT_FIRST_INDEX(eh));\n\t\t\t\tprintk(KERN_DEBUG \"%u <= %u\\n\",\n\t\t\t\t le32_to_cpu(ix->ei_block),\n\t\t\t\t le32_to_cpu(ix[-1].ei_block));\n\t\t\t}\n\t\t\tBUG_ON(k && le32_to_cpu(ix->ei_block)\n\t\t\t\t\t <= le32_to_cpu(ix[-1].ei_block));\n\t\t\tif (block < le32_to_cpu(ix->ei_block))\n\t\t\t\tbreak;\n\t\t\tchix = ix;\n\t\t}\n\t\tBUG_ON(chix != path->p_idx);\n\t}\n#endif", "}", "/*\n * ext4_ext_binsearch:\n * binary search for closest extent of the given block\n * the header must be checked before calling this\n */\nstatic void\next4_ext_binsearch(struct inode *inode,\n\t\tstruct ext4_ext_path *path, ext4_lblk_t block)\n{\n\tstruct ext4_extent_header *eh = path->p_hdr;\n\tstruct ext4_extent *r, *l, *m;", "\tif (eh->eh_entries == 0) {\n\t\t/*\n\t\t * this leaf is empty:\n\t\t * we get such a leaf in split/add case\n\t\t */\n\t\treturn;\n\t}", "\text_debug(\"binsearch for %u: \", block);", "\tl = EXT_FIRST_EXTENT(eh) + 1;\n\tr = EXT_LAST_EXTENT(eh);", "\twhile (l <= r) {\n\t\tm = l + (r - l) / 2;\n\t\tif (block < le32_to_cpu(m->ee_block))\n\t\t\tr = m - 1;\n\t\telse\n\t\t\tl = m + 1;\n\t\text_debug(\"%p(%u):%p(%u):%p(%u) \", l, le32_to_cpu(l->ee_block),\n\t\t\t\tm, le32_to_cpu(m->ee_block),\n\t\t\t\tr, le32_to_cpu(r->ee_block));\n\t}", "\tpath->p_ext = l - 1;\n\text_debug(\" -> %d:%llu:[%d]%d \",\n\t\t\tle32_to_cpu(path->p_ext->ee_block),\n\t\t\text4_ext_pblock(path->p_ext),\n\t\t\text4_ext_is_uninitialized(path->p_ext),\n\t\t\text4_ext_get_actual_len(path->p_ext));", "#ifdef CHECK_BINSEARCH\n\t{\n\t\tstruct ext4_extent *chex, *ex;\n\t\tint k;", "\t\tchex = ex = EXT_FIRST_EXTENT(eh);\n\t\tfor (k = 0; k < le16_to_cpu(eh->eh_entries); k++, ex++) {\n\t\t\tBUG_ON(k && le32_to_cpu(ex->ee_block)\n\t\t\t\t\t <= le32_to_cpu(ex[-1].ee_block));\n\t\t\tif (block < le32_to_cpu(ex->ee_block))\n\t\t\t\tbreak;\n\t\t\tchex = ex;\n\t\t}\n\t\tBUG_ON(chex != path->p_ext);\n\t}\n#endif", "}", "int ext4_ext_tree_init(handle_t *handle, struct inode *inode)\n{\n\tstruct ext4_extent_header *eh;", "\teh = ext_inode_hdr(inode);\n\teh->eh_depth = 0;\n\teh->eh_entries = 0;\n\teh->eh_magic = EXT4_EXT_MAGIC;\n\teh->eh_max = cpu_to_le16(ext4_ext_space_root(inode, 0));\n\text4_mark_inode_dirty(handle, inode);\n\text4_ext_invalidate_cache(inode);\n\treturn 0;\n}", "struct ext4_ext_path *\next4_ext_find_extent(struct inode *inode, ext4_lblk_t block,\n\t\t\t\t\tstruct ext4_ext_path *path)\n{\n\tstruct ext4_extent_header *eh;\n\tstruct buffer_head *bh;\n\tshort int depth, i, ppos = 0, alloc = 0;", "\teh = ext_inode_hdr(inode);\n\tdepth = ext_depth(inode);", "\t/* account possible depth increase */\n\tif (!path) {\n\t\tpath = kzalloc(sizeof(struct ext4_ext_path) * (depth + 2),\n\t\t\t\tGFP_NOFS);\n\t\tif (!path)\n\t\t\treturn ERR_PTR(-ENOMEM);\n\t\talloc = 1;\n\t}\n\tpath[0].p_hdr = eh;\n\tpath[0].p_bh = NULL;", "\ti = depth;\n\t/* walk through the tree */\n\twhile (i) {\n\t\text_debug(\"depth %d: num %d, max %d\\n\",\n\t\t\t ppos, le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));", "\t\text4_ext_binsearch_idx(inode, path + ppos, block);\n\t\tpath[ppos].p_block = ext4_idx_pblock(path[ppos].p_idx);\n\t\tpath[ppos].p_depth = i;\n\t\tpath[ppos].p_ext = NULL;", "\t\tbh = sb_getblk(inode->i_sb, path[ppos].p_block);\n\t\tif (unlikely(!bh))\n\t\t\tgoto err;\n\t\tif (!bh_uptodate_or_lock(bh)) {\n\t\t\ttrace_ext4_ext_load_extent(inode, block,\n\t\t\t\t\t\tpath[ppos].p_block);\n\t\t\tif (bh_submit_read(bh) < 0) {\n\t\t\t\tput_bh(bh);\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t}\n\t\teh = ext_block_hdr(bh);\n\t\tppos++;\n\t\tif (unlikely(ppos > depth)) {\n\t\t\tput_bh(bh);\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"ppos %d > depth %d\", ppos, depth);\n\t\t\tgoto err;\n\t\t}\n\t\tpath[ppos].p_bh = bh;\n\t\tpath[ppos].p_hdr = eh;\n\t\ti--;", "\t\tif (ext4_ext_check_block(inode, eh, i, bh))\n\t\t\tgoto err;\n\t}", "\tpath[ppos].p_depth = i;\n\tpath[ppos].p_ext = NULL;\n\tpath[ppos].p_idx = NULL;", "\t/* find extent */\n\text4_ext_binsearch(inode, path + ppos, block);\n\t/* if not an empty leaf */\n\tif (path[ppos].p_ext)\n\t\tpath[ppos].p_block = ext4_ext_pblock(path[ppos].p_ext);", "\text4_ext_show_path(inode, path);", "\treturn path;", "err:\n\text4_ext_drop_refs(path);\n\tif (alloc)\n\t\tkfree(path);\n\treturn ERR_PTR(-EIO);\n}", "/*\n * ext4_ext_insert_index:\n * insert new index [@logical;@ptr] into the block at @curp;\n * check where to insert: before @curp or after @curp\n */\nstatic int ext4_ext_insert_index(handle_t *handle, struct inode *inode,\n\t\t\t\t struct ext4_ext_path *curp,\n\t\t\t\t int logical, ext4_fsblk_t ptr)\n{\n\tstruct ext4_extent_idx *ix;\n\tint len, err;", "\terr = ext4_ext_get_access(handle, inode, curp);\n\tif (err)\n\t\treturn err;", "\tif (unlikely(logical == le32_to_cpu(curp->p_idx->ei_block))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"logical %d == ei_block %d!\",\n\t\t\t\t logical, le32_to_cpu(curp->p_idx->ei_block));\n\t\treturn -EIO;\n\t}", "\tif (unlikely(le16_to_cpu(curp->p_hdr->eh_entries)\n\t\t\t >= le16_to_cpu(curp->p_hdr->eh_max))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"eh_entries %d >= eh_max %d!\",\n\t\t\t\t le16_to_cpu(curp->p_hdr->eh_entries),\n\t\t\t\t le16_to_cpu(curp->p_hdr->eh_max));\n\t\treturn -EIO;\n\t}", "\tif (logical > le32_to_cpu(curp->p_idx->ei_block)) {\n\t\t/* insert after */\n\t\text_debug(\"insert new index %d after: %llu\\n\", logical, ptr);\n\t\tix = curp->p_idx + 1;\n\t} else {\n\t\t/* insert before */\n\t\text_debug(\"insert new index %d before: %llu\\n\", logical, ptr);\n\t\tix = curp->p_idx;\n\t}", "\tlen = EXT_LAST_INDEX(curp->p_hdr) - ix + 1;\n\tBUG_ON(len < 0);\n\tif (len > 0) {\n\t\text_debug(\"insert new index %d: \"\n\t\t\t\t\"move %d indices from 0x%p to 0x%p\\n\",\n\t\t\t\tlogical, len, ix, ix + 1);\n\t\tmemmove(ix + 1, ix, len * sizeof(struct ext4_extent_idx));\n\t}", "\tif (unlikely(ix > EXT_MAX_INDEX(curp->p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"ix > EXT_MAX_INDEX!\");\n\t\treturn -EIO;\n\t}", "\tix->ei_block = cpu_to_le32(logical);\n\text4_idx_store_pblock(ix, ptr);\n\tle16_add_cpu(&curp->p_hdr->eh_entries, 1);", "\tif (unlikely(ix > EXT_LAST_INDEX(curp->p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"ix > EXT_LAST_INDEX!\");\n\t\treturn -EIO;\n\t}", "\terr = ext4_ext_dirty(handle, inode, curp);\n\text4_std_error(inode->i_sb, err);", "\treturn err;\n}", "/*\n * ext4_ext_split:\n * inserts new subtree into the path, using free index entry\n * at depth @at:\n * - allocates all needed blocks (new leaf and all intermediate index blocks)\n * - makes decision where to split\n * - moves remaining extents and index entries (right to the split point)\n * into the newly allocated blocks\n * - initializes subtree\n */\nstatic int ext4_ext_split(handle_t *handle, struct inode *inode,\n\t\t\t unsigned int flags,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t struct ext4_extent *newext, int at)\n{\n\tstruct buffer_head *bh = NULL;\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent_header *neh;\n\tstruct ext4_extent_idx *fidx;\n\tint i = at, k, m, a;\n\text4_fsblk_t newblock, oldblock;\n\t__le32 border;\n\text4_fsblk_t *ablocks = NULL; /* array of allocated blocks */\n\tint err = 0;", "\t/* make decision: where to split? */\n\t/* FIXME: now decision is simplest: at current extent */", "\t/* if current leaf will be split, then we should use\n\t * border from split point */\n\tif (unlikely(path[depth].p_ext > EXT_MAX_EXTENT(path[depth].p_hdr))) {\n\t\tEXT4_ERROR_INODE(inode, \"p_ext > EXT_MAX_EXTENT!\");\n\t\treturn -EIO;\n\t}\n\tif (path[depth].p_ext != EXT_MAX_EXTENT(path[depth].p_hdr)) {\n\t\tborder = path[depth].p_ext[1].ee_block;\n\t\text_debug(\"leaf will be split.\"\n\t\t\t\t\" next leaf starts at %d\\n\",\n\t\t\t\t le32_to_cpu(border));\n\t} else {\n\t\tborder = newext->ee_block;\n\t\text_debug(\"leaf will be added.\"\n\t\t\t\t\" next leaf starts at %d\\n\",\n\t\t\t\tle32_to_cpu(border));\n\t}", "\t/*\n\t * If error occurs, then we break processing\n\t * and mark filesystem read-only. index won't\n\t * be inserted and tree will be in consistent\n\t * state. Next mount will repair buffers too.\n\t */", "\t/*\n\t * Get array to track all allocated blocks.\n\t * We need this to handle errors and free blocks\n\t * upon them.\n\t */\n\tablocks = kzalloc(sizeof(ext4_fsblk_t) * depth, GFP_NOFS);\n\tif (!ablocks)\n\t\treturn -ENOMEM;", "\t/* allocate all needed blocks */\n\text_debug(\"allocate %d blocks for indexes/leaf\\n\", depth - at);\n\tfor (a = 0; a < depth - at; a++) {\n\t\tnewblock = ext4_ext_new_meta_block(handle, inode, path,\n\t\t\t\t\t\t newext, &err, flags);\n\t\tif (newblock == 0)\n\t\t\tgoto cleanup;\n\t\tablocks[a] = newblock;\n\t}", "\t/* initialize new leaf */\n\tnewblock = ablocks[--a];\n\tif (unlikely(newblock == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"newblock == 0!\");\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tbh = sb_getblk(inode->i_sb, newblock);\n\tif (!bh) {\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tlock_buffer(bh);", "\terr = ext4_journal_get_create_access(handle, bh);\n\tif (err)\n\t\tgoto cleanup;", "\tneh = ext_block_hdr(bh);\n\tneh->eh_entries = 0;\n\tneh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));\n\tneh->eh_magic = EXT4_EXT_MAGIC;\n\tneh->eh_depth = 0;", "\t/* move remainder of path[depth] to the new leaf */\n\tif (unlikely(path[depth].p_hdr->eh_entries !=\n\t\t path[depth].p_hdr->eh_max)) {\n\t\tEXT4_ERROR_INODE(inode, \"eh_entries %d != eh_max %d!\",\n\t\t\t\t path[depth].p_hdr->eh_entries,\n\t\t\t\t path[depth].p_hdr->eh_max);\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\t/* start copy from next extent */\n\tm = EXT_MAX_EXTENT(path[depth].p_hdr) - path[depth].p_ext++;\n\text4_ext_show_move(inode, path, newblock, depth);\n\tif (m) {\n\t\tstruct ext4_extent *ex;\n\t\tex = EXT_FIRST_EXTENT(neh);\n\t\tmemmove(ex, path[depth].p_ext, sizeof(struct ext4_extent) * m);\n\t\tle16_add_cpu(&neh->eh_entries, m);\n\t}", "\text4_extent_block_csum_set(inode, neh);\n\tset_buffer_uptodate(bh);\n\tunlock_buffer(bh);", "\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\tif (err)\n\t\tgoto cleanup;\n\tbrelse(bh);\n\tbh = NULL;", "\t/* correct old leaf */\n\tif (m) {\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\t\tle16_add_cpu(&path[depth].p_hdr->eh_entries, -m);\n\t\terr = ext4_ext_dirty(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto cleanup;", "\t}", "\t/* create intermediate indexes */\n\tk = depth - at - 1;\n\tif (unlikely(k < 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"k %d < 0!\", k);\n\t\terr = -EIO;\n\t\tgoto cleanup;\n\t}\n\tif (k)\n\t\text_debug(\"create %d intermediate indices\\n\", k);\n\t/* insert new index into current index block */\n\t/* current depth stored in i var */\n\ti = depth - 1;\n\twhile (k--) {\n\t\toldblock = newblock;\n\t\tnewblock = ablocks[--a];\n\t\tbh = sb_getblk(inode->i_sb, newblock);\n\t\tif (!bh) {\n\t\t\terr = -EIO;\n\t\t\tgoto cleanup;\n\t\t}\n\t\tlock_buffer(bh);", "\t\terr = ext4_journal_get_create_access(handle, bh);\n\t\tif (err)\n\t\t\tgoto cleanup;", "\t\tneh = ext_block_hdr(bh);\n\t\tneh->eh_entries = cpu_to_le16(1);\n\t\tneh->eh_magic = EXT4_EXT_MAGIC;\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));\n\t\tneh->eh_depth = cpu_to_le16(depth - i);\n\t\tfidx = EXT_FIRST_INDEX(neh);\n\t\tfidx->ei_block = border;\n\t\text4_idx_store_pblock(fidx, oldblock);", "\t\text_debug(\"int.index at %d (block %llu): %u -> %llu\\n\",\n\t\t\t\ti, newblock, le32_to_cpu(border), oldblock);", "\t\t/* move remainder of path[i] to the new index block */\n\t\tif (unlikely(EXT_MAX_INDEX(path[i].p_hdr) !=\n\t\t\t\t\tEXT_LAST_INDEX(path[i].p_hdr))) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"EXT_MAX_INDEX != EXT_LAST_INDEX ee_block %d!\",\n\t\t\t\t\t le32_to_cpu(path[i].p_ext->ee_block));\n\t\t\terr = -EIO;\n\t\t\tgoto cleanup;\n\t\t}\n\t\t/* start copy indexes */\n\t\tm = EXT_MAX_INDEX(path[i].p_hdr) - path[i].p_idx++;\n\t\text_debug(\"cur 0x%p, last 0x%p\\n\", path[i].p_idx,\n\t\t\t\tEXT_MAX_INDEX(path[i].p_hdr));\n\t\text4_ext_show_move(inode, path, newblock, i);\n\t\tif (m) {\n\t\t\tmemmove(++fidx, path[i].p_idx,\n\t\t\t\tsizeof(struct ext4_extent_idx) * m);\n\t\t\tle16_add_cpu(&neh->eh_entries, m);\n\t\t}\n\t\text4_extent_block_csum_set(inode, neh);\n\t\tset_buffer_uptodate(bh);\n\t\tunlock_buffer(bh);", "\t\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\t\tif (err)\n\t\t\tgoto cleanup;\n\t\tbrelse(bh);\n\t\tbh = NULL;", "\t\t/* correct old index */\n\t\tif (m) {\n\t\t\terr = ext4_ext_get_access(handle, inode, path + i);\n\t\t\tif (err)\n\t\t\t\tgoto cleanup;\n\t\t\tle16_add_cpu(&path[i].p_hdr->eh_entries, -m);\n\t\t\terr = ext4_ext_dirty(handle, inode, path + i);\n\t\t\tif (err)\n\t\t\t\tgoto cleanup;\n\t\t}", "\t\ti--;\n\t}", "\t/* insert new index */\n\terr = ext4_ext_insert_index(handle, inode, path + at,\n\t\t\t\t le32_to_cpu(border), newblock);", "cleanup:\n\tif (bh) {\n\t\tif (buffer_locked(bh))\n\t\t\tunlock_buffer(bh);\n\t\tbrelse(bh);\n\t}", "\tif (err) {\n\t\t/* free all allocated blocks in error case */\n\t\tfor (i = 0; i < depth; i++) {\n\t\t\tif (!ablocks[i])\n\t\t\t\tcontinue;\n\t\t\text4_free_blocks(handle, inode, NULL, ablocks[i], 1,\n\t\t\t\t\t EXT4_FREE_BLOCKS_METADATA);\n\t\t}\n\t}\n\tkfree(ablocks);", "\treturn err;\n}", "/*\n * ext4_ext_grow_indepth:\n * implements tree growing procedure:\n * - allocates new block\n * - moves top-level data (index block or leaf) into the new block\n * - initializes new top-level, creating index that points to the\n * just created block\n */\nstatic int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,\n\t\t\t\t unsigned int flags,\n\t\t\t\t struct ext4_extent *newext)\n{\n\tstruct ext4_extent_header *neh;\n\tstruct buffer_head *bh;\n\text4_fsblk_t newblock;\n\tint err = 0;", "\tnewblock = ext4_ext_new_meta_block(handle, inode, NULL,\n\t\tnewext, &err, flags);\n\tif (newblock == 0)\n\t\treturn err;", "\tbh = sb_getblk(inode->i_sb, newblock);\n\tif (!bh) {\n\t\terr = -EIO;\n\t\text4_std_error(inode->i_sb, err);\n\t\treturn err;\n\t}\n\tlock_buffer(bh);", "\terr = ext4_journal_get_create_access(handle, bh);\n\tif (err) {\n\t\tunlock_buffer(bh);\n\t\tgoto out;\n\t}", "\t/* move top-level index/leaf into new block */\n\tmemmove(bh->b_data, EXT4_I(inode)->i_data,\n\t\tsizeof(EXT4_I(inode)->i_data));", "\t/* set size of new block */\n\tneh = ext_block_hdr(bh);\n\t/* old root could have indexes or leaves\n\t * so calculate e_max right way */\n\tif (ext_depth(inode))\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0));\n\telse\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0));\n\tneh->eh_magic = EXT4_EXT_MAGIC;\n\text4_extent_block_csum_set(inode, neh);\n\tset_buffer_uptodate(bh);\n\tunlock_buffer(bh);", "\terr = ext4_handle_dirty_metadata(handle, inode, bh);\n\tif (err)\n\t\tgoto out;", "\t/* Update top-level index: num,max,pointer */\n\tneh = ext_inode_hdr(inode);\n\tneh->eh_entries = cpu_to_le16(1);\n\text4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock);\n\tif (neh->eh_depth == 0) {\n\t\t/* Root extent block becomes index block */\n\t\tneh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0));\n\t\tEXT_FIRST_INDEX(neh)->ei_block =\n\t\t\tEXT_FIRST_EXTENT(neh)->ee_block;\n\t}\n\text_debug(\"new root: num %d(%d), lblock %d, ptr %llu\\n\",\n\t\t le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max),\n\t\t le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block),\n\t\t ext4_idx_pblock(EXT_FIRST_INDEX(neh)));", "\tle16_add_cpu(&neh->eh_depth, 1);\n\text4_mark_inode_dirty(handle, inode);\nout:\n\tbrelse(bh);", "\treturn err;\n}", "/*\n * ext4_ext_create_new_leaf:\n * finds empty index and adds new leaf.\n * if no free index is found, then it requests in-depth growing.\n */\nstatic int ext4_ext_create_new_leaf(handle_t *handle, struct inode *inode,\n\t\t\t\t unsigned int flags,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t struct ext4_extent *newext)\n{\n\tstruct ext4_ext_path *curp;\n\tint depth, i, err = 0;", "repeat:\n\ti = depth = ext_depth(inode);", "\t/* walk up to the tree and look for free index entry */\n\tcurp = path + depth;\n\twhile (i > 0 && !EXT_HAS_FREE_INDEX(curp)) {\n\t\ti--;\n\t\tcurp--;\n\t}", "\t/* we use already allocated block for index block,\n\t * so subsequent data blocks should be contiguous */\n\tif (EXT_HAS_FREE_INDEX(curp)) {\n\t\t/* if we found index with free entry, then use that\n\t\t * entry: create all needed subtree and add new leaf */\n\t\terr = ext4_ext_split(handle, inode, flags, path, newext, i);\n\t\tif (err)\n\t\t\tgoto out;", "\t\t/* refill path */\n\t\text4_ext_drop_refs(path);\n\t\tpath = ext4_ext_find_extent(inode,\n\t\t\t\t (ext4_lblk_t)le32_to_cpu(newext->ee_block),\n\t\t\t\t path);\n\t\tif (IS_ERR(path))\n\t\t\terr = PTR_ERR(path);\n\t} else {\n\t\t/* tree is full, time to grow in depth */\n\t\terr = ext4_ext_grow_indepth(handle, inode, flags, newext);\n\t\tif (err)\n\t\t\tgoto out;", "\t\t/* refill path */\n\t\text4_ext_drop_refs(path);\n\t\tpath = ext4_ext_find_extent(inode,\n\t\t\t\t (ext4_lblk_t)le32_to_cpu(newext->ee_block),\n\t\t\t\t path);\n\t\tif (IS_ERR(path)) {\n\t\t\terr = PTR_ERR(path);\n\t\t\tgoto out;\n\t\t}", "\t\t/*\n\t\t * only first (depth 0 -> 1) produces free space;\n\t\t * in all other cases we have to split the grown tree\n\t\t */\n\t\tdepth = ext_depth(inode);\n\t\tif (path[depth].p_hdr->eh_entries == path[depth].p_hdr->eh_max) {\n\t\t\t/* now we need to split */\n\t\t\tgoto repeat;\n\t\t}\n\t}", "out:\n\treturn err;\n}", "/*\n * search the closest allocated block to the left for *logical\n * and returns it at @logical + it's physical address at @phys\n * if *logical is the smallest allocated block, the function\n * returns 0 at @phys\n * return value contains 0 (success) or error code\n */\nstatic int ext4_ext_search_left(struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\text4_lblk_t *logical, ext4_fsblk_t *phys)\n{\n\tstruct ext4_extent_idx *ix;\n\tstruct ext4_extent *ex;\n\tint depth, ee_len;", "\tif (unlikely(path == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path == NULL *logical %d!\", *logical);\n\t\treturn -EIO;\n\t}\n\tdepth = path->p_depth;\n\t*phys = 0;", "\tif (depth == 0 && path->p_ext == NULL)\n\t\treturn 0;", "\t/* usually extent in the path covers blocks smaller\n\t * then *logical, but it can be that extent is the\n\t * first one in the file */", "\tex = path[depth].p_ext;\n\tee_len = ext4_ext_get_actual_len(ex);\n\tif (*logical < le32_to_cpu(ex->ee_block)) {\n\t\tif (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"EXT_FIRST_EXTENT != ex *logical %d ee_block %d!\",\n\t\t\t\t\t *logical, le32_to_cpu(ex->ee_block));\n\t\t\treturn -EIO;\n\t\t}\n\t\twhile (--depth >= 0) {\n\t\t\tix = path[depth].p_idx;\n\t\t\tif (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"ix (%d) != EXT_FIRST_INDEX (%d) (depth %d)!\",\n\t\t\t\t ix != NULL ? le32_to_cpu(ix->ei_block) : 0,\n\t\t\t\t EXT_FIRST_INDEX(path[depth].p_hdr) != NULL ?\n\t\tle32_to_cpu(EXT_FIRST_INDEX(path[depth].p_hdr)->ei_block) : 0,\n\t\t\t\t depth);\n\t\t\t\treturn -EIO;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}", "\tif (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"logical %d < ee_block %d + ee_len %d!\",\n\t\t\t\t *logical, le32_to_cpu(ex->ee_block), ee_len);\n\t\treturn -EIO;\n\t}", "\t*logical = le32_to_cpu(ex->ee_block) + ee_len - 1;\n\t*phys = ext4_ext_pblock(ex) + ee_len - 1;\n\treturn 0;\n}", "/*\n * search the closest allocated block to the right for *logical\n * and returns it at @logical + it's physical address at @phys\n * if *logical is the largest allocated block, the function\n * returns 0 at @phys\n * return value contains 0 (success) or error code\n */\nstatic int ext4_ext_search_right(struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t ext4_lblk_t *logical, ext4_fsblk_t *phys,\n\t\t\t\t struct ext4_extent **ret_ex)\n{\n\tstruct buffer_head *bh = NULL;\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent_idx *ix;\n\tstruct ext4_extent *ex;\n\text4_fsblk_t block;\n\tint depth;\t/* Note, NOT eh_depth; depth from top of tree */\n\tint ee_len;", "\tif (unlikely(path == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path == NULL *logical %d!\", *logical);\n\t\treturn -EIO;\n\t}\n\tdepth = path->p_depth;\n\t*phys = 0;", "\tif (depth == 0 && path->p_ext == NULL)\n\t\treturn 0;", "\t/* usually extent in the path covers blocks smaller\n\t * then *logical, but it can be that extent is the\n\t * first one in the file */", "\tex = path[depth].p_ext;\n\tee_len = ext4_ext_get_actual_len(ex);\n\tif (*logical < le32_to_cpu(ex->ee_block)) {\n\t\tif (unlikely(EXT_FIRST_EXTENT(path[depth].p_hdr) != ex)) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"first_extent(path[%d].p_hdr) != ex\",\n\t\t\t\t\t depth);\n\t\t\treturn -EIO;\n\t\t}\n\t\twhile (--depth >= 0) {\n\t\t\tix = path[depth].p_idx;\n\t\t\tif (unlikely(ix != EXT_FIRST_INDEX(path[depth].p_hdr))) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t\t \"ix != EXT_FIRST_INDEX *logical %d!\",\n\t\t\t\t\t\t *logical);\n\t\t\t\treturn -EIO;\n\t\t\t}\n\t\t}\n\t\tgoto found_extent;\n\t}", "\tif (unlikely(*logical < (le32_to_cpu(ex->ee_block) + ee_len))) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"logical %d < ee_block %d + ee_len %d!\",\n\t\t\t\t *logical, le32_to_cpu(ex->ee_block), ee_len);\n\t\treturn -EIO;\n\t}", "\tif (ex != EXT_LAST_EXTENT(path[depth].p_hdr)) {\n\t\t/* next allocated block in this leaf */\n\t\tex++;\n\t\tgoto found_extent;\n\t}", "\t/* go up and search for index to the right */\n\twhile (--depth >= 0) {\n\t\tix = path[depth].p_idx;\n\t\tif (ix != EXT_LAST_INDEX(path[depth].p_hdr))\n\t\t\tgoto got_index;\n\t}", "\t/* we've gone up to the root and found no index to the right */\n\treturn 0;", "got_index:\n\t/* we've found index to the right, let's\n\t * follow it and find the closest allocated\n\t * block to the right */\n\tix++;\n\tblock = ext4_idx_pblock(ix);\n\twhile (++depth < path->p_depth) {\n\t\tbh = sb_bread(inode->i_sb, block);\n\t\tif (bh == NULL)\n\t\t\treturn -EIO;\n\t\teh = ext_block_hdr(bh);\n\t\t/* subtract from p_depth to get proper eh_depth */\n\t\tif (ext4_ext_check_block(inode, eh,\n\t\t\t\t\t path->p_depth - depth, bh)) {\n\t\t\tput_bh(bh);\n\t\t\treturn -EIO;\n\t\t}\n\t\tix = EXT_FIRST_INDEX(eh);\n\t\tblock = ext4_idx_pblock(ix);\n\t\tput_bh(bh);\n\t}", "\tbh = sb_bread(inode->i_sb, block);\n\tif (bh == NULL)\n\t\treturn -EIO;\n\teh = ext_block_hdr(bh);\n\tif (ext4_ext_check_block(inode, eh, path->p_depth - depth, bh)) {\n\t\tput_bh(bh);\n\t\treturn -EIO;\n\t}\n\tex = EXT_FIRST_EXTENT(eh);\nfound_extent:\n\t*logical = le32_to_cpu(ex->ee_block);\n\t*phys = ext4_ext_pblock(ex);\n\t*ret_ex = ex;\n\tif (bh)\n\t\tput_bh(bh);\n\treturn 0;\n}", "/*\n * ext4_ext_next_allocated_block:\n * returns allocated block in subsequent extent or EXT_MAX_BLOCKS.\n * NOTE: it considers block number from index entry as\n * allocated block. Thus, index entries have to be consistent\n * with leaves.\n */\nstatic ext4_lblk_t\next4_ext_next_allocated_block(struct ext4_ext_path *path)\n{\n\tint depth;", "\tBUG_ON(path == NULL);\n\tdepth = path->p_depth;", "\tif (depth == 0 && path->p_ext == NULL)\n\t\treturn EXT_MAX_BLOCKS;", "\twhile (depth >= 0) {\n\t\tif (depth == path->p_depth) {\n\t\t\t/* leaf */\n\t\t\tif (path[depth].p_ext &&\n\t\t\t\tpath[depth].p_ext !=\n\t\t\t\t\tEXT_LAST_EXTENT(path[depth].p_hdr))\n\t\t\t return le32_to_cpu(path[depth].p_ext[1].ee_block);\n\t\t} else {\n\t\t\t/* index */\n\t\t\tif (path[depth].p_idx !=\n\t\t\t\t\tEXT_LAST_INDEX(path[depth].p_hdr))\n\t\t\t return le32_to_cpu(path[depth].p_idx[1].ei_block);\n\t\t}\n\t\tdepth--;\n\t}", "\treturn EXT_MAX_BLOCKS;\n}", "/*\n * ext4_ext_next_leaf_block:\n * returns first allocated block from next leaf or EXT_MAX_BLOCKS\n */\nstatic ext4_lblk_t ext4_ext_next_leaf_block(struct ext4_ext_path *path)\n{\n\tint depth;", "\tBUG_ON(path == NULL);\n\tdepth = path->p_depth;", "\t/* zero-tree has no leaf blocks at all */\n\tif (depth == 0)\n\t\treturn EXT_MAX_BLOCKS;", "\t/* go to index block */\n\tdepth--;", "\twhile (depth >= 0) {\n\t\tif (path[depth].p_idx !=\n\t\t\t\tEXT_LAST_INDEX(path[depth].p_hdr))\n\t\t\treturn (ext4_lblk_t)\n\t\t\t\tle32_to_cpu(path[depth].p_idx[1].ei_block);\n\t\tdepth--;\n\t}", "\treturn EXT_MAX_BLOCKS;\n}", "/*\n * ext4_ext_correct_indexes:\n * if leaf gets modified and modified extent is first in the leaf,\n * then we have to correct all indexes above.\n * TODO: do we need to correct tree in all cases?\n */\nstatic int ext4_ext_correct_indexes(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path)\n{\n\tstruct ext4_extent_header *eh;\n\tint depth = ext_depth(inode);\n\tstruct ext4_extent *ex;\n\t__le32 border;\n\tint k, err = 0;", "\teh = path[depth].p_hdr;\n\tex = path[depth].p_ext;", "\tif (unlikely(ex == NULL || eh == NULL)) {\n\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t \"ex %p == NULL or eh %p == NULL\", ex, eh);\n\t\treturn -EIO;\n\t}", "\tif (depth == 0) {\n\t\t/* there is no tree at all */\n\t\treturn 0;\n\t}", "\tif (ex != EXT_FIRST_EXTENT(eh)) {\n\t\t/* we correct tree if first leaf got modified only */\n\t\treturn 0;\n\t}", "\t/*\n\t * TODO: we need correction if border is smaller than current one\n\t */\n\tk = depth - 1;\n\tborder = path[depth].p_ext->ee_block;\n\terr = ext4_ext_get_access(handle, inode, path + k);\n\tif (err)\n\t\treturn err;\n\tpath[k].p_idx->ei_block = border;\n\terr = ext4_ext_dirty(handle, inode, path + k);\n\tif (err)\n\t\treturn err;", "\twhile (k--) {\n\t\t/* change all left-side indexes */\n\t\tif (path[k+1].p_idx != EXT_FIRST_INDEX(path[k+1].p_hdr))\n\t\t\tbreak;\n\t\terr = ext4_ext_get_access(handle, inode, path + k);\n\t\tif (err)\n\t\t\tbreak;\n\t\tpath[k].p_idx->ei_block = border;\n\t\terr = ext4_ext_dirty(handle, inode, path + k);\n\t\tif (err)\n\t\t\tbreak;\n\t}", "\treturn err;\n}", "int\next4_can_extents_be_merged(struct inode *inode, struct ext4_extent *ex1,\n\t\t\t\tstruct ext4_extent *ex2)\n{\n\tunsigned short ext1_ee_len, ext2_ee_len, max_len;", "\t/*\n\t * Make sure that either both extents are uninitialized, or\n\t * both are _not_.\n\t */\n\tif (ext4_ext_is_uninitialized(ex1) ^ ext4_ext_is_uninitialized(ex2))\n\t\treturn 0;", "\tif (ext4_ext_is_uninitialized(ex1))\n\t\tmax_len = EXT_UNINIT_MAX_LEN;\n\telse\n\t\tmax_len = EXT_INIT_MAX_LEN;", "\text1_ee_len = ext4_ext_get_actual_len(ex1);\n\text2_ee_len = ext4_ext_get_actual_len(ex2);", "\tif (le32_to_cpu(ex1->ee_block) + ext1_ee_len !=\n\t\t\tle32_to_cpu(ex2->ee_block))\n\t\treturn 0;", "\t/*\n\t * To allow future support for preallocated extents to be added\n\t * as an RO_COMPAT feature, refuse to merge to extents if\n\t * this can result in the top bit of ee_len being set.\n\t */\n\tif (ext1_ee_len + ext2_ee_len > max_len)\n\t\treturn 0;\n#ifdef AGGRESSIVE_TEST\n\tif (ext1_ee_len >= 4)\n\t\treturn 0;\n#endif", "\tif (ext4_ext_pblock(ex1) + ext1_ee_len == ext4_ext_pblock(ex2))\n\t\treturn 1;\n\treturn 0;\n}", "/*\n * This function tries to merge the \"ex\" extent to the next extent in the tree.\n * It always tries to merge towards right. If you want to merge towards\n * left, pass \"ex - 1\" as argument instead of \"ex\".\n * Returns 0 if the extents (ex and ex+1) were _not_ merged and returns\n * 1 if they got merged.\n */\nstatic int ext4_ext_try_to_merge_right(struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t struct ext4_extent *ex)\n{\n\tstruct ext4_extent_header *eh;\n\tunsigned int depth, len;\n\tint merge_done = 0;\n\tint uninitialized = 0;", "\tdepth = ext_depth(inode);\n\tBUG_ON(path[depth].p_hdr == NULL);\n\teh = path[depth].p_hdr;", "\twhile (ex < EXT_LAST_EXTENT(eh)) {\n\t\tif (!ext4_can_extents_be_merged(inode, ex, ex + 1))\n\t\t\tbreak;\n\t\t/* merge with next extent! */\n\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\tex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)\n\t\t\t\t+ ext4_ext_get_actual_len(ex + 1));\n\t\tif (uninitialized)\n\t\t\text4_ext_mark_uninitialized(ex);", "\t\tif (ex + 1 < EXT_LAST_EXTENT(eh)) {\n\t\t\tlen = (EXT_LAST_EXTENT(eh) - ex - 1)\n\t\t\t\t* sizeof(struct ext4_extent);\n\t\t\tmemmove(ex + 1, ex + 2, len);\n\t\t}\n\t\tle16_add_cpu(&eh->eh_entries, -1);\n\t\tmerge_done = 1;\n\t\tWARN_ON(eh->eh_entries == 0);\n\t\tif (!eh->eh_entries)\n\t\t\tEXT4_ERROR_INODE(inode, \"eh->eh_entries = 0!\");\n\t}", "\treturn merge_done;\n}", "/*\n * This function does a very simple check to see if we can collapse\n * an extent tree with a single extent tree leaf block into the inode.\n */\nstatic void ext4_ext_try_to_merge_up(handle_t *handle,\n\t\t\t\t struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path)\n{\n\tsize_t s;\n\tunsigned max_root = ext4_ext_space_root(inode, 0);\n\text4_fsblk_t blk;", "\tif ((path[0].p_depth != 1) ||\n\t (le16_to_cpu(path[0].p_hdr->eh_entries) != 1) ||\n\t (le16_to_cpu(path[1].p_hdr->eh_entries) > max_root))\n\t\treturn;", "\t/*\n\t * We need to modify the block allocation bitmap and the block\n\t * group descriptor to release the extent tree block. If we\n\t * can't get the journal credits, give up.\n\t */\n\tif (ext4_journal_extend(handle, 2))\n\t\treturn;", "\t/*\n\t * Copy the extent data up to the inode\n\t */\n\tblk = ext4_idx_pblock(path[0].p_idx);\n\ts = le16_to_cpu(path[1].p_hdr->eh_entries) *\n\t\tsizeof(struct ext4_extent_idx);\n\ts += sizeof(struct ext4_extent_header);", "\tmemcpy(path[0].p_hdr, path[1].p_hdr, s);\n\tpath[0].p_depth = 0;\n\tpath[0].p_ext = EXT_FIRST_EXTENT(path[0].p_hdr) +\n\t\t(path[1].p_ext - EXT_FIRST_EXTENT(path[1].p_hdr));\n\tpath[0].p_hdr->eh_max = cpu_to_le16(max_root);", "\tbrelse(path[1].p_bh);\n\text4_free_blocks(handle, inode, NULL, blk, 1,\n\t\t\t EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);\n}", "/*\n * This function tries to merge the @ex extent to neighbours in the tree.\n * return 1 if merge left else 0.\n */\nstatic void ext4_ext_try_to_merge(handle_t *handle,\n\t\t\t\t struct inode *inode,\n\t\t\t\t struct ext4_ext_path *path,\n\t\t\t\t struct ext4_extent *ex) {\n\tstruct ext4_extent_header *eh;\n\tunsigned int depth;\n\tint merge_done = 0;", "\tdepth = ext_depth(inode);\n\tBUG_ON(path[depth].p_hdr == NULL);\n\teh = path[depth].p_hdr;", "\tif (ex > EXT_FIRST_EXTENT(eh))\n\t\tmerge_done = ext4_ext_try_to_merge_right(inode, path, ex - 1);", "\tif (!merge_done)\n\t\t(void) ext4_ext_try_to_merge_right(inode, path, ex);", "\text4_ext_try_to_merge_up(handle, inode, path);\n}", "/*\n * check if a portion of the \"newext\" extent overlaps with an\n * existing extent.\n *\n * If there is an overlap discovered, it updates the length of the newext\n * such that there will be no overlap, and then returns 1.\n * If there is no overlap found, it returns 0.\n */\nstatic unsigned int ext4_ext_check_overlap(struct ext4_sb_info *sbi,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t struct ext4_extent *newext,\n\t\t\t\t\t struct ext4_ext_path *path)\n{\n\text4_lblk_t b1, b2;\n\tunsigned int depth, len1;\n\tunsigned int ret = 0;", "\tb1 = le32_to_cpu(newext->ee_block);\n\tlen1 = ext4_ext_get_actual_len(newext);\n\tdepth = ext_depth(inode);\n\tif (!path[depth].p_ext)\n\t\tgoto out;\n\tb2 = le32_to_cpu(path[depth].p_ext->ee_block);\n\tb2 &= ~(sbi->s_cluster_ratio - 1);", "\t/*\n\t * get the next allocated block if the extent in the path\n\t * is before the requested block(s)\n\t */\n\tif (b2 < b1) {\n\t\tb2 = ext4_ext_next_allocated_block(path);\n\t\tif (b2 == EXT_MAX_BLOCKS)\n\t\t\tgoto out;\n\t\tb2 &= ~(sbi->s_cluster_ratio - 1);\n\t}", "\t/* check for wrap through zero on extent logical start block*/\n\tif (b1 + len1 < b1) {\n\t\tlen1 = EXT_MAX_BLOCKS - b1;\n\t\tnewext->ee_len = cpu_to_le16(len1);\n\t\tret = 1;\n\t}", "\t/* check for overlap */\n\tif (b1 + len1 > b2) {\n\t\tnewext->ee_len = cpu_to_le16(b2 - b1);\n\t\tret = 1;\n\t}\nout:\n\treturn ret;\n}", "/*\n * ext4_ext_insert_extent:\n * tries to merge requsted extent into the existing extent or\n * inserts requested extent as new one into the tree,\n * creating new leaf in the no-space case.\n */\nint ext4_ext_insert_extent(handle_t *handle, struct inode *inode,\n\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\tstruct ext4_extent *newext, int flag)\n{\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *ex, *fex;\n\tstruct ext4_extent *nearex; /* nearest extent */\n\tstruct ext4_ext_path *npath = NULL;\n\tint depth, len, err;\n\text4_lblk_t next;\n\tunsigned uninitialized = 0;\n\tint flags = 0;", "\tif (unlikely(ext4_ext_get_actual_len(newext) == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"ext4_ext_get_actual_len(newext) == 0\");\n\t\treturn -EIO;\n\t}\n\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tif (unlikely(path[depth].p_hdr == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path[%d].p_hdr == NULL\", depth);\n\t\treturn -EIO;\n\t}", "\t/* try to insert block into found extent and return */\n\tif (ex && !(flag & EXT4_GET_BLOCKS_PRE_IO)\n\t\t&& ext4_can_extents_be_merged(inode, ex, newext)) {\n\t\text_debug(\"append [%d]%d block to %u:[%d]%d (from %llu)\\n\",\n\t\t\t ext4_ext_is_uninitialized(newext),\n\t\t\t ext4_ext_get_actual_len(newext),\n\t\t\t le32_to_cpu(ex->ee_block),\n\t\t\t ext4_ext_is_uninitialized(ex),\n\t\t\t ext4_ext_get_actual_len(ex),\n\t\t\t ext4_ext_pblock(ex));\n\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\treturn err;", "\t\t/*\n\t\t * ext4_can_extents_be_merged should have checked that either\n\t\t * both extents are uninitialized, or both aren't. Thus we\n\t\t * need to check only one of them here.\n\t\t */\n\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\tex->ee_len = cpu_to_le16(ext4_ext_get_actual_len(ex)\n\t\t\t\t\t+ ext4_ext_get_actual_len(newext));\n\t\tif (uninitialized)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\teh = path[depth].p_hdr;\n\t\tnearex = ex;\n\t\tgoto merge;\n\t}", "\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\tif (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max))\n\t\tgoto has_space;", "\t/* probably next leaf has space for us? */\n\tfex = EXT_LAST_EXTENT(eh);\n\tnext = EXT_MAX_BLOCKS;\n\tif (le32_to_cpu(newext->ee_block) > le32_to_cpu(fex->ee_block))\n\t\tnext = ext4_ext_next_leaf_block(path);\n\tif (next != EXT_MAX_BLOCKS) {\n\t\text_debug(\"next leaf block - %u\\n\", next);\n\t\tBUG_ON(npath != NULL);\n\t\tnpath = ext4_ext_find_extent(inode, next, NULL);\n\t\tif (IS_ERR(npath))\n\t\t\treturn PTR_ERR(npath);\n\t\tBUG_ON(npath->p_depth != path->p_depth);\n\t\teh = npath[depth].p_hdr;\n\t\tif (le16_to_cpu(eh->eh_entries) < le16_to_cpu(eh->eh_max)) {\n\t\t\text_debug(\"next leaf isn't full(%d)\\n\",\n\t\t\t\t le16_to_cpu(eh->eh_entries));\n\t\t\tpath = npath;\n\t\t\tgoto has_space;\n\t\t}\n\t\text_debug(\"next leaf has no free space(%d,%d)\\n\",\n\t\t\t le16_to_cpu(eh->eh_entries), le16_to_cpu(eh->eh_max));\n\t}", "\t/*\n\t * There is no free space in the found leaf.\n\t * We're gonna add a new leaf in the tree.\n\t */\n\tif (flag & EXT4_GET_BLOCKS_PUNCH_OUT_EXT)\n\t\tflags = EXT4_MB_USE_ROOT_BLOCKS;\n\terr = ext4_ext_create_new_leaf(handle, inode, flags, path, newext);\n\tif (err)\n\t\tgoto cleanup;\n\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;", "has_space:\n\tnearex = path[depth].p_ext;", "\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto cleanup;", "\tif (!nearex) {\n\t\t/* there is no extent in this leaf, create first one */\n\t\text_debug(\"first extent in the leaf: %u:%llu:[%d]%d\\n\",\n\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\text4_ext_pblock(newext),\n\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\text4_ext_get_actual_len(newext));\n\t\tnearex = EXT_FIRST_EXTENT(eh);\n\t} else {\n\t\tif (le32_to_cpu(newext->ee_block)\n\t\t\t > le32_to_cpu(nearex->ee_block)) {\n\t\t\t/* Insert after */\n\t\t\text_debug(\"insert %u:%llu:[%d]%d before: \"\n\t\t\t\t\t\"nearest %p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text4_ext_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tnearex);\n\t\t\tnearex++;\n\t\t} else {\n\t\t\t/* Insert before */\n\t\t\tBUG_ON(newext->ee_block == nearex->ee_block);\n\t\t\text_debug(\"insert %u:%llu:[%d]%d after: \"\n\t\t\t\t\t\"nearest %p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text4_ext_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tnearex);\n\t\t}\n\t\tlen = EXT_LAST_EXTENT(eh) - nearex + 1;\n\t\tif (len > 0) {\n\t\t\text_debug(\"insert %u:%llu:[%d]%d: \"\n\t\t\t\t\t\"move %d extents from 0x%p to 0x%p\\n\",\n\t\t\t\t\tle32_to_cpu(newext->ee_block),\n\t\t\t\t\text4_ext_pblock(newext),\n\t\t\t\t\text4_ext_is_uninitialized(newext),\n\t\t\t\t\text4_ext_get_actual_len(newext),\n\t\t\t\t\tlen, nearex, nearex + 1);\n\t\t\tmemmove(nearex + 1, nearex,\n\t\t\t\tlen * sizeof(struct ext4_extent));\n\t\t}\n\t}", "\tle16_add_cpu(&eh->eh_entries, 1);\n\tpath[depth].p_ext = nearex;\n\tnearex->ee_block = newext->ee_block;\n\text4_ext_store_pblock(nearex, ext4_ext_pblock(newext));\n\tnearex->ee_len = newext->ee_len;", "merge:\n\t/* try to merge extents */\n\tif (!(flag & EXT4_GET_BLOCKS_PRE_IO))\n\t\text4_ext_try_to_merge(handle, inode, path, nearex);", "\n\t/* time to correct all indexes above */\n\terr = ext4_ext_correct_indexes(handle, inode, path);\n\tif (err)\n\t\tgoto cleanup;", "\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);", "cleanup:\n\tif (npath) {\n\t\text4_ext_drop_refs(npath);\n\t\tkfree(npath);\n\t}\n\text4_ext_invalidate_cache(inode);\n\treturn err;\n}", "static int ext4_ext_walk_space(struct inode *inode, ext4_lblk_t block,\n\t\t\t ext4_lblk_t num, ext_prepare_callback func,\n\t\t\t void *cbdata)\n{\n\tstruct ext4_ext_path *path = NULL;\n\tstruct ext4_ext_cache cbex;\n\tstruct ext4_extent *ex;\n\text4_lblk_t next, start = 0, end = 0;\n\text4_lblk_t last = block + num;\n\tint depth, exists, err = 0;", "\tBUG_ON(func == NULL);\n\tBUG_ON(inode == NULL);", "\twhile (block < last && block != EXT_MAX_BLOCKS) {\n\t\tnum = last - block;\n\t\t/* find extent for this block */\n\t\tdown_read(&EXT4_I(inode)->i_data_sem);\n\t\tpath = ext4_ext_find_extent(inode, block, path);\n\t\tup_read(&EXT4_I(inode)->i_data_sem);\n\t\tif (IS_ERR(path)) {\n\t\t\terr = PTR_ERR(path);\n\t\t\tpath = NULL;\n\t\t\tbreak;\n\t\t}", "\t\tdepth = ext_depth(inode);\n\t\tif (unlikely(path[depth].p_hdr == NULL)) {\n\t\t\tEXT4_ERROR_INODE(inode, \"path[%d].p_hdr == NULL\", depth);\n\t\t\terr = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\tex = path[depth].p_ext;\n\t\tnext = ext4_ext_next_allocated_block(path);", "\t\texists = 0;\n\t\tif (!ex) {\n\t\t\t/* there is no extent yet, so try to allocate\n\t\t\t * all requested space */\n\t\t\tstart = block;\n\t\t\tend = block + num;\n\t\t} else if (le32_to_cpu(ex->ee_block) > block) {\n\t\t\t/* need to allocate space before found extent */\n\t\t\tstart = block;\n\t\t\tend = le32_to_cpu(ex->ee_block);\n\t\t\tif (block + num < end)\n\t\t\t\tend = block + num;\n\t\t} else if (block >= le32_to_cpu(ex->ee_block)\n\t\t\t\t\t+ ext4_ext_get_actual_len(ex)) {\n\t\t\t/* need to allocate space after found extent */\n\t\t\tstart = block;\n\t\t\tend = block + num;\n\t\t\tif (end >= next)\n\t\t\t\tend = next;\n\t\t} else if (block >= le32_to_cpu(ex->ee_block)) {\n\t\t\t/*\n\t\t\t * some part of requested space is covered\n\t\t\t * by found extent\n\t\t\t */\n\t\t\tstart = block;\n\t\t\tend = le32_to_cpu(ex->ee_block)\n\t\t\t\t+ ext4_ext_get_actual_len(ex);\n\t\t\tif (block + num < end)\n\t\t\t\tend = block + num;\n\t\t\texists = 1;\n\t\t} else {\n\t\t\tBUG();\n\t\t}\n\t\tBUG_ON(end <= start);", "\t\tif (!exists) {\n\t\t\tcbex.ec_block = start;\n\t\t\tcbex.ec_len = end - start;\n\t\t\tcbex.ec_start = 0;\n\t\t} else {\n\t\t\tcbex.ec_block = le32_to_cpu(ex->ee_block);\n\t\t\tcbex.ec_len = ext4_ext_get_actual_len(ex);\n\t\t\tcbex.ec_start = ext4_ext_pblock(ex);\n\t\t}", "\t\tif (unlikely(cbex.ec_len == 0)) {\n\t\t\tEXT4_ERROR_INODE(inode, \"cbex.ec_len == 0\");\n\t\t\terr = -EIO;\n\t\t\tbreak;\n\t\t}\n\t\terr = func(inode, next, &cbex, ex, cbdata);\n\t\text4_ext_drop_refs(path);", "\t\tif (err < 0)\n\t\t\tbreak;", "\t\tif (err == EXT_REPEAT)\n\t\t\tcontinue;\n\t\telse if (err == EXT_BREAK) {\n\t\t\terr = 0;\n\t\t\tbreak;\n\t\t}", "\t\tif (ext_depth(inode) != depth) {\n\t\t\t/* depth was changed. we have to realloc path */\n\t\t\tkfree(path);\n\t\t\tpath = NULL;\n\t\t}", "\t\tblock = cbex.ec_block + cbex.ec_len;\n\t}", "\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}", "\treturn err;\n}", "static void\next4_ext_put_in_cache(struct inode *inode, ext4_lblk_t block,\n\t\t\t__u32 len, ext4_fsblk_t start)\n{\n\tstruct ext4_ext_cache *cex;\n\tBUG_ON(len == 0);\n\tspin_lock(&EXT4_I(inode)->i_block_reservation_lock);\n\ttrace_ext4_ext_put_in_cache(inode, block, len, start);\n\tcex = &EXT4_I(inode)->i_cached_extent;\n\tcex->ec_block = block;\n\tcex->ec_len = len;\n\tcex->ec_start = start;\n\tspin_unlock(&EXT4_I(inode)->i_block_reservation_lock);\n}", "/*\n * ext4_ext_put_gap_in_cache:\n * calculate boundaries of the gap that the requested block fits into\n * and cache this gap\n */\nstatic void\next4_ext_put_gap_in_cache(struct inode *inode, struct ext4_ext_path *path,\n\t\t\t\text4_lblk_t block)\n{\n\tint depth = ext_depth(inode);\n\tunsigned long len;\n\text4_lblk_t lblock;\n\tstruct ext4_extent *ex;", "\tex = path[depth].p_ext;\n\tif (ex == NULL) {\n\t\t/* there is no extent yet, so gap is [0;-] */\n\t\tlblock = 0;\n\t\tlen = EXT_MAX_BLOCKS;\n\t\text_debug(\"cache gap(whole file):\");\n\t} else if (block < le32_to_cpu(ex->ee_block)) {\n\t\tlblock = block;\n\t\tlen = le32_to_cpu(ex->ee_block) - block;\n\t\text_debug(\"cache gap(before): %u [%u:%u]\",\n\t\t\t\tblock,\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\t ext4_ext_get_actual_len(ex));\n\t} else if (block >= le32_to_cpu(ex->ee_block)\n\t\t\t+ ext4_ext_get_actual_len(ex)) {\n\t\text4_lblk_t next;\n\t\tlblock = le32_to_cpu(ex->ee_block)\n\t\t\t+ ext4_ext_get_actual_len(ex);", "\t\tnext = ext4_ext_next_allocated_block(path);\n\t\text_debug(\"cache gap(after): [%u:%u] %u\",\n\t\t\t\tle32_to_cpu(ex->ee_block),\n\t\t\t\text4_ext_get_actual_len(ex),\n\t\t\t\tblock);\n\t\tBUG_ON(next == lblock);\n\t\tlen = next - lblock;\n\t} else {\n\t\tlblock = len = 0;\n\t\tBUG();\n\t}", "\text_debug(\" -> %u:%lu\\n\", lblock, len);\n\text4_ext_put_in_cache(inode, lblock, len, 0);\n}", "/*\n * ext4_ext_in_cache()\n * Checks to see if the given block is in the cache.\n * If it is, the cached extent is stored in the given\n * cache extent pointer.\n *\n * @inode: The files inode\n * @block: The block to look for in the cache\n * @ex: Pointer where the cached extent will be stored\n * if it contains block\n *\n * Return 0 if cache is invalid; 1 if the cache is valid\n */\nstatic int\next4_ext_in_cache(struct inode *inode, ext4_lblk_t block,\n\t\t struct ext4_extent *ex)\n{\n\tstruct ext4_ext_cache *cex;\n\tstruct ext4_sb_info *sbi;\n\tint ret = 0;", "\t/*\n\t * We borrow i_block_reservation_lock to protect i_cached_extent\n\t */\n\tspin_lock(&EXT4_I(inode)->i_block_reservation_lock);\n\tcex = &EXT4_I(inode)->i_cached_extent;\n\tsbi = EXT4_SB(inode->i_sb);", "\t/* has cache valid data? */\n\tif (cex->ec_len == 0)\n\t\tgoto errout;", "\tif (in_range(block, cex->ec_block, cex->ec_len)) {\n\t\tex->ee_block = cpu_to_le32(cex->ec_block);\n\t\text4_ext_store_pblock(ex, cex->ec_start);\n\t\tex->ee_len = cpu_to_le16(cex->ec_len);\n\t\text_debug(\"%u cached by %u:%u:%llu\\n\",\n\t\t\t\tblock,\n\t\t\t\tcex->ec_block, cex->ec_len, cex->ec_start);\n\t\tret = 1;\n\t}\nerrout:\n\ttrace_ext4_ext_in_cache(inode, block, ret);\n\tspin_unlock(&EXT4_I(inode)->i_block_reservation_lock);\n\treturn ret;\n}", "/*\n * ext4_ext_rm_idx:\n * removes index from the index block.\n */\nstatic int ext4_ext_rm_idx(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_ext_path *path)\n{\n\tint err;\n\text4_fsblk_t leaf;", "\t/* free index block */\n\tpath--;\n\tleaf = ext4_idx_pblock(path->p_idx);\n\tif (unlikely(path->p_hdr->eh_entries == 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"path->p_hdr->eh_entries == 0\");\n\t\treturn -EIO;\n\t}\n\terr = ext4_ext_get_access(handle, inode, path);\n\tif (err)\n\t\treturn err;", "\tif (path->p_idx != EXT_LAST_INDEX(path->p_hdr)) {\n\t\tint len = EXT_LAST_INDEX(path->p_hdr) - path->p_idx;\n\t\tlen *= sizeof(struct ext4_extent_idx);\n\t\tmemmove(path->p_idx, path->p_idx + 1, len);\n\t}", "\tle16_add_cpu(&path->p_hdr->eh_entries, -1);\n\terr = ext4_ext_dirty(handle, inode, path);\n\tif (err)\n\t\treturn err;\n\text_debug(\"index is empty, remove it, free block %llu\\n\", leaf);\n\ttrace_ext4_ext_rm_idx(inode, leaf);", "\text4_free_blocks(handle, inode, NULL, leaf, 1,\n\t\t\t EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET);\n\treturn err;\n}", "/*\n * ext4_ext_calc_credits_for_single_extent:\n * This routine returns max. credits that needed to insert an extent\n * to the extent tree.\n * When pass the actual path, the caller should calculate credits\n * under i_data_sem.\n */\nint ext4_ext_calc_credits_for_single_extent(struct inode *inode, int nrblocks,\n\t\t\t\t\t\tstruct ext4_ext_path *path)\n{\n\tif (path) {\n\t\tint depth = ext_depth(inode);\n\t\tint ret = 0;", "\t\t/* probably there is space in leaf? */\n\t\tif (le16_to_cpu(path[depth].p_hdr->eh_entries)\n\t\t\t\t< le16_to_cpu(path[depth].p_hdr->eh_max)) {", "\t\t\t/*\n\t\t\t * There are some space in the leaf tree, no\n\t\t\t * need to account for leaf block credit\n\t\t\t *\n\t\t\t * bitmaps and block group descriptor blocks\n\t\t\t * and other metadata blocks still need to be\n\t\t\t * accounted.\n\t\t\t */\n\t\t\t/* 1 bitmap, 1 block group descriptor */\n\t\t\tret = 2 + EXT4_META_TRANS_BLOCKS(inode->i_sb);\n\t\t\treturn ret;\n\t\t}\n\t}", "\treturn ext4_chunk_trans_blocks(inode, nrblocks);\n}", "/*\n * How many index/leaf blocks need to change/allocate to modify nrblocks?\n *\n * if nrblocks are fit in a single extent (chunk flag is 1), then\n * in the worse case, each tree level index/leaf need to be changed\n * if the tree split due to insert a new extent, then the old tree\n * index/leaf need to be updated too\n *\n * If the nrblocks are discontiguous, they could cause\n * the whole tree split more than once, but this is really rare.\n */\nint ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)\n{\n\tint index;\n\tint depth = ext_depth(inode);", "\tif (chunk)\n\t\tindex = depth * 2;\n\telse\n\t\tindex = depth * 3;", "\treturn index;\n}", "static int ext4_remove_blocks(handle_t *handle, struct inode *inode,\n\t\t\t struct ext4_extent *ex,\n\t\t\t ext4_fsblk_t *partial_cluster,\n\t\t\t ext4_lblk_t from, ext4_lblk_t to)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\tunsigned short ee_len = ext4_ext_get_actual_len(ex);\n\text4_fsblk_t pblk;\n\tint flags = 0;", "\tif (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))\n\t\tflags |= EXT4_FREE_BLOCKS_METADATA | EXT4_FREE_BLOCKS_FORGET;\n\telse if (ext4_should_journal_data(inode))\n\t\tflags |= EXT4_FREE_BLOCKS_FORGET;", "\t/*\n\t * For bigalloc file systems, we never free a partial cluster\n\t * at the beginning of the extent. Instead, we make a note\n\t * that we tried freeing the cluster, and check to see if we\n\t * need to free it on a subsequent call to ext4_remove_blocks,\n\t * or at the end of the ext4_truncate() operation.\n\t */\n\tflags |= EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER;", "\ttrace_ext4_remove_blocks(inode, ex, from, to, *partial_cluster);\n\t/*\n\t * If we have a partial cluster, and it's different from the\n\t * cluster of the last block, we need to explicitly free the\n\t * partial cluster here.\n\t */\n\tpblk = ext4_ext_pblock(ex) + ee_len - 1;\n\tif (*partial_cluster && (EXT4_B2C(sbi, pblk) != *partial_cluster)) {\n\t\text4_free_blocks(handle, inode, NULL,\n\t\t\t\t EXT4_C2B(sbi, *partial_cluster),\n\t\t\t\t sbi->s_cluster_ratio, flags);\n\t\t*partial_cluster = 0;\n\t}", "#ifdef EXTENTS_STATS\n\t{\n\t\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\t\tspin_lock(&sbi->s_ext_stats_lock);\n\t\tsbi->s_ext_blocks += ee_len;\n\t\tsbi->s_ext_extents++;\n\t\tif (ee_len < sbi->s_ext_min)\n\t\t\tsbi->s_ext_min = ee_len;\n\t\tif (ee_len > sbi->s_ext_max)\n\t\t\tsbi->s_ext_max = ee_len;\n\t\tif (ext_depth(inode) > sbi->s_depth_max)\n\t\t\tsbi->s_depth_max = ext_depth(inode);\n\t\tspin_unlock(&sbi->s_ext_stats_lock);\n\t}\n#endif\n\tif (from >= le32_to_cpu(ex->ee_block)\n\t && to == le32_to_cpu(ex->ee_block) + ee_len - 1) {\n\t\t/* tail removal */\n\t\text4_lblk_t num;", "\t\tnum = le32_to_cpu(ex->ee_block) + ee_len - from;\n\t\tpblk = ext4_ext_pblock(ex) + ee_len - num;\n\t\text_debug(\"free last %u blocks starting %llu\\n\", num, pblk);\n\t\text4_free_blocks(handle, inode, NULL, pblk, num, flags);\n\t\t/*\n\t\t * If the block range to be freed didn't start at the\n\t\t * beginning of a cluster, and we removed the entire\n\t\t * extent, save the partial cluster here, since we\n\t\t * might need to delete if we determine that the\n\t\t * truncate operation has removed all of the blocks in\n\t\t * the cluster.\n\t\t */\n\t\tif (pblk & (sbi->s_cluster_ratio - 1) &&\n\t\t (ee_len == num))\n\t\t\t*partial_cluster = EXT4_B2C(sbi, pblk);\n\t\telse\n\t\t\t*partial_cluster = 0;\n\t} else if (from == le32_to_cpu(ex->ee_block)\n\t\t && to <= le32_to_cpu(ex->ee_block) + ee_len - 1) {\n\t\t/* head removal */\n\t\text4_lblk_t num;\n\t\text4_fsblk_t start;", "\t\tnum = to - from;\n\t\tstart = ext4_ext_pblock(ex);", "\t\text_debug(\"free first %u blocks starting %llu\\n\", num, start);\n\t\text4_free_blocks(handle, inode, NULL, start, num, flags);", "\t} else {\n\t\tprintk(KERN_INFO \"strange request: removal(2) \"\n\t\t\t\t\"%u-%u from %u:%u\\n\",\n\t\t\t\tfrom, to, le32_to_cpu(ex->ee_block), ee_len);\n\t}\n\treturn 0;\n}", "\n/*\n * ext4_ext_rm_leaf() Removes the extents associated with the\n * blocks appearing between \"start\" and \"end\", and splits the extents\n * if \"start\" and \"end\" appear in the same extent\n *\n * @handle: The journal handle\n * @inode: The files inode\n * @path: The path to the leaf\n * @start: The first block to remove\n * @end: The last block to remove\n */\nstatic int\next4_ext_rm_leaf(handle_t *handle, struct inode *inode,\n\t\t struct ext4_ext_path *path, ext4_fsblk_t *partial_cluster,\n\t\t ext4_lblk_t start, ext4_lblk_t end)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\tint err = 0, correct_index = 0;\n\tint depth = ext_depth(inode), credits;\n\tstruct ext4_extent_header *eh;\n\text4_lblk_t a, b;\n\tunsigned num;\n\text4_lblk_t ex_ee_block;\n\tunsigned short ex_ee_len;\n\tunsigned uninitialized = 0;\n\tstruct ext4_extent *ex;", "\t/* the header must be checked already in ext4_ext_remove_space() */\n\text_debug(\"truncate since %u in leaf to %u\\n\", start, end);\n\tif (!path[depth].p_hdr)\n\t\tpath[depth].p_hdr = ext_block_hdr(path[depth].p_bh);\n\teh = path[depth].p_hdr;\n\tif (unlikely(path[depth].p_hdr == NULL)) {\n\t\tEXT4_ERROR_INODE(inode, \"path[%d].p_hdr == NULL\", depth);\n\t\treturn -EIO;\n\t}\n\t/* find where to start removing */\n\tex = EXT_LAST_EXTENT(eh);", "\tex_ee_block = le32_to_cpu(ex->ee_block);\n\tex_ee_len = ext4_ext_get_actual_len(ex);", "\ttrace_ext4_ext_rm_leaf(inode, start, ex, *partial_cluster);", "\twhile (ex >= EXT_FIRST_EXTENT(eh) &&\n\t\t\tex_ee_block + ex_ee_len > start) {", "\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\tuninitialized = 1;\n\t\telse\n\t\t\tuninitialized = 0;", "\t\text_debug(\"remove ext %u:[%d]%d\\n\", ex_ee_block,\n\t\t\t uninitialized, ex_ee_len);\n\t\tpath[depth].p_ext = ex;", "\t\ta = ex_ee_block > start ? ex_ee_block : start;\n\t\tb = ex_ee_block+ex_ee_len - 1 < end ?\n\t\t\tex_ee_block+ex_ee_len - 1 : end;", "\t\text_debug(\" border %u:%u\\n\", a, b);", "\t\t/* If this extent is beyond the end of the hole, skip it */\n\t\tif (end < ex_ee_block) {\n\t\t\tex--;\n\t\t\tex_ee_block = le32_to_cpu(ex->ee_block);\n\t\t\tex_ee_len = ext4_ext_get_actual_len(ex);\n\t\t\tcontinue;\n\t\t} else if (b != ex_ee_block + ex_ee_len - 1) {\n\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t \"can not handle truncate %u:%u \"\n\t\t\t\t\t \"on extent %u:%u\",\n\t\t\t\t\t start, end, ex_ee_block,\n\t\t\t\t\t ex_ee_block + ex_ee_len - 1);\n\t\t\terr = -EIO;\n\t\t\tgoto out;\n\t\t} else if (a != ex_ee_block) {\n\t\t\t/* remove tail of the extent */\n\t\t\tnum = a - ex_ee_block;\n\t\t} else {\n\t\t\t/* remove whole extent: excellent! */\n\t\t\tnum = 0;\n\t\t}\n\t\t/*\n\t\t * 3 for leaf, sb, and inode plus 2 (bmap and group\n\t\t * descriptor) for each block group; assume two block\n\t\t * groups plus ex_ee_len/blocks_per_block_group for\n\t\t * the worst case\n\t\t */\n\t\tcredits = 7 + 2*(ex_ee_len/EXT4_BLOCKS_PER_GROUP(inode->i_sb));\n\t\tif (ex == EXT_FIRST_EXTENT(eh)) {\n\t\t\tcorrect_index = 1;\n\t\t\tcredits += (ext_depth(inode)) + 1;\n\t\t}\n\t\tcredits += EXT4_MAXQUOTAS_TRANS_BLOCKS(inode->i_sb);", "\t\terr = ext4_ext_truncate_extend_restart(handle, inode, credits);\n\t\tif (err)\n\t\t\tgoto out;", "\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;", "\t\terr = ext4_remove_blocks(handle, inode, ex, partial_cluster,\n\t\t\t\t\t a, b);\n\t\tif (err)\n\t\t\tgoto out;", "\t\tif (num == 0)\n\t\t\t/* this extent is removed; mark slot entirely unused */\n\t\t\text4_ext_store_pblock(ex, 0);", "\t\tex->ee_len = cpu_to_le16(num);\n\t\t/*\n\t\t * Do not mark uninitialized if all the blocks in the\n\t\t * extent have been removed.\n\t\t */\n\t\tif (uninitialized && num)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\t/*\n\t\t * If the extent was completely released,\n\t\t * we need to remove it from the leaf\n\t\t */\n\t\tif (num == 0) {\n\t\t\tif (end != EXT_MAX_BLOCKS - 1) {\n\t\t\t\t/*\n\t\t\t\t * For hole punching, we need to scoot all the\n\t\t\t\t * extents up when an extent is removed so that\n\t\t\t\t * we dont have blank extents in the middle\n\t\t\t\t */\n\t\t\t\tmemmove(ex, ex+1, (EXT_LAST_EXTENT(eh) - ex) *\n\t\t\t\t\tsizeof(struct ext4_extent));", "\t\t\t\t/* Now get rid of the one at the end */\n\t\t\t\tmemset(EXT_LAST_EXTENT(eh), 0,\n\t\t\t\t\tsizeof(struct ext4_extent));\n\t\t\t}\n\t\t\tle16_add_cpu(&eh->eh_entries, -1);\n\t\t} else\n\t\t\t*partial_cluster = 0;", "\t\terr = ext4_ext_dirty(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;", "\t\text_debug(\"new extent: %u:%u:%llu\\n\", ex_ee_block, num,\n\t\t\t\text4_ext_pblock(ex));\n\t\tex--;\n\t\tex_ee_block = le32_to_cpu(ex->ee_block);\n\t\tex_ee_len = ext4_ext_get_actual_len(ex);\n\t}", "\tif (correct_index && eh->eh_entries)\n\t\terr = ext4_ext_correct_indexes(handle, inode, path);", "\t/*\n\t * If there is still a entry in the leaf node, check to see if\n\t * it references the partial cluster. This is the only place\n\t * where it could; if it doesn't, we can free the cluster.\n\t */\n\tif (*partial_cluster && ex >= EXT_FIRST_EXTENT(eh) &&\n\t (EXT4_B2C(sbi, ext4_ext_pblock(ex) + ex_ee_len - 1) !=\n\t *partial_cluster)) {\n\t\tint flags = EXT4_FREE_BLOCKS_FORGET;", "\t\tif (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))\n\t\t\tflags |= EXT4_FREE_BLOCKS_METADATA;", "\t\text4_free_blocks(handle, inode, NULL,\n\t\t\t\t EXT4_C2B(sbi, *partial_cluster),\n\t\t\t\t sbi->s_cluster_ratio, flags);\n\t\t*partial_cluster = 0;\n\t}", "\t/* if this leaf is free, then we should\n\t * remove it from index block above */\n\tif (err == 0 && eh->eh_entries == 0 && path[depth].p_bh != NULL)\n\t\terr = ext4_ext_rm_idx(handle, inode, path + depth);", "out:\n\treturn err;\n}", "/*\n * ext4_ext_more_to_rm:\n * returns 1 if current index has to be freed (even partial)\n */\nstatic int\next4_ext_more_to_rm(struct ext4_ext_path *path)\n{\n\tBUG_ON(path->p_idx == NULL);", "\tif (path->p_idx < EXT_FIRST_INDEX(path->p_hdr))\n\t\treturn 0;", "\t/*\n\t * if truncate on deeper level happened, it wasn't partial,\n\t * so we have to consider current index for truncation\n\t */\n\tif (le16_to_cpu(path->p_hdr->eh_entries) == path->p_block)\n\t\treturn 0;\n\treturn 1;\n}", "static int ext4_ext_remove_space(struct inode *inode, ext4_lblk_t start,\n\t\t\t\t ext4_lblk_t end)\n{\n\tstruct super_block *sb = inode->i_sb;\n\tint depth = ext_depth(inode);\n\tstruct ext4_ext_path *path = NULL;\n\text4_fsblk_t partial_cluster = 0;\n\thandle_t *handle;\n\tint i = 0, err = 0;", "\text_debug(\"truncate since %u to %u\\n\", start, end);", "\t/* probably first extent we're gonna free will be last in block */\n\thandle = ext4_journal_start(inode, depth + 1);\n\tif (IS_ERR(handle))\n\t\treturn PTR_ERR(handle);", "again:\n\text4_ext_invalidate_cache(inode);", "\ttrace_ext4_ext_remove_space(inode, start, depth);", "\t/*\n\t * Check if we are removing extents inside the extent tree. If that\n\t * is the case, we are going to punch a hole inside the extent tree\n\t * so we have to check whether we need to split the extent covering\n\t * the last block to remove so we can easily remove the part of it\n\t * in ext4_ext_rm_leaf().\n\t */\n\tif (end < EXT_MAX_BLOCKS - 1) {\n\t\tstruct ext4_extent *ex;\n\t\text4_lblk_t ee_block;", "\t\t/* find extent for this block */\n\t\tpath = ext4_ext_find_extent(inode, end, NULL);\n\t\tif (IS_ERR(path)) {\n\t\t\text4_journal_stop(handle);\n\t\t\treturn PTR_ERR(path);\n\t\t}\n\t\tdepth = ext_depth(inode);\n\t\t/* Leaf not may not exist only if inode has no blocks at all */\n\t\tex = path[depth].p_ext;\n\t\tif (!ex) {\n\t\t\tif (depth) {\n\t\t\t\tEXT4_ERROR_INODE(inode,\n\t\t\t\t\t\t \"path[%d].p_hdr == NULL\",\n\t\t\t\t\t\t depth);\n\t\t\t\terr = -EIO;\n\t\t\t}\n\t\t\tgoto out;\n\t\t}", "\t\tee_block = le32_to_cpu(ex->ee_block);", "\t\t/*\n\t\t * See if the last block is inside the extent, if so split\n\t\t * the extent at 'end' block so we can easily remove the\n\t\t * tail of the first part of the split extent in\n\t\t * ext4_ext_rm_leaf().\n\t\t */\n\t\tif (end >= ee_block &&\n\t\t end < ee_block + ext4_ext_get_actual_len(ex) - 1) {\n\t\t\tint split_flag = 0;", "\t\t\tif (ext4_ext_is_uninitialized(ex))\n\t\t\t\tsplit_flag = EXT4_EXT_MARK_UNINIT1 |\n\t\t\t\t\t EXT4_EXT_MARK_UNINIT2;", "\t\t\t/*\n\t\t\t * Split the extent in two so that 'end' is the last\n\t\t\t * block in the first new extent\n\t\t\t */\n\t\t\terr = ext4_split_extent_at(handle, inode, path,\n\t\t\t\t\t\tend + 1, split_flag,\n\t\t\t\t\t\tEXT4_GET_BLOCKS_PRE_IO |\n\t\t\t\t\t\tEXT4_GET_BLOCKS_PUNCH_OUT_EXT);", "\t\t\tif (err < 0)\n\t\t\t\tgoto out;\n\t\t}\n\t}\n\t/*\n\t * We start scanning from right side, freeing all the blocks\n\t * after i_size and walking into the tree depth-wise.\n\t */\n\tdepth = ext_depth(inode);\n\tif (path) {\n\t\tint k = i = depth;\n\t\twhile (--k > 0)\n\t\t\tpath[k].p_block =\n\t\t\t\tle16_to_cpu(path[k].p_hdr->eh_entries)+1;\n\t} else {\n\t\tpath = kzalloc(sizeof(struct ext4_ext_path) * (depth + 1),\n\t\t\t GFP_NOFS);\n\t\tif (path == NULL) {\n\t\t\text4_journal_stop(handle);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t\tpath[0].p_depth = depth;\n\t\tpath[0].p_hdr = ext_inode_hdr(inode);\n\t\ti = 0;", "\t\tif (ext4_ext_check(inode, path[0].p_hdr, depth)) {\n\t\t\terr = -EIO;\n\t\t\tgoto out;\n\t\t}\n\t}\n\terr = 0;", "\twhile (i >= 0 && err == 0) {\n\t\tif (i == depth) {\n\t\t\t/* this is leaf block */\n\t\t\terr = ext4_ext_rm_leaf(handle, inode, path,\n\t\t\t\t\t &partial_cluster, start,\n\t\t\t\t\t end);\n\t\t\t/* root level has p_bh == NULL, brelse() eats this */\n\t\t\tbrelse(path[i].p_bh);\n\t\t\tpath[i].p_bh = NULL;\n\t\t\ti--;\n\t\t\tcontinue;\n\t\t}", "\t\t/* this is index block */\n\t\tif (!path[i].p_hdr) {\n\t\t\text_debug(\"initialize header\\n\");\n\t\t\tpath[i].p_hdr = ext_block_hdr(path[i].p_bh);\n\t\t}", "\t\tif (!path[i].p_idx) {\n\t\t\t/* this level hasn't been touched yet */\n\t\t\tpath[i].p_idx = EXT_LAST_INDEX(path[i].p_hdr);\n\t\t\tpath[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries)+1;\n\t\t\text_debug(\"init index ptr: hdr 0x%p, num %d\\n\",\n\t\t\t\t path[i].p_hdr,\n\t\t\t\t le16_to_cpu(path[i].p_hdr->eh_entries));\n\t\t} else {\n\t\t\t/* we were already here, see at next index */\n\t\t\tpath[i].p_idx--;\n\t\t}", "\t\text_debug(\"level %d - index, first 0x%p, cur 0x%p\\n\",\n\t\t\t\ti, EXT_FIRST_INDEX(path[i].p_hdr),\n\t\t\t\tpath[i].p_idx);\n\t\tif (ext4_ext_more_to_rm(path + i)) {\n\t\t\tstruct buffer_head *bh;\n\t\t\t/* go to the next level */\n\t\t\text_debug(\"move to level %d (block %llu)\\n\",\n\t\t\t\t i + 1, ext4_idx_pblock(path[i].p_idx));\n\t\t\tmemset(path + i + 1, 0, sizeof(*path));\n\t\t\tbh = sb_bread(sb, ext4_idx_pblock(path[i].p_idx));\n\t\t\tif (!bh) {\n\t\t\t\t/* should we reset i_size? */\n\t\t\t\terr = -EIO;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (WARN_ON(i + 1 > depth)) {\n\t\t\t\terr = -EIO;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ext4_ext_check_block(inode, ext_block_hdr(bh),\n\t\t\t\t\t\t\tdepth - i - 1, bh)) {\n\t\t\t\terr = -EIO;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpath[i + 1].p_bh = bh;", "\t\t\t/* save actual number of indexes since this\n\t\t\t * number is changed at the next iteration */\n\t\t\tpath[i].p_block = le16_to_cpu(path[i].p_hdr->eh_entries);\n\t\t\ti++;\n\t\t} else {\n\t\t\t/* we finished processing this index, go up */\n\t\t\tif (path[i].p_hdr->eh_entries == 0 && i > 0) {\n\t\t\t\t/* index is empty, remove it;\n\t\t\t\t * handle must be already prepared by the\n\t\t\t\t * truncatei_leaf() */\n\t\t\t\terr = ext4_ext_rm_idx(handle, inode, path + i);\n\t\t\t}\n\t\t\t/* root level has p_bh == NULL, brelse() eats this */\n\t\t\tbrelse(path[i].p_bh);\n\t\t\tpath[i].p_bh = NULL;\n\t\t\ti--;\n\t\t\text_debug(\"return to level %d\\n\", i);\n\t\t}\n\t}", "\ttrace_ext4_ext_remove_space_done(inode, start, depth, partial_cluster,\n\t\t\tpath->p_hdr->eh_entries);", "\t/* If we still have something in the partial cluster and we have removed\n\t * even the first extent, then we should free the blocks in the partial\n\t * cluster as well. */\n\tif (partial_cluster && path->p_hdr->eh_entries == 0) {\n\t\tint flags = EXT4_FREE_BLOCKS_FORGET;", "\t\tif (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))\n\t\t\tflags |= EXT4_FREE_BLOCKS_METADATA;", "\t\text4_free_blocks(handle, inode, NULL,\n\t\t\t\t EXT4_C2B(EXT4_SB(sb), partial_cluster),\n\t\t\t\t EXT4_SB(sb)->s_cluster_ratio, flags);\n\t\tpartial_cluster = 0;\n\t}", "\t/* TODO: flexible tree reduction should be here */\n\tif (path->p_hdr->eh_entries == 0) {\n\t\t/*\n\t\t * truncate to zero freed all the tree,\n\t\t * so we need to correct eh_depth\n\t\t */\n\t\terr = ext4_ext_get_access(handle, inode, path);\n\t\tif (err == 0) {\n\t\t\text_inode_hdr(inode)->eh_depth = 0;\n\t\t\text_inode_hdr(inode)->eh_max =\n\t\t\t\tcpu_to_le16(ext4_ext_space_root(inode, 0));\n\t\t\terr = ext4_ext_dirty(handle, inode, path);\n\t\t}\n\t}\nout:\n\text4_ext_drop_refs(path);\n\tkfree(path);\n\tif (err == -EAGAIN) {\n\t\tpath = NULL;\n\t\tgoto again;\n\t}\n\text4_journal_stop(handle);", "\treturn err;\n}", "/*\n * called at mount time\n */\nvoid ext4_ext_init(struct super_block *sb)\n{\n\t/*\n\t * possible initialization would be here\n\t */", "\tif (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS)) {\n#if defined(AGGRESSIVE_TEST) || defined(CHECK_BINSEARCH) || defined(EXTENTS_STATS)\n\t\tprintk(KERN_INFO \"EXT4-fs: file extents enabled\"\n#ifdef AGGRESSIVE_TEST\n\t\t \", aggressive tests\"\n#endif\n#ifdef CHECK_BINSEARCH\n\t\t \", check binsearch\"\n#endif\n#ifdef EXTENTS_STATS\n\t\t \", stats\"\n#endif\n\t\t \"\\n\");\n#endif\n#ifdef EXTENTS_STATS\n\t\tspin_lock_init(&EXT4_SB(sb)->s_ext_stats_lock);\n\t\tEXT4_SB(sb)->s_ext_min = 1 << 30;\n\t\tEXT4_SB(sb)->s_ext_max = 0;\n#endif\n\t}\n}", "/*\n * called at umount time\n */\nvoid ext4_ext_release(struct super_block *sb)\n{\n\tif (!EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_EXTENTS))\n\t\treturn;", "#ifdef EXTENTS_STATS\n\tif (EXT4_SB(sb)->s_ext_blocks && EXT4_SB(sb)->s_ext_extents) {\n\t\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\t\tprintk(KERN_ERR \"EXT4-fs: %lu blocks in %lu extents (%lu ave)\\n\",\n\t\t\tsbi->s_ext_blocks, sbi->s_ext_extents,\n\t\t\tsbi->s_ext_blocks / sbi->s_ext_extents);\n\t\tprintk(KERN_ERR \"EXT4-fs: extents: %lu min, %lu max, max depth %lu\\n\",\n\t\t\tsbi->s_ext_min, sbi->s_ext_max, sbi->s_depth_max);\n\t}\n#endif\n}", "/* FIXME!! we need to try to merge to left or right after zero-out */\nstatic int ext4_ext_zeroout(struct inode *inode, struct ext4_extent *ex)\n{\n\text4_fsblk_t ee_pblock;\n\tunsigned int ee_len;\n\tint ret;", "\tee_len = ext4_ext_get_actual_len(ex);\n\tee_pblock = ext4_ext_pblock(ex);", "\tret = sb_issue_zeroout(inode->i_sb, ee_pblock, ee_len, GFP_NOFS);\n\tif (ret > 0)\n\t\tret = 0;", "\treturn ret;\n}", "/*\n * ext4_split_extent_at() splits an extent at given block.\n *\n * @handle: the journal handle\n * @inode: the file inode\n * @path: the path to the extent\n * @split: the logical block where the extent is splitted.\n * @split_flags: indicates if the extent could be zeroout if split fails, and\n *\t\t the states(init or uninit) of new extents.\n * @flags: flags used to insert new extent to extent tree.\n *\n *\n * Splits extent [a, b] into two extents [a, @split) and [@split, b], states\n * of which are deterimined by split_flag.\n *\n * There are two cases:\n * a> the extent are splitted into two extent.\n * b> split is not needed, and just mark the extent.\n *\n * return 0 on success.\n */\nstatic int ext4_split_extent_at(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t ext4_lblk_t split,\n\t\t\t int split_flag,\n\t\t\t int flags)\n{\n\text4_fsblk_t newblock;\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex, newex, orig_ex;\n\tstruct ext4_extent *ex2 = NULL;\n\tunsigned int ee_len, depth;\n\tint err = 0;\n", "\tBUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==\n\t (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));\n", "\text_debug(\"ext4_split_extents_at: inode %lu, logical\"\n\t\t\"block %llu\\n\", inode->i_ino, (unsigned long long)split);", "\text4_ext_show_leaf(inode, path);", "\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tnewblock = split - ee_block + ext4_ext_pblock(ex);", "\tBUG_ON(split < ee_block || split >= (ee_block + ee_len));", "\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;", "\tif (split == ee_block) {\n\t\t/*\n\t\t * case b: block @split is the block that the extent begins with\n\t\t * then we just change the state of the extent, and splitting\n\t\t * is not needed.\n\t\t */\n\t\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\t\text4_ext_mark_uninitialized(ex);\n\t\telse\n\t\t\text4_ext_mark_initialized(ex);", "\t\tif (!(flags & EXT4_GET_BLOCKS_PRE_IO))\n\t\t\text4_ext_try_to_merge(handle, inode, path, ex);", "\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t}", "\t/* case a */\n\tmemcpy(&orig_ex, ex, sizeof(orig_ex));\n\tex->ee_len = cpu_to_le16(split - ee_block);\n\tif (split_flag & EXT4_EXT_MARK_UNINIT1)\n\t\text4_ext_mark_uninitialized(ex);", "\t/*\n\t * path may lead to new leaf, not to original leaf any more\n\t * after ext4_ext_insert_extent() returns,\n\t */\n\terr = ext4_ext_dirty(handle, inode, path + depth);\n\tif (err)\n\t\tgoto fix_extent_len;", "\tex2 = &newex;\n\tex2->ee_block = cpu_to_le32(split);\n\tex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));\n\text4_ext_store_pblock(ex2, newblock);\n\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\text4_ext_mark_uninitialized(ex2);", "\terr = ext4_ext_insert_extent(handle, inode, path, &newex, flags);\n\tif (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {", "\t\tif (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {\n\t\t\tif (split_flag & EXT4_EXT_DATA_VALID1)\n\t\t\t\terr = ext4_ext_zeroout(inode, ex2);\n\t\t\telse\n\t\t\t\terr = ext4_ext_zeroout(inode, ex);\n\t\t} else\n\t\t\terr = ext4_ext_zeroout(inode, &orig_ex);\n", "\t\tif (err)\n\t\t\tgoto fix_extent_len;\n\t\t/* update the extent length and mark as initialized */\n\t\tex->ee_len = cpu_to_le16(ee_len);\n\t\text4_ext_try_to_merge(handle, inode, path, ex);\n\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t} else if (err)\n\t\tgoto fix_extent_len;", "out:\n\text4_ext_show_leaf(inode, path);\n\treturn err;", "fix_extent_len:\n\tex->ee_len = orig_ex.ee_len;\n\text4_ext_dirty(handle, inode, path + depth);\n\treturn err;\n}", "/*\n * ext4_split_extents() splits an extent and mark extent which is covered\n * by @map as split_flags indicates\n *\n * It may result in splitting the extent into multiple extents (upto three)\n * There are three possibilities:\n * a> There is no split required\n * b> Splits in two extents: Split is happening at either end of the extent\n * c> Splits in three extents: Somone is splitting in middle of the extent\n *\n */\nstatic int ext4_split_extent(handle_t *handle,\n\t\t\t struct inode *inode,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t struct ext4_map_blocks *map,\n\t\t\t int split_flag,\n\t\t\t int flags)\n{\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex;\n\tunsigned int ee_len, depth;\n\tint err = 0;\n\tint uninitialized;\n\tint split_flag1, flags1;", "\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tuninitialized = ext4_ext_is_uninitialized(ex);", "\tif (map->m_lblk + map->m_len < ee_block + ee_len) {", "\t\tsplit_flag1 = split_flag & EXT4_EXT_MAY_ZEROOUT;", "\t\tflags1 = flags | EXT4_GET_BLOCKS_PRE_IO;\n\t\tif (uninitialized)\n\t\t\tsplit_flag1 |= EXT4_EXT_MARK_UNINIT1 |\n\t\t\t\t EXT4_EXT_MARK_UNINIT2;", "\t\tif (split_flag & EXT4_EXT_DATA_VALID2)\n\t\t\tsplit_flag1 |= EXT4_EXT_DATA_VALID1;", "\t\terr = ext4_split_extent_at(handle, inode, path,\n\t\t\t\tmap->m_lblk + map->m_len, split_flag1, flags1);\n\t\tif (err)\n\t\t\tgoto out;\n\t}", "\text4_ext_drop_refs(path);\n\tpath = ext4_ext_find_extent(inode, map->m_lblk, path);\n\tif (IS_ERR(path))\n\t\treturn PTR_ERR(path);", "\tif (map->m_lblk >= ee_block) {", "\t\tsplit_flag1 = split_flag & (EXT4_EXT_MAY_ZEROOUT |\n\t\t\t\t\t EXT4_EXT_DATA_VALID2);", "\t\tif (uninitialized)\n\t\t\tsplit_flag1 |= EXT4_EXT_MARK_UNINIT1;\n\t\tif (split_flag & EXT4_EXT_MARK_UNINIT2)\n\t\t\tsplit_flag1 |= EXT4_EXT_MARK_UNINIT2;\n\t\terr = ext4_split_extent_at(handle, inode, path,\n\t\t\t\tmap->m_lblk, split_flag1, flags);\n\t\tif (err)\n\t\t\tgoto out;\n\t}", "\text4_ext_show_leaf(inode, path);\nout:\n\treturn err ? err : map->m_len;\n}", "/*\n * This function is called by ext4_ext_map_blocks() if someone tries to write\n * to an uninitialized extent. It may result in splitting the uninitialized\n * extent into multiple extents (up to three - one initialized and two\n * uninitialized).\n * There are three possibilities:\n * a> There is no split required: Entire extent should be initialized\n * b> Splits in two extents: Write is happening at either end of the extent\n * c> Splits in three extents: Somone is writing in middle of the extent\n *\n * Pre-conditions:\n * - The extent pointed to by 'path' is uninitialized.\n * - The extent pointed to by 'path' contains a superset\n * of the logical span [map->m_lblk, map->m_lblk + map->m_len).\n *\n * Post-conditions on success:\n * - the returned value is the number of blocks beyond map->l_lblk\n * that are allocated and initialized.\n * It is guaranteed to be >= map->m_len.\n */\nstatic int ext4_ext_convert_to_initialized(handle_t *handle,\n\t\t\t\t\t struct inode *inode,\n\t\t\t\t\t struct ext4_map_blocks *map,\n\t\t\t\t\t struct ext4_ext_path *path)\n{\n\tstruct ext4_sb_info *sbi;\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_map_blocks split_map;\n\tstruct ext4_extent zero_ex;\n\tstruct ext4_extent *ex;\n\text4_lblk_t ee_block, eof_block;\n\tunsigned int ee_len, depth;\n\tint allocated, max_zeroout = 0;\n\tint err = 0;\n\tint split_flag = 0;", "\text_debug(\"ext4_ext_convert_to_initialized: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,\n\t\t(unsigned long long)map->m_lblk, map->m_len);", "\tsbi = EXT4_SB(inode->i_sb);\n\teof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>\n\t\tinode->i_sb->s_blocksize_bits;\n\tif (eof_block < map->m_lblk + map->m_len)\n\t\teof_block = map->m_lblk + map->m_len;", "\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);\n\tallocated = ee_len - (map->m_lblk - ee_block);", "\ttrace_ext4_ext_convert_to_initialized_enter(inode, map, ex);", "\t/* Pre-conditions */\n\tBUG_ON(!ext4_ext_is_uninitialized(ex));\n\tBUG_ON(!in_range(map->m_lblk, ee_block, ee_len));", "\t/*\n\t * Attempt to transfer newly initialized blocks from the currently\n\t * uninitialized extent to its left neighbor. This is much cheaper\n\t * than an insertion followed by a merge as those involve costly\n\t * memmove() calls. This is the common case in steady state for\n\t * workloads doing fallocate(FALLOC_FL_KEEP_SIZE) followed by append\n\t * writes.\n\t *\n\t * Limitations of the current logic:\n\t * - L1: we only deal with writes at the start of the extent.\n\t * The approach could be extended to writes at the end\n\t * of the extent but this scenario was deemed less common.\n\t * - L2: we do not deal with writes covering the whole extent.\n\t * This would require removing the extent if the transfer\n\t * is possible.\n\t * - L3: we only attempt to merge with an extent stored in the\n\t * same extent tree node.\n\t */\n\tif ((map->m_lblk == ee_block) &&\t/*L1*/\n\t\t(map->m_len < ee_len) &&\t/*L2*/\n\t\t(ex > EXT_FIRST_EXTENT(eh))) {\t/*L3*/\n\t\tstruct ext4_extent *prev_ex;\n\t\text4_lblk_t prev_lblk;\n\t\text4_fsblk_t prev_pblk, ee_pblk;\n\t\tunsigned int prev_len, write_len;", "\t\tprev_ex = ex - 1;\n\t\tprev_lblk = le32_to_cpu(prev_ex->ee_block);\n\t\tprev_len = ext4_ext_get_actual_len(prev_ex);\n\t\tprev_pblk = ext4_ext_pblock(prev_ex);\n\t\tee_pblk = ext4_ext_pblock(ex);\n\t\twrite_len = map->m_len;", "\t\t/*\n\t\t * A transfer of blocks from 'ex' to 'prev_ex' is allowed\n\t\t * upon those conditions:\n\t\t * - C1: prev_ex is initialized,\n\t\t * - C2: prev_ex is logically abutting ex,\n\t\t * - C3: prev_ex is physically abutting ex,\n\t\t * - C4: prev_ex can receive the additional blocks without\n\t\t * overflowing the (initialized) length limit.\n\t\t */\n\t\tif ((!ext4_ext_is_uninitialized(prev_ex)) &&\t\t/*C1*/\n\t\t\t((prev_lblk + prev_len) == ee_block) &&\t\t/*C2*/\n\t\t\t((prev_pblk + prev_len) == ee_pblk) &&\t\t/*C3*/\n\t\t\t(prev_len < (EXT_INIT_MAX_LEN - write_len))) {\t/*C4*/\n\t\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\t\tif (err)\n\t\t\t\tgoto out;", "\t\t\ttrace_ext4_ext_convert_to_initialized_fastpath(inode,\n\t\t\t\tmap, ex, prev_ex);", "\t\t\t/* Shift the start of ex by 'write_len' blocks */\n\t\t\tex->ee_block = cpu_to_le32(ee_block + write_len);\n\t\t\text4_ext_store_pblock(ex, ee_pblk + write_len);\n\t\t\tex->ee_len = cpu_to_le16(ee_len - write_len);\n\t\t\text4_ext_mark_uninitialized(ex); /* Restore the flag */", "\t\t\t/* Extend prev_ex by 'write_len' blocks */\n\t\t\tprev_ex->ee_len = cpu_to_le16(prev_len + write_len);", "\t\t\t/* Mark the block containing both extents as dirty */\n\t\t\text4_ext_dirty(handle, inode, path + depth);", "\t\t\t/* Update path to point to the right extent */\n\t\t\tpath[depth].p_ext = prev_ex;", "\t\t\t/* Result: number of initialized blocks past m_lblk */\n\t\t\tallocated = write_len;\n\t\t\tgoto out;\n\t\t}\n\t}", "\tWARN_ON(map->m_lblk < ee_block);\n\t/*\n\t * It is safe to convert extent to initialized via explicit\n\t * zeroout only if extent is fully insde i_size or new_size.\n\t */\n\tsplit_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;", "\tif (EXT4_EXT_MAY_ZEROOUT & split_flag)\n\t\tmax_zeroout = sbi->s_extent_max_zeroout_kb >>\n\t\t\tinode->i_sb->s_blocksize_bits;", "\t/* If extent is less than s_max_zeroout_kb, zeroout directly */\n\tif (max_zeroout && (ee_len <= max_zeroout)) {\n\t\terr = ext4_ext_zeroout(inode, ex);\n\t\tif (err)\n\t\t\tgoto out;", "\t\terr = ext4_ext_get_access(handle, inode, path + depth);\n\t\tif (err)\n\t\t\tgoto out;\n\t\text4_ext_mark_initialized(ex);\n\t\text4_ext_try_to_merge(handle, inode, path, ex);\n\t\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\n\t\tgoto out;\n\t}", "\t/*\n\t * four cases:\n\t * 1. split the extent into three extents.\n\t * 2. split the extent into two extents, zeroout the first half.\n\t * 3. split the extent into two extents, zeroout the second half.\n\t * 4. split the extent into two extents with out zeroout.\n\t */\n\tsplit_map.m_lblk = map->m_lblk;\n\tsplit_map.m_len = map->m_len;", "\tif (max_zeroout && (allocated > map->m_len)) {\n\t\tif (allocated <= max_zeroout) {\n\t\t\t/* case 3 */\n\t\t\tzero_ex.ee_block =\n\t\t\t\t\t cpu_to_le32(map->m_lblk);\n\t\t\tzero_ex.ee_len = cpu_to_le16(allocated);\n\t\t\text4_ext_store_pblock(&zero_ex,\n\t\t\t\text4_ext_pblock(ex) + map->m_lblk - ee_block);\n\t\t\terr = ext4_ext_zeroout(inode, &zero_ex);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t\tsplit_map.m_lblk = map->m_lblk;\n\t\t\tsplit_map.m_len = allocated;\n\t\t} else if (map->m_lblk - ee_block + map->m_len < max_zeroout) {\n\t\t\t/* case 2 */\n\t\t\tif (map->m_lblk != ee_block) {\n\t\t\t\tzero_ex.ee_block = ex->ee_block;\n\t\t\t\tzero_ex.ee_len = cpu_to_le16(map->m_lblk -\n\t\t\t\t\t\t\tee_block);\n\t\t\t\text4_ext_store_pblock(&zero_ex,\n\t\t\t\t\t\t ext4_ext_pblock(ex));\n\t\t\t\terr = ext4_ext_zeroout(inode, &zero_ex);\n\t\t\t\tif (err)\n\t\t\t\t\tgoto out;\n\t\t\t}", "\t\t\tsplit_map.m_lblk = ee_block;\n\t\t\tsplit_map.m_len = map->m_lblk - ee_block + map->m_len;\n\t\t\tallocated = map->m_len;\n\t\t}\n\t}", "\tallocated = ext4_split_extent(handle, inode, path,\n\t\t\t\t &split_map, split_flag, 0);\n\tif (allocated < 0)\n\t\terr = allocated;", "out:\n\treturn err ? err : allocated;\n}", "/*\n * This function is called by ext4_ext_map_blocks() from\n * ext4_get_blocks_dio_write() when DIO to write\n * to an uninitialized extent.\n *\n * Writing to an uninitialized extent may result in splitting the uninitialized\n * extent into multiple initialized/uninitialized extents (up to three)\n * There are three possibilities:\n * a> There is no split required: Entire extent should be uninitialized\n * b> Splits in two extents: Write is happening at either end of the extent\n * c> Splits in three extents: Somone is writing in middle of the extent\n *\n * One of more index blocks maybe needed if the extent tree grow after\n * the uninitialized extent split. To prevent ENOSPC occur at the IO\n * complete, we need to split the uninitialized extent before DIO submit\n * the IO. The uninitialized extent called at this time will be split\n * into three uninitialized extent(at most). After IO complete, the part\n * being filled will be convert to initialized by the end_io callback function\n * via ext4_convert_unwritten_extents().\n *\n * Returns the size of uninitialized extent to be written on success.\n */\nstatic int ext4_split_unwritten_extents(handle_t *handle,\n\t\t\t\t\tstruct inode *inode,\n\t\t\t\t\tstruct ext4_map_blocks *map,\n\t\t\t\t\tstruct ext4_ext_path *path,\n\t\t\t\t\tint flags)\n{\n\text4_lblk_t eof_block;\n\text4_lblk_t ee_block;\n\tstruct ext4_extent *ex;\n\tunsigned int ee_len;\n\tint split_flag = 0, depth;", "\text_debug(\"ext4_split_unwritten_extents: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,\n\t\t(unsigned long long)map->m_lblk, map->m_len);", "\teof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >>\n\t\tinode->i_sb->s_blocksize_bits;\n\tif (eof_block < map->m_lblk + map->m_len)\n\t\teof_block = map->m_lblk + map->m_len;\n\t/*\n\t * It is safe to convert extent to initialized via explicit\n\t * zeroout only if extent is fully insde i_size or new_size.\n\t */\n\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;\n\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);", "\tsplit_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0;\n\tsplit_flag |= EXT4_EXT_MARK_UNINIT2;", "\tif (flags & EXT4_GET_BLOCKS_CONVERT)\n\t\tsplit_flag |= EXT4_EXT_DATA_VALID2;", "\tflags |= EXT4_GET_BLOCKS_PRE_IO;\n\treturn ext4_split_extent(handle, inode, path, map, split_flag, flags);\n}", "static int ext4_convert_unwritten_extents_endio(handle_t *handle,", "\t\t\t\t\t\tstruct inode *inode,\n\t\t\t\t\t\tstruct ext4_map_blocks *map,\n\t\t\t\t\t\tstruct ext4_ext_path *path)", "{\n\tstruct ext4_extent *ex;", "\text4_lblk_t ee_block;\n\tunsigned int ee_len;", "\tint depth;\n\tint err = 0;", "\tdepth = ext_depth(inode);\n\tex = path[depth].p_ext;", "\tee_block = le32_to_cpu(ex->ee_block);\n\tee_len = ext4_ext_get_actual_len(ex);", "\n\text_debug(\"ext4_convert_unwritten_extents_endio: inode %lu, logical\"\n\t\t\"block %llu, max_blocks %u\\n\", inode->i_ino,", "\t\t (unsigned long long)ee_block, ee_len);", "\t/* If extent is larger than requested then split is required */\n\tif (ee_block != map->m_lblk || ee_len > map->m_len) {\n\t\terr = ext4_split_unwritten_extents(handle, inode, map, path,\n\t\t\t\t\t\t EXT4_GET_BLOCKS_CONVERT);\n\t\tif (err < 0)\n\t\t\tgoto out;\n\t\text4_ext_drop_refs(path);\n\t\tpath = ext4_ext_find_extent(inode, map->m_lblk, path);\n\t\tif (IS_ERR(path)) {\n\t\t\terr = PTR_ERR(path);\n\t\t\tgoto out;\n\t\t}\n\t\tdepth = ext_depth(inode);\n\t\tex = path[depth].p_ext;\n\t}", "\n\terr = ext4_ext_get_access(handle, inode, path + depth);\n\tif (err)\n\t\tgoto out;\n\t/* first mark the extent as initialized */\n\text4_ext_mark_initialized(ex);", "\t/* note: ext4_ext_correct_indexes() isn't needed here because\n\t * borders are not changed\n\t */\n\text4_ext_try_to_merge(handle, inode, path, ex);", "\t/* Mark modified extent as dirty */\n\terr = ext4_ext_dirty(handle, inode, path + path->p_depth);\nout:\n\text4_ext_show_leaf(inode, path);\n\treturn err;\n}", "static void unmap_underlying_metadata_blocks(struct block_device *bdev,\n\t\t\tsector_t block, int count)\n{\n\tint i;\n\tfor (i = 0; i < count; i++)\n unmap_underlying_metadata(bdev, block + i);\n}", "/*\n * Handle EOFBLOCKS_FL flag, clearing it if necessary\n */\nstatic int check_eofblocks_fl(handle_t *handle, struct inode *inode,\n\t\t\t ext4_lblk_t lblk,\n\t\t\t struct ext4_ext_path *path,\n\t\t\t unsigned int len)\n{\n\tint i, depth;\n\tstruct ext4_extent_header *eh;\n\tstruct ext4_extent *last_ex;", "\tif (!ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))\n\t\treturn 0;", "\tdepth = ext_depth(inode);\n\teh = path[depth].p_hdr;", "\t/*\n\t * We're going to remove EOFBLOCKS_FL entirely in future so we\n\t * do not care for this case anymore. Simply remove the flag\n\t * if there are no extents.\n\t */\n\tif (unlikely(!eh->eh_entries))\n\t\tgoto out;\n\tlast_ex = EXT_LAST_EXTENT(eh);\n\t/*\n\t * We should clear the EOFBLOCKS_FL flag if we are writing the\n\t * last block in the last extent in the file. We test this by\n\t * first checking to see if the caller to\n\t * ext4_ext_get_blocks() was interested in the last block (or\n\t * a block beyond the last block) in the current extent. If\n\t * this turns out to be false, we can bail out from this\n\t * function immediately.\n\t */\n\tif (lblk + len < le32_to_cpu(last_ex->ee_block) +\n\t ext4_ext_get_actual_len(last_ex))\n\t\treturn 0;\n\t/*\n\t * If the caller does appear to be planning to write at or\n\t * beyond the end of the current extent, we then test to see\n\t * if the current extent is the last extent in the file, by\n\t * checking to make sure it was reached via the rightmost node\n\t * at each level of the tree.\n\t */\n\tfor (i = depth-1; i >= 0; i--)\n\t\tif (path[i].p_idx != EXT_LAST_INDEX(path[i].p_hdr))\n\t\t\treturn 0;\nout:\n\text4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);\n\treturn ext4_mark_inode_dirty(handle, inode);\n}", "/**\n * ext4_find_delalloc_range: find delayed allocated block in the given range.\n *\n * Goes through the buffer heads in the range [lblk_start, lblk_end] and returns\n * whether there are any buffers marked for delayed allocation. It returns '1'\n * on the first delalloc'ed buffer head found. If no buffer head in the given\n * range is marked for delalloc, it returns 0.\n * lblk_start should always be <= lblk_end.\n * search_hint_reverse is to indicate that searching in reverse from lblk_end to\n * lblk_start might be more efficient (i.e., we will likely hit the delalloc'ed\n * block sooner). This is useful when blocks are truncated sequentially from\n * lblk_start towards lblk_end.\n */\nstatic int ext4_find_delalloc_range(struct inode *inode,\n\t\t\t\t ext4_lblk_t lblk_start,\n\t\t\t\t ext4_lblk_t lblk_end,\n\t\t\t\t int search_hint_reverse)\n{\n\tstruct address_space *mapping = inode->i_mapping;\n\tstruct buffer_head *head, *bh = NULL;\n\tstruct page *page;\n\text4_lblk_t i, pg_lblk;\n\tpgoff_t index;", "\tif (!test_opt(inode->i_sb, DELALLOC))\n\t\treturn 0;", "\t/* reverse search wont work if fs block size is less than page size */\n\tif (inode->i_blkbits < PAGE_CACHE_SHIFT)\n\t\tsearch_hint_reverse = 0;", "\tif (search_hint_reverse)\n\t\ti = lblk_end;\n\telse\n\t\ti = lblk_start;", "\tindex = i >> (PAGE_CACHE_SHIFT - inode->i_blkbits);", "\twhile ((i >= lblk_start) && (i <= lblk_end)) {\n\t\tpage = find_get_page(mapping, index);\n\t\tif (!page)\n\t\t\tgoto nextpage;", "\t\tif (!page_has_buffers(page))\n\t\t\tgoto nextpage;", "\t\thead = page_buffers(page);\n\t\tif (!head)\n\t\t\tgoto nextpage;", "\t\tbh = head;\n\t\tpg_lblk = index << (PAGE_CACHE_SHIFT -\n\t\t\t\t\t\tinode->i_blkbits);\n\t\tdo {\n\t\t\tif (unlikely(pg_lblk < lblk_start)) {\n\t\t\t\t/*\n\t\t\t\t * This is possible when fs block size is less\n\t\t\t\t * than page size and our cluster starts/ends in\n\t\t\t\t * middle of the page. So we need to skip the\n\t\t\t\t * initial few blocks till we reach the 'lblk'\n\t\t\t\t */\n\t\t\t\tpg_lblk++;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\t/* Check if the buffer is delayed allocated and that it\n\t\t\t * is not yet mapped. (when da-buffers are mapped during\n\t\t\t * their writeout, their da_mapped bit is set.)\n\t\t\t */\n\t\t\tif (buffer_delay(bh) && !buffer_da_mapped(bh)) {\n\t\t\t\tpage_cache_release(page);\n\t\t\t\ttrace_ext4_find_delalloc_range(inode,\n\t\t\t\t\t\tlblk_start, lblk_end,\n\t\t\t\t\t\tsearch_hint_reverse,\n\t\t\t\t\t\t1, i);\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (search_hint_reverse)\n\t\t\t\ti--;\n\t\t\telse\n\t\t\t\ti++;\n\t\t} while ((i >= lblk_start) && (i <= lblk_end) &&\n\t\t\t\t((bh = bh->b_this_page) != head));\nnextpage:\n\t\tif (page)\n\t\t\tpage_cache_release(page);\n\t\t/*\n\t\t * Move to next page. 'i' will be the first lblk in the next\n\t\t * page.\n\t\t */\n\t\tif (search_hint_reverse)\n\t\t\tindex--;\n\t\telse\n\t\t\tindex++;\n\t\ti = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);\n\t}", "\ttrace_ext4_find_delalloc_range(inode, lblk_start, lblk_end,\n\t\t\t\t\tsearch_hint_reverse, 0, 0);\n\treturn 0;\n}", "int ext4_find_delalloc_cluster(struct inode *inode, ext4_lblk_t lblk,\n\t\t\t int search_hint_reverse)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\text4_lblk_t lblk_start, lblk_end;\n\tlblk_start = lblk & (~(sbi->s_cluster_ratio - 1));\n\tlblk_end = lblk_start + sbi->s_cluster_ratio - 1;", "\treturn ext4_find_delalloc_range(inode, lblk_start, lblk_end,\n\t\t\t\t\tsearch_hint_reverse);\n}", "/**\n * Determines how many complete clusters (out of those specified by the 'map')\n * are under delalloc and were reserved quota for.\n * This function is called when we are writing out the blocks that were\n * originally written with their allocation delayed, but then the space was\n * allocated using fallocate() before the delayed allocation could be resolved.\n * The cases to look for are:\n * ('=' indicated delayed allocated blocks\n * '-' indicates non-delayed allocated blocks)\n * (a) partial clusters towards beginning and/or end outside of allocated range\n * are not delalloc'ed.\n *\tEx:\n *\t|----c---=|====c====|====c====|===-c----|\n *\t |++++++ allocated ++++++|\n *\t==> 4 complete clusters in above example\n *\n * (b) partial cluster (outside of allocated range) towards either end is\n * marked for delayed allocation. In this case, we will exclude that\n * cluster.\n *\tEx:\n *\t|----====c========|========c========|\n *\t |++++++ allocated ++++++|\n *\t==> 1 complete clusters in above example\n *\n *\tEx:\n *\t|================c================|\n * |++++++ allocated ++++++|\n *\t==> 0 complete clusters in above example\n *\n * The ext4_da_update_reserve_space will be called only if we\n * determine here that there were some \"entire\" clusters that span\n * this 'allocated' range.\n * In the non-bigalloc case, this function will just end up returning num_blks\n * without ever calling ext4_find_delalloc_range.\n */\nstatic unsigned int\nget_reserved_cluster_alloc(struct inode *inode, ext4_lblk_t lblk_start,\n\t\t\t unsigned int num_blks)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\text4_lblk_t alloc_cluster_start, alloc_cluster_end;\n\text4_lblk_t lblk_from, lblk_to, c_offset;\n\tunsigned int allocated_clusters = 0;", "\talloc_cluster_start = EXT4_B2C(sbi, lblk_start);\n\talloc_cluster_end = EXT4_B2C(sbi, lblk_start + num_blks - 1);", "\t/* max possible clusters for this allocation */\n\tallocated_clusters = alloc_cluster_end - alloc_cluster_start + 1;", "\ttrace_ext4_get_reserved_cluster_alloc(inode, lblk_start, num_blks);", "\t/* Check towards left side */\n\tc_offset = lblk_start & (sbi->s_cluster_ratio - 1);\n\tif (c_offset) {\n\t\tlblk_from = lblk_start & (~(sbi->s_cluster_ratio - 1));\n\t\tlblk_to = lblk_from + c_offset - 1;", "\t\tif (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))\n\t\t\tallocated_clusters--;\n\t}", "\t/* Now check towards right. */\n\tc_offset = (lblk_start + num_blks) & (sbi->s_cluster_ratio - 1);\n\tif (allocated_clusters && c_offset) {\n\t\tlblk_from = lblk_start + num_blks;\n\t\tlblk_to = lblk_from + (sbi->s_cluster_ratio - c_offset) - 1;", "\t\tif (ext4_find_delalloc_range(inode, lblk_from, lblk_to, 0))\n\t\t\tallocated_clusters--;\n\t}", "\treturn allocated_clusters;\n}", "static int\next4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_map_blocks *map,\n\t\t\tstruct ext4_ext_path *path, int flags,\n\t\t\tunsigned int allocated, ext4_fsblk_t newblock)\n{\n\tint ret = 0;\n\tint err = 0;\n\text4_io_end_t *io = ext4_inode_aio(inode);", "\text_debug(\"ext4_ext_handle_uninitialized_extents: inode %lu, logical \"\n\t\t \"block %llu, max_blocks %u, flags %x, allocated %u\\n\",\n\t\t inode->i_ino, (unsigned long long)map->m_lblk, map->m_len,\n\t\t flags, allocated);\n\text4_ext_show_leaf(inode, path);", "\ttrace_ext4_ext_handle_uninitialized_extents(inode, map, allocated,\n\t\t\t\t\t\t newblock);", "\t/* get_block() before submit the IO, split the extent */\n\tif ((flags & EXT4_GET_BLOCKS_PRE_IO)) {\n\t\tret = ext4_split_unwritten_extents(handle, inode, map,\n\t\t\t\t\t\t path, flags);\n\t\tif (ret <= 0)\n\t\t\tgoto out;\n\t\t/*\n\t\t * Flag the inode(non aio case) or end_io struct (aio case)\n\t\t * that this IO needs to conversion to written when IO is\n\t\t * completed\n\t\t */\n\t\tif (io)\n\t\t\text4_set_io_unwritten_flag(inode, io);\n\t\telse\n\t\t\text4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);\n\t\tif (ext4_should_dioread_nolock(inode))\n\t\t\tmap->m_flags |= EXT4_MAP_UNINIT;\n\t\tgoto out;\n\t}\n\t/* IO end_io complete, convert the filled extent to written */\n\tif ((flags & EXT4_GET_BLOCKS_CONVERT)) {", "\t\tret = ext4_convert_unwritten_extents_endio(handle, inode, map,", "\t\t\t\t\t\t\tpath);\n\t\tif (ret >= 0) {\n\t\t\text4_update_inode_fsync_trans(handle, inode, 1);\n\t\t\terr = check_eofblocks_fl(handle, inode, map->m_lblk,\n\t\t\t\t\t\t path, map->m_len);\n\t\t} else\n\t\t\terr = ret;\n\t\tgoto out2;\n\t}\n\t/* buffered IO case */\n\t/*\n\t * repeat fallocate creation request\n\t * we already have an unwritten extent\n\t */\n\tif (flags & EXT4_GET_BLOCKS_UNINIT_EXT)\n\t\tgoto map_out;", "\t/* buffered READ or buffered write_begin() lookup */\n\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t/*\n\t\t * We have blocks reserved already. We\n\t\t * return allocated blocks so that delalloc\n\t\t * won't do block reservation for us. But\n\t\t * the buffer head will be unmapped so that\n\t\t * a read from the block returns 0s.\n\t\t */\n\t\tmap->m_flags |= EXT4_MAP_UNWRITTEN;\n\t\tgoto out1;\n\t}", "\t/* buffered write, writepage time, convert*/\n\tret = ext4_ext_convert_to_initialized(handle, inode, map, path);\n\tif (ret >= 0)\n\t\text4_update_inode_fsync_trans(handle, inode, 1);\nout:\n\tif (ret <= 0) {\n\t\terr = ret;\n\t\tgoto out2;\n\t} else\n\t\tallocated = ret;\n\tmap->m_flags |= EXT4_MAP_NEW;\n\t/*\n\t * if we allocated more blocks than requested\n\t * we need to make sure we unmap the extra block\n\t * allocated. The actual needed block will get\n\t * unmapped later when we find the buffer_head marked\n\t * new.\n\t */\n\tif (allocated > map->m_len) {\n\t\tunmap_underlying_metadata_blocks(inode->i_sb->s_bdev,\n\t\t\t\t\tnewblock + map->m_len,\n\t\t\t\t\tallocated - map->m_len);\n\t\tallocated = map->m_len;\n\t}", "\t/*\n\t * If we have done fallocate with the offset that is already\n\t * delayed allocated, we would have block reservation\n\t * and quota reservation done in the delayed write path.\n\t * But fallocate would have already updated quota and block\n\t * count for this offset. So cancel these reservation\n\t */\n\tif (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {\n\t\tunsigned int reserved_clusters;\n\t\treserved_clusters = get_reserved_cluster_alloc(inode,\n\t\t\t\tmap->m_lblk, map->m_len);\n\t\tif (reserved_clusters)\n\t\t\text4_da_update_reserve_space(inode,\n\t\t\t\t\t\t reserved_clusters,\n\t\t\t\t\t\t 0);\n\t}", "map_out:\n\tmap->m_flags |= EXT4_MAP_MAPPED;\n\tif ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) {\n\t\terr = check_eofblocks_fl(handle, inode, map->m_lblk, path,\n\t\t\t\t\t map->m_len);\n\t\tif (err < 0)\n\t\t\tgoto out2;\n\t}\nout1:\n\tif (allocated > map->m_len)\n\t\tallocated = map->m_len;\n\text4_ext_show_leaf(inode, path);\n\tmap->m_pblk = newblock;\n\tmap->m_len = allocated;\nout2:\n\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}\n\treturn err ? err : allocated;\n}", "/*\n * get_implied_cluster_alloc - check to see if the requested\n * allocation (in the map structure) overlaps with a cluster already\n * allocated in an extent.\n *\t@sb\tThe filesystem superblock structure\n *\t@map\tThe requested lblk->pblk mapping\n *\t@ex\tThe extent structure which might contain an implied\n *\t\t\tcluster allocation\n *\n * This function is called by ext4_ext_map_blocks() after we failed to\n * find blocks that were already in the inode's extent tree. Hence,\n * we know that the beginning of the requested region cannot overlap\n * the extent from the inode's extent tree. There are three cases we\n * want to catch. The first is this case:\n *\n *\t\t |--- cluster # N--|\n * |--- extent ---|\t|---- requested region ---|\n *\t\t\t|==========|\n *\n * The second case that we need to test for is this one:\n *\n * |--------- cluster # N ----------------|\n *\t |--- requested region --| |------- extent ----|\n *\t |=======================|\n *\n * The third case is when the requested region lies between two extents\n * within the same cluster:\n * |------------- cluster # N-------------|\n * |----- ex -----| |---- ex_right ----|\n * |------ requested region ------|\n * |================|\n *\n * In each of the above cases, we need to set the map->m_pblk and\n * map->m_len so it corresponds to the return the extent labelled as\n * \"|====|\" from cluster #N, since it is already in use for data in\n * cluster EXT4_B2C(sbi, map->m_lblk).\tWe will then return 1 to\n * signal to ext4_ext_map_blocks() that map->m_pblk should be treated\n * as a new \"allocated\" block region. Otherwise, we will return 0 and\n * ext4_ext_map_blocks() will then allocate one or more new clusters\n * by calling ext4_mb_new_blocks().\n */\nstatic int get_implied_cluster_alloc(struct super_block *sb,\n\t\t\t\t struct ext4_map_blocks *map,\n\t\t\t\t struct ext4_extent *ex,\n\t\t\t\t struct ext4_ext_path *path)\n{\n\tstruct ext4_sb_info *sbi = EXT4_SB(sb);\n\text4_lblk_t c_offset = map->m_lblk & (sbi->s_cluster_ratio-1);\n\text4_lblk_t ex_cluster_start, ex_cluster_end;\n\text4_lblk_t rr_cluster_start;\n\text4_lblk_t ee_block = le32_to_cpu(ex->ee_block);\n\text4_fsblk_t ee_start = ext4_ext_pblock(ex);\n\tunsigned short ee_len = ext4_ext_get_actual_len(ex);", "\t/* The extent passed in that we are trying to match */\n\tex_cluster_start = EXT4_B2C(sbi, ee_block);\n\tex_cluster_end = EXT4_B2C(sbi, ee_block + ee_len - 1);", "\t/* The requested region passed into ext4_map_blocks() */\n\trr_cluster_start = EXT4_B2C(sbi, map->m_lblk);", "\tif ((rr_cluster_start == ex_cluster_end) ||\n\t (rr_cluster_start == ex_cluster_start)) {\n\t\tif (rr_cluster_start == ex_cluster_end)\n\t\t\tee_start += ee_len - 1;\n\t\tmap->m_pblk = (ee_start & ~(sbi->s_cluster_ratio - 1)) +\n\t\t\tc_offset;\n\t\tmap->m_len = min(map->m_len,\n\t\t\t\t (unsigned) sbi->s_cluster_ratio - c_offset);\n\t\t/*\n\t\t * Check for and handle this case:\n\t\t *\n\t\t * |--------- cluster # N-------------|\n\t\t *\t\t |------- extent ----|\n\t\t *\t |--- requested region ---|\n\t\t *\t |===========|\n\t\t */", "\t\tif (map->m_lblk < ee_block)\n\t\t\tmap->m_len = min(map->m_len, ee_block - map->m_lblk);", "\t\t/*\n\t\t * Check for the case where there is already another allocated\n\t\t * block to the right of 'ex' but before the end of the cluster.\n\t\t *\n\t\t * |------------- cluster # N-------------|\n\t\t * |----- ex -----| |---- ex_right ----|\n\t\t * |------ requested region ------|\n\t\t * |================|\n\t\t */\n\t\tif (map->m_lblk > ee_block) {\n\t\t\text4_lblk_t next = ext4_ext_next_allocated_block(path);\n\t\t\tmap->m_len = min(map->m_len, next - map->m_lblk);\n\t\t}", "\t\ttrace_ext4_get_implied_cluster_alloc_exit(sb, map, 1);\n\t\treturn 1;\n\t}", "\ttrace_ext4_get_implied_cluster_alloc_exit(sb, map, 0);\n\treturn 0;\n}", "\n/*\n * Block allocation/map/preallocation routine for extents based files\n *\n *\n * Need to be called with\n * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block\n * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)\n *\n * return > 0, number of of blocks already mapped/allocated\n * if create == 0 and these are pre-allocated blocks\n * \tbuffer head is unmapped\n * otherwise blocks are mapped\n *\n * return = 0, if plain look up failed (blocks have not been allocated)\n * buffer head is unmapped\n *\n * return < 0, error case.\n */\nint ext4_ext_map_blocks(handle_t *handle, struct inode *inode,\n\t\t\tstruct ext4_map_blocks *map, int flags)\n{\n\tstruct ext4_ext_path *path = NULL;\n\tstruct ext4_extent newex, *ex, *ex2;\n\tstruct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);\n\text4_fsblk_t newblock = 0;\n\tint free_on_err = 0, err = 0, depth, ret;\n\tunsigned int allocated = 0, offset = 0;\n\tunsigned int allocated_clusters = 0;\n\tstruct ext4_allocation_request ar;\n\text4_io_end_t *io = ext4_inode_aio(inode);\n\text4_lblk_t cluster_offset;\n\tint set_unwritten = 0;", "\text_debug(\"blocks %u/%u requested for inode %lu\\n\",\n\t\t map->m_lblk, map->m_len, inode->i_ino);\n\ttrace_ext4_ext_map_blocks_enter(inode, map->m_lblk, map->m_len, flags);", "\t/* check in cache */\n\tif (ext4_ext_in_cache(inode, map->m_lblk, &newex)) {\n\t\tif (!newex.ee_start_lo && !newex.ee_start_hi) {\n\t\t\tif ((sbi->s_cluster_ratio > 1) &&\n\t\t\t ext4_find_delalloc_cluster(inode, map->m_lblk, 0))\n\t\t\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;", "\t\t\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t\t\t/*\n\t\t\t\t * block isn't allocated yet and\n\t\t\t\t * user doesn't want to allocate it\n\t\t\t\t */\n\t\t\t\tgoto out2;\n\t\t\t}\n\t\t\t/* we should allocate requested block */\n\t\t} else {\n\t\t\t/* block is already allocated */\n\t\t\tif (sbi->s_cluster_ratio > 1)\n\t\t\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;\n\t\t\tnewblock = map->m_lblk\n\t\t\t\t - le32_to_cpu(newex.ee_block)\n\t\t\t\t + ext4_ext_pblock(&newex);\n\t\t\t/* number of remaining blocks in the extent */\n\t\t\tallocated = ext4_ext_get_actual_len(&newex) -\n\t\t\t\t(map->m_lblk - le32_to_cpu(newex.ee_block));\n\t\t\tgoto out;\n\t\t}\n\t}", "\t/* find extent for this block */\n\tpath = ext4_ext_find_extent(inode, map->m_lblk, NULL);\n\tif (IS_ERR(path)) {\n\t\terr = PTR_ERR(path);\n\t\tpath = NULL;\n\t\tgoto out2;\n\t}", "\tdepth = ext_depth(inode);", "\t/*\n\t * consistent leaf must not be empty;\n\t * this situation is possible, though, _during_ tree modification;\n\t * this is why assert can't be put in ext4_ext_find_extent()\n\t */\n\tif (unlikely(path[depth].p_ext == NULL && depth != 0)) {\n\t\tEXT4_ERROR_INODE(inode, \"bad extent address \"\n\t\t\t\t \"lblock: %lu, depth: %d pblock %lld\",\n\t\t\t\t (unsigned long) map->m_lblk, depth,\n\t\t\t\t path[depth].p_block);\n\t\terr = -EIO;\n\t\tgoto out2;\n\t}", "\tex = path[depth].p_ext;\n\tif (ex) {\n\t\text4_lblk_t ee_block = le32_to_cpu(ex->ee_block);\n\t\text4_fsblk_t ee_start = ext4_ext_pblock(ex);\n\t\tunsigned short ee_len;", "\t\t/*\n\t\t * Uninitialized extents are treated as holes, except that\n\t\t * we split out initialized portions during a write.\n\t\t */\n\t\tee_len = ext4_ext_get_actual_len(ex);", "\t\ttrace_ext4_ext_show_extent(inode, ee_block, ee_start, ee_len);", "\t\t/* if found extent covers block, simply return it */\n\t\tif (in_range(map->m_lblk, ee_block, ee_len)) {\n\t\t\tnewblock = map->m_lblk - ee_block + ee_start;\n\t\t\t/* number of remaining blocks in the extent */\n\t\t\tallocated = ee_len - (map->m_lblk - ee_block);\n\t\t\text_debug(\"%u fit into %u:%d -> %llu\\n\", map->m_lblk,\n\t\t\t\t ee_block, ee_len, newblock);", "\t\t\t/*\n\t\t\t * Do not put uninitialized extent\n\t\t\t * in the cache\n\t\t\t */\n\t\t\tif (!ext4_ext_is_uninitialized(ex)) {\n\t\t\t\text4_ext_put_in_cache(inode, ee_block,\n\t\t\t\t\tee_len, ee_start);\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tret = ext4_ext_handle_uninitialized_extents(\n\t\t\t\thandle, inode, map, path, flags,\n\t\t\t\tallocated, newblock);\n\t\t\treturn ret;\n\t\t}\n\t}", "\tif ((sbi->s_cluster_ratio > 1) &&\n\t ext4_find_delalloc_cluster(inode, map->m_lblk, 0))\n\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;", "\t/*\n\t * requested block isn't allocated yet;\n\t * we couldn't try to create block if create flag is zero\n\t */\n\tif ((flags & EXT4_GET_BLOCKS_CREATE) == 0) {\n\t\t/*\n\t\t * put just found gap into cache to speed up\n\t\t * subsequent requests\n\t\t */\n\t\text4_ext_put_gap_in_cache(inode, path, map->m_lblk);\n\t\tgoto out2;\n\t}", "\t/*\n\t * Okay, we need to do block allocation.\n\t */\n\tmap->m_flags &= ~EXT4_MAP_FROM_CLUSTER;\n\tnewex.ee_block = cpu_to_le32(map->m_lblk);\n\tcluster_offset = map->m_lblk & (sbi->s_cluster_ratio-1);", "\t/*\n\t * If we are doing bigalloc, check to see if the extent returned\n\t * by ext4_ext_find_extent() implies a cluster we can use.\n\t */\n\tif (cluster_offset && ex &&\n\t get_implied_cluster_alloc(inode->i_sb, map, ex, path)) {\n\t\tar.len = allocated = map->m_len;\n\t\tnewblock = map->m_pblk;\n\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;\n\t\tgoto got_allocated_blocks;\n\t}", "\t/* find neighbour allocated blocks */\n\tar.lleft = map->m_lblk;\n\terr = ext4_ext_search_left(inode, path, &ar.lleft, &ar.pleft);\n\tif (err)\n\t\tgoto out2;\n\tar.lright = map->m_lblk;\n\tex2 = NULL;\n\terr = ext4_ext_search_right(inode, path, &ar.lright, &ar.pright, &ex2);\n\tif (err)\n\t\tgoto out2;", "\t/* Check if the extent after searching to the right implies a\n\t * cluster we can use. */\n\tif ((sbi->s_cluster_ratio > 1) && ex2 &&\n\t get_implied_cluster_alloc(inode->i_sb, map, ex2, path)) {\n\t\tar.len = allocated = map->m_len;\n\t\tnewblock = map->m_pblk;\n\t\tmap->m_flags |= EXT4_MAP_FROM_CLUSTER;\n\t\tgoto got_allocated_blocks;\n\t}", "\t/*\n\t * See if request is beyond maximum number of blocks we can have in\n\t * a single extent. For an initialized extent this limit is\n\t * EXT_INIT_MAX_LEN and for an uninitialized extent this limit is\n\t * EXT_UNINIT_MAX_LEN.\n\t */\n\tif (map->m_len > EXT_INIT_MAX_LEN &&\n\t !(flags & EXT4_GET_BLOCKS_UNINIT_EXT))\n\t\tmap->m_len = EXT_INIT_MAX_LEN;\n\telse if (map->m_len > EXT_UNINIT_MAX_LEN &&\n\t\t (flags & EXT4_GET_BLOCKS_UNINIT_EXT))\n\t\tmap->m_len = EXT_UNINIT_MAX_LEN;", "\t/* Check if we can really insert (m_lblk)::(m_lblk + m_len) extent */\n\tnewex.ee_len = cpu_to_le16(map->m_len);\n\terr = ext4_ext_check_overlap(sbi, inode, &newex, path);\n\tif (err)\n\t\tallocated = ext4_ext_get_actual_len(&newex);\n\telse\n\t\tallocated = map->m_len;", "\t/* allocate new block */\n\tar.inode = inode;\n\tar.goal = ext4_ext_find_goal(inode, path, map->m_lblk);\n\tar.logical = map->m_lblk;\n\t/*\n\t * We calculate the offset from the beginning of the cluster\n\t * for the logical block number, since when we allocate a\n\t * physical cluster, the physical block should start at the\n\t * same offset from the beginning of the cluster. This is\n\t * needed so that future calls to get_implied_cluster_alloc()\n\t * work correctly.\n\t */\n\toffset = map->m_lblk & (sbi->s_cluster_ratio - 1);\n\tar.len = EXT4_NUM_B2C(sbi, offset+allocated);\n\tar.goal -= offset;\n\tar.logical -= offset;\n\tif (S_ISREG(inode->i_mode))\n\t\tar.flags = EXT4_MB_HINT_DATA;\n\telse\n\t\t/* disable in-core preallocation for non-regular files */\n\t\tar.flags = 0;\n\tif (flags & EXT4_GET_BLOCKS_NO_NORMALIZE)\n\t\tar.flags |= EXT4_MB_HINT_NOPREALLOC;\n\tnewblock = ext4_mb_new_blocks(handle, &ar, &err);\n\tif (!newblock)\n\t\tgoto out2;\n\text_debug(\"allocate new block: goal %llu, found %llu/%u\\n\",\n\t\t ar.goal, newblock, allocated);\n\tfree_on_err = 1;\n\tallocated_clusters = ar.len;\n\tar.len = EXT4_C2B(sbi, ar.len) - offset;\n\tif (ar.len > allocated)\n\t\tar.len = allocated;", "got_allocated_blocks:\n\t/* try to insert new extent into found leaf and return */\n\text4_ext_store_pblock(&newex, newblock + offset);\n\tnewex.ee_len = cpu_to_le16(ar.len);\n\t/* Mark uninitialized */\n\tif (flags & EXT4_GET_BLOCKS_UNINIT_EXT){\n\t\text4_ext_mark_uninitialized(&newex);\n\t\t/*\n\t\t * io_end structure was created for every IO write to an\n\t\t * uninitialized extent. To avoid unnecessary conversion,\n\t\t * here we flag the IO that really needs the conversion.\n\t\t * For non asycn direct IO case, flag the inode state\n\t\t * that we need to perform conversion when IO is done.\n\t\t */\n\t\tif ((flags & EXT4_GET_BLOCKS_PRE_IO))\n\t\t\tset_unwritten = 1;\n\t\tif (ext4_should_dioread_nolock(inode))\n\t\t\tmap->m_flags |= EXT4_MAP_UNINIT;\n\t}", "\terr = 0;\n\tif ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0)\n\t\terr = check_eofblocks_fl(handle, inode, map->m_lblk,\n\t\t\t\t\t path, ar.len);\n\tif (!err)\n\t\terr = ext4_ext_insert_extent(handle, inode, path,\n\t\t\t\t\t &newex, flags);", "\tif (!err && set_unwritten) {\n\t\tif (io)\n\t\t\text4_set_io_unwritten_flag(inode, io);\n\t\telse\n\t\t\text4_set_inode_state(inode,\n\t\t\t\t\t EXT4_STATE_DIO_UNWRITTEN);\n\t}", "\tif (err && free_on_err) {\n\t\tint fb_flags = flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE ?\n\t\t\tEXT4_FREE_BLOCKS_NO_QUOT_UPDATE : 0;\n\t\t/* free data blocks we just allocated */\n\t\t/* not a good idea to call discard here directly,\n\t\t * but otherwise we'd need to call it every free() */\n\t\text4_discard_preallocations(inode);\n\t\text4_free_blocks(handle, inode, NULL, ext4_ext_pblock(&newex),\n\t\t\t\t ext4_ext_get_actual_len(&newex), fb_flags);\n\t\tgoto out2;\n\t}", "\t/* previous routine could use block we allocated */\n\tnewblock = ext4_ext_pblock(&newex);\n\tallocated = ext4_ext_get_actual_len(&newex);\n\tif (allocated > map->m_len)\n\t\tallocated = map->m_len;\n\tmap->m_flags |= EXT4_MAP_NEW;", "\t/*\n\t * Update reserved blocks/metadata blocks after successful\n\t * block allocation which had been deferred till now.\n\t */\n\tif (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {\n\t\tunsigned int reserved_clusters;\n\t\t/*\n\t\t * Check how many clusters we had reserved this allocated range\n\t\t */\n\t\treserved_clusters = get_reserved_cluster_alloc(inode,\n\t\t\t\t\t\tmap->m_lblk, allocated);\n\t\tif (map->m_flags & EXT4_MAP_FROM_CLUSTER) {\n\t\t\tif (reserved_clusters) {\n\t\t\t\t/*\n\t\t\t\t * We have clusters reserved for this range.\n\t\t\t\t * But since we are not doing actual allocation\n\t\t\t\t * and are simply using blocks from previously\n\t\t\t\t * allocated cluster, we should release the\n\t\t\t\t * reservation and not claim quota.\n\t\t\t\t */\n\t\t\t\text4_da_update_reserve_space(inode,\n\t\t\t\t\t\treserved_clusters, 0);\n\t\t\t}\n\t\t} else {\n\t\t\tBUG_ON(allocated_clusters < reserved_clusters);\n\t\t\t/* We will claim quota for all newly allocated blocks.*/\n\t\t\text4_da_update_reserve_space(inode, allocated_clusters,\n\t\t\t\t\t\t\t1);\n\t\t\tif (reserved_clusters < allocated_clusters) {\n\t\t\t\tstruct ext4_inode_info *ei = EXT4_I(inode);\n\t\t\t\tint reservation = allocated_clusters -\n\t\t\t\t\t\t reserved_clusters;\n\t\t\t\t/*\n\t\t\t\t * It seems we claimed few clusters outside of\n\t\t\t\t * the range of this allocation. We should give\n\t\t\t\t * it back to the reservation pool. This can\n\t\t\t\t * happen in the following case:\n\t\t\t\t *\n\t\t\t\t * * Suppose s_cluster_ratio is 4 (i.e., each\n\t\t\t\t * cluster has 4 blocks. Thus, the clusters\n\t\t\t\t * are [0-3],[4-7],[8-11]...\n\t\t\t\t * * First comes delayed allocation write for\n\t\t\t\t * logical blocks 10 & 11. Since there were no\n\t\t\t\t * previous delayed allocated blocks in the\n\t\t\t\t * range [8-11], we would reserve 1 cluster\n\t\t\t\t * for this write.\n\t\t\t\t * * Next comes write for logical blocks 3 to 8.\n\t\t\t\t * In this case, we will reserve 2 clusters\n\t\t\t\t * (for [0-3] and [4-7]; and not for [8-11] as\n\t\t\t\t * that range has a delayed allocated blocks.\n\t\t\t\t * Thus total reserved clusters now becomes 3.\n\t\t\t\t * * Now, during the delayed allocation writeout\n\t\t\t\t * time, we will first write blocks [3-8] and\n\t\t\t\t * allocate 3 clusters for writing these\n\t\t\t\t * blocks. Also, we would claim all these\n\t\t\t\t * three clusters above.\n\t\t\t\t * * Now when we come here to writeout the\n\t\t\t\t * blocks [10-11], we would expect to claim\n\t\t\t\t * the reservation of 1 cluster we had made\n\t\t\t\t * (and we would claim it since there are no\n\t\t\t\t * more delayed allocated blocks in the range\n\t\t\t\t * [8-11]. But our reserved cluster count had\n\t\t\t\t * already gone to 0.\n\t\t\t\t *\n\t\t\t\t * Thus, at the step 4 above when we determine\n\t\t\t\t * that there are still some unwritten delayed\n\t\t\t\t * allocated blocks outside of our current\n\t\t\t\t * block range, we should increment the\n\t\t\t\t * reserved clusters count so that when the\n\t\t\t\t * remaining blocks finally gets written, we\n\t\t\t\t * could claim them.\n\t\t\t\t */\n\t\t\t\tdquot_reserve_block(inode,\n\t\t\t\t\t\tEXT4_C2B(sbi, reservation));\n\t\t\t\tspin_lock(&ei->i_block_reservation_lock);\n\t\t\t\tei->i_reserved_data_blocks += reservation;\n\t\t\t\tspin_unlock(&ei->i_block_reservation_lock);\n\t\t\t}\n\t\t}\n\t}", "\t/*\n\t * Cache the extent and update transaction to commit on fdatasync only\n\t * when it is _not_ an uninitialized extent.\n\t */\n\tif ((flags & EXT4_GET_BLOCKS_UNINIT_EXT) == 0) {\n\t\text4_ext_put_in_cache(inode, map->m_lblk, allocated, newblock);\n\t\text4_update_inode_fsync_trans(handle, inode, 1);\n\t} else\n\t\text4_update_inode_fsync_trans(handle, inode, 0);\nout:\n\tif (allocated > map->m_len)\n\t\tallocated = map->m_len;\n\text4_ext_show_leaf(inode, path);\n\tmap->m_flags |= EXT4_MAP_MAPPED;\n\tmap->m_pblk = newblock;\n\tmap->m_len = allocated;\nout2:\n\tif (path) {\n\t\text4_ext_drop_refs(path);\n\t\tkfree(path);\n\t}", "\ttrace_ext4_ext_map_blocks_exit(inode, map->m_lblk,\n\t\tnewblock, map->m_len, err ? err : allocated);", "\treturn err ? err : allocated;\n}", "void ext4_ext_truncate(struct inode *inode)\n{\n\tstruct address_space *mapping = inode->i_mapping;\n\tstruct super_block *sb = inode->i_sb;\n\text4_lblk_t last_block;\n\thandle_t *handle;\n\tloff_t page_len;\n\tint err = 0;", "\t/*\n\t * finish any pending end_io work so we won't run the risk of\n\t * converting any truncated blocks to initialized later\n\t */\n\text4_flush_unwritten_io(inode);", "\t/*\n\t * probably first extent we're gonna free will be last in block\n\t */\n\terr = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, err);\n\tif (IS_ERR(handle))\n\t\treturn;", "\tif (inode->i_size % PAGE_CACHE_SIZE != 0) {\n\t\tpage_len = PAGE_CACHE_SIZE -\n\t\t\t(inode->i_size & (PAGE_CACHE_SIZE - 1));", "\t\terr = ext4_discard_partial_page_buffers(handle,\n\t\t\tmapping, inode->i_size, page_len, 0);", "\t\tif (err)\n\t\t\tgoto out_stop;\n\t}", "\tif (ext4_orphan_add(handle, inode))\n\t\tgoto out_stop;", "\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_ext_invalidate_cache(inode);", "\text4_discard_preallocations(inode);", "\t/*\n\t * TODO: optimization is possible here.\n\t * Probably we need not scan at all,\n\t * because page truncation is enough.\n\t */", "\t/* we have to know where to truncate from in crash case */\n\tEXT4_I(inode)->i_disksize = inode->i_size;\n\text4_mark_inode_dirty(handle, inode);", "\tlast_block = (inode->i_size + sb->s_blocksize - 1)\n\t\t\t>> EXT4_BLOCK_SIZE_BITS(sb);\n\terr = ext4_ext_remove_space(inode, last_block, EXT_MAX_BLOCKS - 1);", "\t/* In a multi-transaction truncate, we only make the final\n\t * transaction synchronous.\n\t */\n\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);", "\tup_write(&EXT4_I(inode)->i_data_sem);", "out_stop:\n\t/*\n\t * If this was a simple ftruncate() and the file will remain alive,\n\t * then we need to clear up the orphan record which we created above.\n\t * However, if this was a real unlink then we were called by\n\t * ext4_delete_inode(), and we allow that function to clean up the\n\t * orphan info for us.\n\t */\n\tif (inode->i_nlink)\n\t\text4_orphan_del(handle, inode);", "\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\text4_mark_inode_dirty(handle, inode);\n\text4_journal_stop(handle);\n}", "static void ext4_falloc_update_inode(struct inode *inode,\n\t\t\t\tint mode, loff_t new_size, int update_ctime)\n{\n\tstruct timespec now;", "\tif (update_ctime) {\n\t\tnow = current_fs_time(inode->i_sb);\n\t\tif (!timespec_equal(&inode->i_ctime, &now))\n\t\t\tinode->i_ctime = now;\n\t}\n\t/*\n\t * Update only when preallocation was requested beyond\n\t * the file size.\n\t */\n\tif (!(mode & FALLOC_FL_KEEP_SIZE)) {\n\t\tif (new_size > i_size_read(inode))\n\t\t\ti_size_write(inode, new_size);\n\t\tif (new_size > EXT4_I(inode)->i_disksize)\n\t\t\text4_update_i_disksize(inode, new_size);\n\t} else {\n\t\t/*\n\t\t * Mark that we allocate beyond EOF so the subsequent truncate\n\t\t * can proceed even if the new size is the same as i_size.\n\t\t */\n\t\tif (new_size > i_size_read(inode))\n\t\t\text4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);\n\t}", "}", "/*\n * preallocate space for a file. This implements ext4's fallocate file\n * operation, which gets called from sys_fallocate system call.\n * For block-mapped files, posix_fallocate should fall back to the method\n * of writing zeroes to the required new blocks (the same behavior which is\n * expected for file systems which do not support fallocate() system call).\n */\nlong ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)\n{\n\tstruct inode *inode = file->f_path.dentry->d_inode;\n\thandle_t *handle;\n\tloff_t new_size;\n\tunsigned int max_blocks;\n\tint ret = 0;\n\tint ret2 = 0;\n\tint retries = 0;\n\tint flags;\n\tstruct ext4_map_blocks map;\n\tunsigned int credits, blkbits = inode->i_blkbits;", "\t/*\n\t * currently supporting (pre)allocate mode for extent-based\n\t * files _only_\n\t */\n\tif (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))\n\t\treturn -EOPNOTSUPP;", "\t/* Return error if mode is not supported */\n\tif (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))\n\t\treturn -EOPNOTSUPP;", "\tif (mode & FALLOC_FL_PUNCH_HOLE)\n\t\treturn ext4_punch_hole(file, offset, len);", "\ttrace_ext4_fallocate_enter(inode, offset, len, mode);\n\tmap.m_lblk = offset >> blkbits;\n\t/*\n\t * We can't just convert len to max_blocks because\n\t * If blocksize = 4096 offset = 3072 and len = 2048\n\t */\n\tmax_blocks = (EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits)\n\t\t- map.m_lblk;\n\t/*\n\t * credits to insert 1 extent into extent tree\n\t */\n\tcredits = ext4_chunk_trans_blocks(inode, max_blocks);\n\tmutex_lock(&inode->i_mutex);\n\tret = inode_newsize_ok(inode, (len + offset));\n\tif (ret) {\n\t\tmutex_unlock(&inode->i_mutex);\n\t\ttrace_ext4_fallocate_exit(inode, offset, max_blocks, ret);\n\t\treturn ret;\n\t}\n\tflags = EXT4_GET_BLOCKS_CREATE_UNINIT_EXT;\n\tif (mode & FALLOC_FL_KEEP_SIZE)\n\t\tflags |= EXT4_GET_BLOCKS_KEEP_SIZE;\n\t/*\n\t * Don't normalize the request if it can fit in one extent so\n\t * that it doesn't get unnecessarily split into multiple\n\t * extents.\n\t */\n\tif (len <= EXT_UNINIT_MAX_LEN << blkbits)\n\t\tflags |= EXT4_GET_BLOCKS_NO_NORMALIZE;", "\t/* Prevent race condition between unwritten */\n\text4_flush_unwritten_io(inode);\nretry:\n\twhile (ret >= 0 && ret < max_blocks) {\n\t\tmap.m_lblk = map.m_lblk + ret;\n\t\tmap.m_len = max_blocks = max_blocks - ret;\n\t\thandle = ext4_journal_start(inode, credits);\n\t\tif (IS_ERR(handle)) {\n\t\t\tret = PTR_ERR(handle);\n\t\t\tbreak;\n\t\t}\n\t\tret = ext4_map_blocks(handle, inode, &map, flags);\n\t\tif (ret <= 0) {\n#ifdef EXT4FS_DEBUG\n\t\t\tWARN_ON(ret <= 0);\n\t\t\tprintk(KERN_ERR \"%s: ext4_ext_map_blocks \"\n\t\t\t\t \"returned error inode#%lu, block=%u, \"\n\t\t\t\t \"max_blocks=%u\", __func__,\n\t\t\t\t inode->i_ino, map.m_lblk, max_blocks);\n#endif\n\t\t\text4_mark_inode_dirty(handle, inode);\n\t\t\tret2 = ext4_journal_stop(handle);\n\t\t\tbreak;\n\t\t}\n\t\tif ((map.m_lblk + ret) >= (EXT4_BLOCK_ALIGN(offset + len,\n\t\t\t\t\t\tblkbits) >> blkbits))\n\t\t\tnew_size = offset + len;\n\t\telse\n\t\t\tnew_size = ((loff_t) map.m_lblk + ret) << blkbits;", "\t\text4_falloc_update_inode(inode, mode, new_size,\n\t\t\t\t\t (map.m_flags & EXT4_MAP_NEW));\n\t\text4_mark_inode_dirty(handle, inode);\n\t\tif ((file->f_flags & O_SYNC) && ret >= max_blocks)\n\t\t\text4_handle_sync(handle);\n\t\tret2 = ext4_journal_stop(handle);\n\t\tif (ret2)\n\t\t\tbreak;\n\t}\n\tif (ret == -ENOSPC &&\n\t\t\text4_should_retry_alloc(inode->i_sb, &retries)) {\n\t\tret = 0;\n\t\tgoto retry;\n\t}\n\tmutex_unlock(&inode->i_mutex);\n\ttrace_ext4_fallocate_exit(inode, offset, max_blocks,\n\t\t\t\tret > 0 ? ret2 : ret);\n\treturn ret > 0 ? ret2 : ret;\n}", "/*\n * This function convert a range of blocks to written extents\n * The caller of this function will pass the start offset and the size.\n * all unwritten extents within this range will be converted to\n * written extents.\n *\n * This function is called from the direct IO end io call back\n * function, to convert the fallocated extents after IO is completed.\n * Returns 0 on success.\n */\nint ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,\n\t\t\t\t ssize_t len)\n{\n\thandle_t *handle;\n\tunsigned int max_blocks;\n\tint ret = 0;\n\tint ret2 = 0;\n\tstruct ext4_map_blocks map;\n\tunsigned int credits, blkbits = inode->i_blkbits;", "\tmap.m_lblk = offset >> blkbits;\n\t/*\n\t * We can't just convert len to max_blocks because\n\t * If blocksize = 4096 offset = 3072 and len = 2048\n\t */\n\tmax_blocks = ((EXT4_BLOCK_ALIGN(len + offset, blkbits) >> blkbits) -\n\t\t map.m_lblk);\n\t/*\n\t * credits to insert 1 extent into extent tree\n\t */\n\tcredits = ext4_chunk_trans_blocks(inode, max_blocks);\n\twhile (ret >= 0 && ret < max_blocks) {\n\t\tmap.m_lblk += ret;\n\t\tmap.m_len = (max_blocks -= ret);\n\t\thandle = ext4_journal_start(inode, credits);\n\t\tif (IS_ERR(handle)) {\n\t\t\tret = PTR_ERR(handle);\n\t\t\tbreak;\n\t\t}\n\t\tret = ext4_map_blocks(handle, inode, &map,\n\t\t\t\t EXT4_GET_BLOCKS_IO_CONVERT_EXT);\n\t\tif (ret <= 0) {\n\t\t\tWARN_ON(ret <= 0);\n\t\t\text4_msg(inode->i_sb, KERN_ERR,\n\t\t\t\t \"%s:%d: inode #%lu: block %u: len %u: \"\n\t\t\t\t \"ext4_ext_map_blocks returned %d\",\n\t\t\t\t __func__, __LINE__, inode->i_ino, map.m_lblk,\n\t\t\t\t map.m_len, ret);\n\t\t}\n\t\text4_mark_inode_dirty(handle, inode);\n\t\tret2 = ext4_journal_stop(handle);\n\t\tif (ret <= 0 || ret2 )\n\t\t\tbreak;\n\t}\n\treturn ret > 0 ? ret2 : ret;\n}", "/*\n * Callback function called for each extent to gather FIEMAP information.\n */\nstatic int ext4_ext_fiemap_cb(struct inode *inode, ext4_lblk_t next,\n\t\t struct ext4_ext_cache *newex, struct ext4_extent *ex,\n\t\t void *data)\n{\n\t__u64\tlogical;\n\t__u64\tphysical;\n\t__u64\tlength;\n\t__u32\tflags = 0;\n\tint\t\tret = 0;\n\tstruct fiemap_extent_info *fieinfo = data;\n\tunsigned char blksize_bits;", "\tblksize_bits = inode->i_sb->s_blocksize_bits;\n\tlogical = (__u64)newex->ec_block << blksize_bits;", "\tif (newex->ec_start == 0) {\n\t\t/*\n\t\t * No extent in extent-tree contains block @newex->ec_start,\n\t\t * then the block may stay in 1)a hole or 2)delayed-extent.\n\t\t *\n\t\t * Holes or delayed-extents are processed as follows.\n\t\t * 1. lookup dirty pages with specified range in pagecache.\n\t\t * If no page is got, then there is no delayed-extent and\n\t\t * return with EXT_CONTINUE.\n\t\t * 2. find the 1st mapped buffer,\n\t\t * 3. check if the mapped buffer is both in the request range\n\t\t * and a delayed buffer. If not, there is no delayed-extent,\n\t\t * then return.\n\t\t * 4. a delayed-extent is found, the extent will be collected.\n\t\t */\n\t\text4_lblk_t\tend = 0;\n\t\tpgoff_t\t\tlast_offset;\n\t\tpgoff_t\t\toffset;\n\t\tpgoff_t\t\tindex;\n\t\tpgoff_t\t\tstart_index = 0;\n\t\tstruct page\t**pages = NULL;\n\t\tstruct buffer_head *bh = NULL;\n\t\tstruct buffer_head *head = NULL;\n\t\tunsigned int nr_pages = PAGE_SIZE / sizeof(struct page *);", "\t\tpages = kmalloc(PAGE_SIZE, GFP_KERNEL);\n\t\tif (pages == NULL)\n\t\t\treturn -ENOMEM;", "\t\toffset = logical >> PAGE_SHIFT;\nrepeat:\n\t\tlast_offset = offset;\n\t\thead = NULL;\n\t\tret = find_get_pages_tag(inode->i_mapping, &offset,\n\t\t\t\t\tPAGECACHE_TAG_DIRTY, nr_pages, pages);", "\t\tif (!(flags & FIEMAP_EXTENT_DELALLOC)) {\n\t\t\t/* First time, try to find a mapped buffer. */\n\t\t\tif (ret == 0) {\nout:\n\t\t\t\tfor (index = 0; index < ret; index++)\n\t\t\t\t\tpage_cache_release(pages[index]);\n\t\t\t\t/* just a hole. */\n\t\t\t\tkfree(pages);\n\t\t\t\treturn EXT_CONTINUE;\n\t\t\t}\n\t\t\tindex = 0;", "next_page:\n\t\t\t/* Try to find the 1st mapped buffer. */\n\t\t\tend = ((__u64)pages[index]->index << PAGE_SHIFT) >>\n\t\t\t\t blksize_bits;\n\t\t\tif (!page_has_buffers(pages[index]))\n\t\t\t\tgoto out;\n\t\t\thead = page_buffers(pages[index]);\n\t\t\tif (!head)\n\t\t\t\tgoto out;", "\t\t\tindex++;\n\t\t\tbh = head;\n\t\t\tdo {\n\t\t\t\tif (end >= newex->ec_block +\n\t\t\t\t\tnewex->ec_len)\n\t\t\t\t\t/* The buffer is out of\n\t\t\t\t\t * the request range.\n\t\t\t\t\t */\n\t\t\t\t\tgoto out;", "\t\t\t\tif (buffer_mapped(bh) &&\n\t\t\t\t end >= newex->ec_block) {\n\t\t\t\t\tstart_index = index - 1;\n\t\t\t\t\t/* get the 1st mapped buffer. */\n\t\t\t\t\tgoto found_mapped_buffer;\n\t\t\t\t}", "\t\t\t\tbh = bh->b_this_page;\n\t\t\t\tend++;\n\t\t\t} while (bh != head);", "\t\t\t/* No mapped buffer in the range found in this page,\n\t\t\t * We need to look up next page.\n\t\t\t */\n\t\t\tif (index >= ret) {\n\t\t\t\t/* There is no page left, but we need to limit\n\t\t\t\t * newex->ec_len.\n\t\t\t\t */\n\t\t\t\tnewex->ec_len = end - newex->ec_block;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tgoto next_page;\n\t\t} else {\n\t\t\t/*Find contiguous delayed buffers. */\n\t\t\tif (ret > 0 && pages[0]->index == last_offset)\n\t\t\t\thead = page_buffers(pages[0]);\n\t\t\tbh = head;\n\t\t\tindex = 1;\n\t\t\tstart_index = 0;\n\t\t}", "found_mapped_buffer:\n\t\tif (bh != NULL && buffer_delay(bh)) {\n\t\t\t/* 1st or contiguous delayed buffer found. */\n\t\t\tif (!(flags & FIEMAP_EXTENT_DELALLOC)) {\n\t\t\t\t/*\n\t\t\t\t * 1st delayed buffer found, record\n\t\t\t\t * the start of extent.\n\t\t\t\t */\n\t\t\t\tflags |= FIEMAP_EXTENT_DELALLOC;\n\t\t\t\tnewex->ec_block = end;\n\t\t\t\tlogical = (__u64)end << blksize_bits;\n\t\t\t}\n\t\t\t/* Find contiguous delayed buffers. */\n\t\t\tdo {\n\t\t\t\tif (!buffer_delay(bh))\n\t\t\t\t\tgoto found_delayed_extent;\n\t\t\t\tbh = bh->b_this_page;\n\t\t\t\tend++;\n\t\t\t} while (bh != head);", "\t\t\tfor (; index < ret; index++) {\n\t\t\t\tif (!page_has_buffers(pages[index])) {\n\t\t\t\t\tbh = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\thead = page_buffers(pages[index]);\n\t\t\t\tif (!head) {\n\t\t\t\t\tbh = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}", "\t\t\t\tif (pages[index]->index !=\n\t\t\t\t pages[start_index]->index + index\n\t\t\t\t - start_index) {\n\t\t\t\t\t/* Blocks are not contiguous. */\n\t\t\t\t\tbh = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbh = head;\n\t\t\t\tdo {\n\t\t\t\t\tif (!buffer_delay(bh))\n\t\t\t\t\t\t/* Delayed-extent ends. */\n\t\t\t\t\t\tgoto found_delayed_extent;\n\t\t\t\t\tbh = bh->b_this_page;\n\t\t\t\t\tend++;\n\t\t\t\t} while (bh != head);\n\t\t\t}\n\t\t} else if (!(flags & FIEMAP_EXTENT_DELALLOC))\n\t\t\t/* a hole found. */\n\t\t\tgoto out;", "found_delayed_extent:\n\t\tnewex->ec_len = min(end - newex->ec_block,\n\t\t\t\t\t\t(ext4_lblk_t)EXT_INIT_MAX_LEN);\n\t\tif (ret == nr_pages && bh != NULL &&\n\t\t\tnewex->ec_len < EXT_INIT_MAX_LEN &&\n\t\t\tbuffer_delay(bh)) {\n\t\t\t/* Have not collected an extent and continue. */\n\t\t\tfor (index = 0; index < ret; index++)\n\t\t\t\tpage_cache_release(pages[index]);\n\t\t\tgoto repeat;\n\t\t}", "\t\tfor (index = 0; index < ret; index++)\n\t\t\tpage_cache_release(pages[index]);\n\t\tkfree(pages);\n\t}", "\tphysical = (__u64)newex->ec_start << blksize_bits;\n\tlength = (__u64)newex->ec_len << blksize_bits;", "\tif (ex && ext4_ext_is_uninitialized(ex))\n\t\tflags |= FIEMAP_EXTENT_UNWRITTEN;", "\tif (next == EXT_MAX_BLOCKS)\n\t\tflags |= FIEMAP_EXTENT_LAST;", "\tret = fiemap_fill_next_extent(fieinfo, logical, physical,\n\t\t\t\t\tlength, flags);\n\tif (ret < 0)\n\t\treturn ret;\n\tif (ret == 1)\n\t\treturn EXT_BREAK;\n\treturn EXT_CONTINUE;\n}\n/* fiemap flags we can handle specified here */\n#define EXT4_FIEMAP_FLAGS\t(FIEMAP_FLAG_SYNC|FIEMAP_FLAG_XATTR)", "static int ext4_xattr_fiemap(struct inode *inode,\n\t\t\t\tstruct fiemap_extent_info *fieinfo)\n{\n\t__u64 physical = 0;\n\t__u64 length;\n\t__u32 flags = FIEMAP_EXTENT_LAST;\n\tint blockbits = inode->i_sb->s_blocksize_bits;\n\tint error = 0;", "\t/* in-inode? */\n\tif (ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {\n\t\tstruct ext4_iloc iloc;\n\t\tint offset;\t/* offset of xattr in inode */", "\t\terror = ext4_get_inode_loc(inode, &iloc);\n\t\tif (error)\n\t\t\treturn error;\n\t\tphysical = iloc.bh->b_blocknr << blockbits;\n\t\toffset = EXT4_GOOD_OLD_INODE_SIZE +\n\t\t\t\tEXT4_I(inode)->i_extra_isize;\n\t\tphysical += offset;\n\t\tlength = EXT4_SB(inode->i_sb)->s_inode_size - offset;\n\t\tflags |= FIEMAP_EXTENT_DATA_INLINE;\n\t\tbrelse(iloc.bh);\n\t} else { /* external block */\n\t\tphysical = EXT4_I(inode)->i_file_acl << blockbits;\n\t\tlength = inode->i_sb->s_blocksize;\n\t}", "\tif (physical)\n\t\terror = fiemap_fill_next_extent(fieinfo, 0, physical,\n\t\t\t\t\t\tlength, flags);\n\treturn (error < 0 ? error : 0);\n}", "/*\n * ext4_ext_punch_hole\n *\n * Punches a hole of \"length\" bytes in a file starting\n * at byte \"offset\"\n *\n * @inode: The inode of the file to punch a hole in\n * @offset: The starting byte offset of the hole\n * @length: The length of the hole\n *\n * Returns the number of blocks removed or negative on err\n */\nint ext4_ext_punch_hole(struct file *file, loff_t offset, loff_t length)\n{\n\tstruct inode *inode = file->f_path.dentry->d_inode;\n\tstruct super_block *sb = inode->i_sb;\n\text4_lblk_t first_block, stop_block;\n\tstruct address_space *mapping = inode->i_mapping;\n\thandle_t *handle;\n\tloff_t first_page, last_page, page_len;\n\tloff_t first_page_offset, last_page_offset;\n\tint credits, err = 0;", "\t/*\n\t * Write out all dirty pages to avoid race conditions\n\t * Then release them.\n\t */\n\tif (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {\n\t\terr = filemap_write_and_wait_range(mapping,\n\t\t\toffset, offset + length - 1);", "\t\tif (err)\n\t\t\treturn err;\n\t}", "\tmutex_lock(&inode->i_mutex);\n\t/* It's not possible punch hole on append only file */\n\tif (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {\n\t\terr = -EPERM;\n\t\tgoto out_mutex;\n\t}\n\tif (IS_SWAPFILE(inode)) {\n\t\terr = -ETXTBSY;\n\t\tgoto out_mutex;\n\t}", "\t/* No need to punch hole beyond i_size */\n\tif (offset >= inode->i_size)\n\t\tgoto out_mutex;", "\t/*\n\t * If the hole extends beyond i_size, set the hole\n\t * to end after the page that contains i_size\n\t */\n\tif (offset + length > inode->i_size) {\n\t\tlength = inode->i_size +\n\t\t PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -\n\t\t offset;\n\t}", "\tfirst_page = (offset + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;\n\tlast_page = (offset + length) >> PAGE_CACHE_SHIFT;", "\tfirst_page_offset = first_page << PAGE_CACHE_SHIFT;\n\tlast_page_offset = last_page << PAGE_CACHE_SHIFT;", "\t/* Now release the pages */\n\tif (last_page_offset > first_page_offset) {\n\t\ttruncate_pagecache_range(inode, first_page_offset,\n\t\t\t\t\t last_page_offset - 1);\n\t}", "\t/* Wait all existing dio workers, newcomers will block on i_mutex */\n\text4_inode_block_unlocked_dio(inode);\n\terr = ext4_flush_unwritten_io(inode);\n\tif (err)\n\t\tgoto out_dio;\n\tinode_dio_wait(inode);", "\tcredits = ext4_writepage_trans_blocks(inode);\n\thandle = ext4_journal_start(inode, credits);\n\tif (IS_ERR(handle)) {\n\t\terr = PTR_ERR(handle);\n\t\tgoto out_dio;\n\t}", "\n\t/*\n\t * Now we need to zero out the non-page-aligned data in the\n\t * pages at the start and tail of the hole, and unmap the buffer\n\t * heads for the block aligned regions of the page that were\n\t * completely zeroed.\n\t */\n\tif (first_page > last_page) {\n\t\t/*\n\t\t * If the file space being truncated is contained within a page\n\t\t * just zero out and unmap the middle of that page\n\t\t */\n\t\terr = ext4_discard_partial_page_buffers(handle,\n\t\t\tmapping, offset, length, 0);", "\t\tif (err)\n\t\t\tgoto out;\n\t} else {\n\t\t/*\n\t\t * zero out and unmap the partial page that contains\n\t\t * the start of the hole\n\t\t */\n\t\tpage_len = first_page_offset - offset;\n\t\tif (page_len > 0) {\n\t\t\terr = ext4_discard_partial_page_buffers(handle, mapping,\n\t\t\t\t\t\t offset, page_len, 0);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}", "\t\t/*\n\t\t * zero out and unmap the partial page that contains\n\t\t * the end of the hole\n\t\t */\n\t\tpage_len = offset + length - last_page_offset;\n\t\tif (page_len > 0) {\n\t\t\terr = ext4_discard_partial_page_buffers(handle, mapping,\n\t\t\t\t\tlast_page_offset, page_len, 0);\n\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}\n\t}", "\t/*\n\t * If i_size is contained in the last page, we need to\n\t * unmap and zero the partial page after i_size\n\t */\n\tif (inode->i_size >> PAGE_CACHE_SHIFT == last_page &&\n\t inode->i_size % PAGE_CACHE_SIZE != 0) {", "\t\tpage_len = PAGE_CACHE_SIZE -\n\t\t\t(inode->i_size & (PAGE_CACHE_SIZE - 1));", "\t\tif (page_len > 0) {\n\t\t\terr = ext4_discard_partial_page_buffers(handle,\n\t\t\t mapping, inode->i_size, page_len, 0);", "\t\t\tif (err)\n\t\t\t\tgoto out;\n\t\t}\n\t}", "\tfirst_block = (offset + sb->s_blocksize - 1) >>\n\t\tEXT4_BLOCK_SIZE_BITS(sb);\n\tstop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);", "\t/* If there are no blocks to remove, return now */\n\tif (first_block >= stop_block)\n\t\tgoto out;", "\tdown_write(&EXT4_I(inode)->i_data_sem);\n\text4_ext_invalidate_cache(inode);\n\text4_discard_preallocations(inode);", "\terr = ext4_ext_remove_space(inode, first_block, stop_block - 1);", "\text4_ext_invalidate_cache(inode);\n\text4_discard_preallocations(inode);", "\tif (IS_SYNC(inode))\n\t\text4_handle_sync(handle);", "\tup_write(&EXT4_I(inode)->i_data_sem);", "out:\n\tinode->i_mtime = inode->i_ctime = ext4_current_time(inode);\n\text4_mark_inode_dirty(handle, inode);\n\text4_journal_stop(handle);\nout_dio:\n\text4_inode_resume_unlocked_dio(inode);\nout_mutex:\n\tmutex_unlock(&inode->i_mutex);\n\treturn err;\n}\nint ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,\n\t\t__u64 start, __u64 len)\n{\n\text4_lblk_t start_blk;\n\tint error = 0;", "\t/* fallback to generic here if not in extents fmt */\n\tif (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))\n\t\treturn generic_block_fiemap(inode, fieinfo, start, len,\n\t\t\text4_get_block);", "\tif (fiemap_check_flags(fieinfo, EXT4_FIEMAP_FLAGS))\n\t\treturn -EBADR;", "\tif (fieinfo->fi_flags & FIEMAP_FLAG_XATTR) {\n\t\terror = ext4_xattr_fiemap(inode, fieinfo);\n\t} else {\n\t\text4_lblk_t len_blks;\n\t\t__u64 last_blk;", "\t\tstart_blk = start >> inode->i_sb->s_blocksize_bits;\n\t\tlast_blk = (start + len - 1) >> inode->i_sb->s_blocksize_bits;\n\t\tif (last_blk >= EXT_MAX_BLOCKS)\n\t\t\tlast_blk = EXT_MAX_BLOCKS-1;\n\t\tlen_blks = ((ext4_lblk_t) last_blk) - start_blk + 1;", "\t\t/*\n\t\t * Walk the extent tree gathering extent information.\n\t\t * ext4_ext_fiemap_cb will push extents back to user.\n\t\t */\n\t\terror = ext4_ext_walk_space(inode, start_blk, len_blks,\n\t\t\t\t\t ext4_ext_fiemap_cb, fieinfo);\n\t}", "\treturn error;\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [3656], "buggy_code_start_loc": [53], "filenames": ["fs/ext4/extents.c"], "fixing_code_end_loc": [3691], "fixing_code_start_loc": [54], "message": "Race condition in fs/ext4/extents.c in the Linux kernel before 3.4.16 allows local users to obtain sensitive information from a deleted file by reading an extent that was not properly marked as uninitialized.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*", "matchCriteriaId": "2F399128-7646-4F7C-83D5-1C9461024AF6", "versionEndExcluding": null, "versionEndIncluding": "3.4.15", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc1:*:*:*:*:*:*", "matchCriteriaId": "D30AEC07-3CBD-4F4F-9646-BEAA1D98750B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc2:*:*:*:*:*:*", "matchCriteriaId": "C2AA8E68-691B-499C-AEDD-3C0BFFE70044", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc3:*:*:*:*:*:*", "matchCriteriaId": "9440475B-5960-4066-A204-F30AAFC87846", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc4:*:*:*:*:*:*", "matchCriteriaId": "53BCFBFB-6AF0-4525-8623-7633CC5E17DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc5:*:*:*:*:*:*", "matchCriteriaId": "6ED4E86A-74F0-436A-BEB4-3F4EE93A5421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc6:*:*:*:*:*:*", "matchCriteriaId": "BF0365B0-8E16-4F30-BD92-5DD538CC8135", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0:rc7:*:*:*:*:*:*", "matchCriteriaId": "079505E8-2942-4C33-93D1-35ADA4C39E72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.1:*:*:*:*:*:*:*", "matchCriteriaId": "38989541-2360-4E0A-AE5A-3D6144AA6114", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.2:*:*:*:*:*:*:*", "matchCriteriaId": "4E51646B-7A0E-40F3-B8C9-239C1DA81DD1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "42A8A507-F8E2-491C-A144-B2448A1DB26E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.4:*:*:*:*:*:*:*", "matchCriteriaId": "901FC6F3-2C2A-4112-AE27-AB102BBE8DEE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.5:*:*:*:*:*:*:*", "matchCriteriaId": "203AD334-DB9F-41B0-A4D1-A6C158EF8C40", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.6:*:*:*:*:*:*:*", "matchCriteriaId": "B3611753-E440-410F-8250-600C996A4B8E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.7:*:*:*:*:*:*:*", "matchCriteriaId": "9739BB47-EEAF-42F1-A557-2AE2EA9526A3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.8:*:*:*:*:*:*:*", "matchCriteriaId": "5A95E3BB-0AFC-4C2E-B9BE-C975E902A266", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.9:*:*:*:*:*:*:*", "matchCriteriaId": "482A6C9A-9B8E-4D1C-917A-F16370745E7C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.10:*:*:*:*:*:*:*", "matchCriteriaId": "C6D87357-63E0-41D0-9F02-1BCBF9A77E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.11:*:*:*:*:*:*:*", "matchCriteriaId": "3765A2D6-2D78-4FB1-989E-D5106BFA3F5E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.12:*:*:*:*:*:*:*", "matchCriteriaId": "F54257DB-7023-43C4-AC4D-9590B815CD92", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.13:*:*:*:*:*:*:*", "matchCriteriaId": "61FF5FCD-A4A1-4803-AC53-320A4C838AF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.14:*:*:*:*:*:*:*", "matchCriteriaId": "9F096553-064F-46A2-877B-F32F163A0F49", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.15:*:*:*:*:*:*:*", "matchCriteriaId": "C0D762D1-E3AD-40EA-8D39-83EEB51B5E85", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.16:*:*:*:*:*:*:*", "matchCriteriaId": "A6187D19-7148-4B87-AD7E-244FF9EE0FA6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.17:*:*:*:*:*:*:*", "matchCriteriaId": "99AC64C2-E391-485C-9CD7-BA09C8FA5E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.18:*:*:*:*:*:*:*", "matchCriteriaId": "8CDA5E95-7805-441B-BEF7-4448EA45E964", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.19:*:*:*:*:*:*:*", "matchCriteriaId": "51561053-6C28-4F38-BC9B-3F7A7508EB72", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.20:*:*:*:*:*:*:*", "matchCriteriaId": "118F4A5B-C498-4FC3-BE28-50D18EBE4F22", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.21:*:*:*:*:*:*:*", "matchCriteriaId": "BD38EBE6-FE1A-4B55-9FB5-07952253B7A5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.22:*:*:*:*:*:*:*", "matchCriteriaId": "3A491E47-82AD-4055-9444-2EC0D6715326", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.23:*:*:*:*:*:*:*", "matchCriteriaId": "13C5FD16-23B6-467F-9438-5B554922F974", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.24:*:*:*:*:*:*:*", "matchCriteriaId": "9C67235F-5B51-4BF7-89EC-4810F720246F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.25:*:*:*:*:*:*:*", "matchCriteriaId": "08405DEF-05F4-45F0-AC95-DBF914A36D93", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.26:*:*:*:*:*:*:*", "matchCriteriaId": "1A7B9C4B-4A41-4175-9F07-191C1EE98C1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.27:*:*:*:*:*:*:*", "matchCriteriaId": "B306E0A8-4D4A-4895-8128-A500D30A7E0C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.28:*:*:*:*:*:*:*", "matchCriteriaId": "295C839A-F34E-4853-A926-55EABC639412", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.29:*:*:*:*:*:*:*", "matchCriteriaId": "2AFD5F49-7EF9-4CFE-95BD-8FD19B500B0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.30:*:*:*:*:*:*:*", "matchCriteriaId": "00B3DDDD-B2F6-4753-BA38-65A24017857D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.31:*:*:*:*:*:*:*", "matchCriteriaId": "33FCD39E-F4BF-432D-9CF9-F195CF5844F3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.32:*:*:*:*:*:*:*", "matchCriteriaId": "C7308690-CB0D-4758-B80F-D2ADCD2A9D66", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.33:*:*:*:*:*:*:*", "matchCriteriaId": "313A470B-8A2B-478A-82B5-B27D2718331C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.34:*:*:*:*:*:*:*", "matchCriteriaId": "83FF021E-07E3-41CC-AAE8-D99D7FF24B9D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.35:*:*:*:*:*:*:*", "matchCriteriaId": "F72412E3-8DA9-4CC9-A426-B534202ADBA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.36:*:*:*:*:*:*:*", "matchCriteriaId": "FCAA9D7A-3C3E-4C0B-9D38-EA80E68C2E46", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.37:*:*:*:*:*:*:*", "matchCriteriaId": "4A9E3AE5-3FCF-4CBB-A30B-082BCFBFB0CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.38:*:*:*:*:*:*:*", "matchCriteriaId": "CF715657-4C3A-4392-B85D-1BBF4DE45D89", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.39:*:*:*:*:*:*:*", "matchCriteriaId": "4B63C618-AC3D-4EF7-AFDF-27B9BF482B78", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.40:*:*:*:*:*:*:*", "matchCriteriaId": "C33DA5A9-5E40-4365-9602-82FB4DCD15B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.41:*:*:*:*:*:*:*", "matchCriteriaId": "EFAFDB74-40BD-46FA-89AC-617EB2C7160B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.42:*:*:*:*:*:*:*", "matchCriteriaId": "CF5F17DA-30A7-40CF-BD7C-CEDF06D64617", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.43:*:*:*:*:*:*:*", "matchCriteriaId": "71A276F5-BD9D-4C1B-90DF-9B0C15B6F7DF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.0.44:*:*:*:*:*:*:*", "matchCriteriaId": "F8F6EBEC-3C29-444B-BB85-6EF239B59EC1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:*:*:*:*:*:*:*", "matchCriteriaId": "3DFFE5A6-6A67-4992-84A3-C0F05FACDEAD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc1:*:*:*:*:*:*", "matchCriteriaId": "13BBD2A3-AE10-48B9-8776-4FB1CAC37D44", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc2:*:*:*:*:*:*", "matchCriteriaId": "B25680CC-8918-4F27-8D7E-A6579215450B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc3:*:*:*:*:*:*", "matchCriteriaId": "92C48B4C-410C-4BA8-A28A-B2E928320FCC", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1:rc4:*:*:*:*:*:*", "matchCriteriaId": "CB447523-855B-461E-8197-95169BE86EB0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.1:*:*:*:*:*:*:*", "matchCriteriaId": "B155BBDF-6DF6-4FF5-9C41-D8A5266DCC67", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.2:*:*:*:*:*:*:*", "matchCriteriaId": "28476DEC-9630-4B40-9D4D-9BC151DC4CA4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.3:*:*:*:*:*:*:*", "matchCriteriaId": "5646880A-2355-4BDD-89E7-825863A0311F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.4:*:*:*:*:*:*:*", "matchCriteriaId": "7FF99148-267A-46F8-9927-A9082269BAF6", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.5:*:*:*:*:*:*:*", "matchCriteriaId": "A783C083-5D9C-48F9-B5A6-A97A9604FB19", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.6:*:*:*:*:*:*:*", "matchCriteriaId": "2B817A24-03AC-46CD-BEFA-505457FD2A5D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.7:*:*:*:*:*:*:*", "matchCriteriaId": "51CF1BCE-090E-4B70-BA16-ACB74411293B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.8:*:*:*:*:*:*:*", "matchCriteriaId": "187AAD67-10D7-4B57-B4C6-00443E246AF3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.9:*:*:*:*:*:*:*", "matchCriteriaId": "F341CE88-C5BC-4CDD-9CB5-B6BAD7152E63", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.1.10:*:*:*:*:*:*:*", "matchCriteriaId": "37ACE2A6-C229-4236-8E9F-235F008F3AA0", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:*:*", "matchCriteriaId": "D3220B70-917F-4F9F-8A3B-2BF581281E8D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:*:*:*:*:*:x86:*", "matchCriteriaId": "7D47A395-821D-4BFF-996E-E849D9A40217", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc2:*:*:*:*:*:*", "matchCriteriaId": "99372D07-C06A-41FA-9843-6D57F99AB5AF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc3:*:*:*:*:*:*", "matchCriteriaId": "2B9DC110-D260-4DB4-B8B0-EF1D160ADA07", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc4:*:*:*:*:*:*", "matchCriteriaId": "6192FE84-4D53-40D4-AF61-78CE7136141A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc5:*:*:*:*:*:*", "matchCriteriaId": "42FEF3CF-1302-45EB-89CC-3786FE4BAC1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc6:*:*:*:*:*:*", "matchCriteriaId": "AE6A6B58-2C89-4DE4-BA57-78100818095C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2:rc7:*:*:*:*:*:*", "matchCriteriaId": "1D467F87-2F13-4D26-9A93-E0BA526FEA24", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:*:*", "matchCriteriaId": "FE348F7B-02DE-47D5-8011-F83DA9426021", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.1:*:*:*:*:*:x86:*", "matchCriteriaId": "8A603291-33B4-4195-B52D-D2A9938089C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.2:*:*:*:*:*:*:*", "matchCriteriaId": "E91594EA-F0A3-41B3-A9C6-F7864FC2F229", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.3:*:*:*:*:*:*:*", "matchCriteriaId": "9E1ECCDB-0208-48F6-B44F-16CC0ECE3503", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.4:*:*:*:*:*:*:*", "matchCriteriaId": "FBA8B5DE-372E-47E0-A0F6-BE286D509CC3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.5:*:*:*:*:*:*:*", "matchCriteriaId": "9A1CA083-2CF8-45AE-9E15-1AA3A8352E3B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.6:*:*:*:*:*:*:*", "matchCriteriaId": "19D69A49-5290-4C5F-8157-719AD58D253D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.7:*:*:*:*:*:*:*", "matchCriteriaId": "290BD969-42E7-47B0-B21B-06DE4865432C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.8:*:*:*:*:*:*:*", "matchCriteriaId": "23A9E29E-DE78-4C73-9FBD-C2410F5FC8B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.9:*:*:*:*:*:*:*", "matchCriteriaId": "018434C9-E75F-45CB-A169-DAB4B1D864D7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.10:*:*:*:*:*:*:*", "matchCriteriaId": "DC0AC68F-EC58-4C4F-8CBC-A59ECC00CCDE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.11:*:*:*:*:*:*:*", "matchCriteriaId": "C123C844-F6D7-471E-A62E-F756042FB1CD", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.12:*:*:*:*:*:*:*", "matchCriteriaId": "A11C38BB-7FA2-49B0-AAC9-83DB387A06DB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.13:*:*:*:*:*:*:*", "matchCriteriaId": "61F3733C-E5F6-4855-B471-DF3FB823613B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.14:*:*:*:*:*:*:*", "matchCriteriaId": "1DDCA75F-9A06-4457-9A45-38A38E7F7086", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.15:*:*:*:*:*:*:*", "matchCriteriaId": "7AEA837E-7864-4003-8DB7-111ED710A7E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.16:*:*:*:*:*:*:*", "matchCriteriaId": "B6FE471F-2D1F-4A1D-A197-7E46B75787E1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.17:*:*:*:*:*:*:*", "matchCriteriaId": "FDA9E6AB-58DC-4EC5-A25C-11F9D0B38BF7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.18:*:*:*:*:*:*:*", "matchCriteriaId": "DC6B8DB3-B05B-41A2-B091-342D66AAE8F5", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.19:*:*:*:*:*:*:*", "matchCriteriaId": "958F0FF8-33EF-4A71-A0BD-572C85211DBA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.20:*:*:*:*:*:*:*", "matchCriteriaId": "FBA39F48-B02F-4C48-B304-DA9CCA055244", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.21:*:*:*:*:*:*:*", "matchCriteriaId": "1FF841F3-48A7-41D7-9C45-A8170435A5EB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.22:*:*:*:*:*:*:*", "matchCriteriaId": "EF506916-A6DC-4B1E-90E5-959492AF55F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.23:*:*:*:*:*:*:*", "matchCriteriaId": "B3CDAD1F-2C6A-48C0-8FAB-C2659373FA25", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.24:*:*:*:*:*:*:*", "matchCriteriaId": "4FFE4B22-C96A-43D0-B993-F51EDD9C5E0E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.25:*:*:*:*:*:*:*", "matchCriteriaId": "F571CC8B-B212-4553-B463-1DB01D616E8A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.26:*:*:*:*:*:*:*", "matchCriteriaId": "84E3E151-D437-48ED-A529-731EEFF88567", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.27:*:*:*:*:*:*:*", "matchCriteriaId": "E9E3EA3C-CCA5-4433-86E0-3D02C4757A0A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.28:*:*:*:*:*:*:*", "matchCriteriaId": "F7AC4F7D-9FA6-4CF1-B2E9-70BF7D4D177C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.29:*:*:*:*:*:*:*", "matchCriteriaId": "3CE3A80D-9648-43CC-8F99-D741ED6552BF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.2.30:*:*:*:*:*:*:*", "matchCriteriaId": "C8A98C03-A465-41B4-A551-A26FEC7FFD94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:*:*:*:*:*:*:*", "matchCriteriaId": "AFB76697-1C2F-48C0-9B14-517EC053D4B3", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc1:*:*:*:*:*:*", "matchCriteriaId": "BED88DFD-1DC5-4505-A441-44ECDEF0252D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc2:*:*:*:*:*:*", "matchCriteriaId": "DBFD2ACD-728A-4082-BB6A-A1EF6E58E47D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc3:*:*:*:*:*:*", "matchCriteriaId": "C31B0E51-F62D-4053-B04F-FC4D5BC373D2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc4:*:*:*:*:*:*", "matchCriteriaId": "A914303E-1CB6-4AAD-9F5F-DE5433C4E814", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc5:*:*:*:*:*:*", "matchCriteriaId": "203BBA69-90B2-4C5E-8023-C14180742421", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc6:*:*:*:*:*:*", "matchCriteriaId": "0DBFAB53-B889-4028-AC0E-7E165B152A18", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3:rc7:*:*:*:*:*:*", "matchCriteriaId": "FE409AEC-F677-4DEF-8EB7-2C35809043CE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.1:*:*:*:*:*:*:*", "matchCriteriaId": "578EC12B-402F-4AD4-B8F8-C9B2CAB06891", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.2:*:*:*:*:*:*:*", "matchCriteriaId": "877002ED-8097-4BB4-BB88-6FC6306C38B2", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.3:*:*:*:*:*:*:*", "matchCriteriaId": "76294CE3-D72C-41D5-9E0F-B693D0042699", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.4:*:*:*:*:*:*:*", "matchCriteriaId": "916E97D4-1FAB-42F5-826B-653B1C0909A8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.5:*:*:*:*:*:*:*", "matchCriteriaId": "33FD2217-C5D0-48C1-AD74-3527127FEF9C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.6:*:*:*:*:*:*:*", "matchCriteriaId": "2E92971F-B629-4E0A-9A50-8B235F9704B8", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.7:*:*:*:*:*:*:*", "matchCriteriaId": "EDD3A069-3829-4EE2-9D5A-29459F29D4C1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.3.8:*:*:*:*:*:*:*", "matchCriteriaId": "A4A0964C-CEB2-41D7-A69C-1599B05B6171", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:*:*", "matchCriteriaId": "0F960FA6-F904-4A4E-B483-44C70090E9A1", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:*:*:*:*:*:x86:*", "matchCriteriaId": "8C3D9C66-933A-469E-9073-75015A8AD17D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:*:*", "matchCriteriaId": "261C1B41-C9E0-414F-8368-51C0C0B8AD38", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc1:*:*:*:*:x86:*", "matchCriteriaId": "C92F29A0-DEFF-49E4-AE86-5DBDAD51C677", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:*:*", "matchCriteriaId": "5CCA261D-2B97-492F-89A0-5F209A804350", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc2:*:*:*:*:x86:*", "matchCriteriaId": "5690A703-390D-4D8A-9258-2F47116DAB4F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:*:*", "matchCriteriaId": "1B1C0C68-9194-473F-BE5E-EC7F184899FA", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc3:*:*:*:*:x86:*", "matchCriteriaId": "AB1EDDA7-15AF-4B45-A931-DFCBB1EEB701", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:*:*", "matchCriteriaId": "D7A6AC9E-BEA6-44B0-B3B3-F0F94E32424A", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc4:*:*:*:*:x86:*", "matchCriteriaId": "952FE0DC-B2ED-4080-BF29-A2C265E83FEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:*:*", "matchCriteriaId": "16038328-9399-4B85-B777-BA4757D02C9B", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc5:*:*:*:*:x86:*", "matchCriteriaId": "1CE7ABDB-6572-40E8-B952-CBE52C999858", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:*:*", "matchCriteriaId": "16CA2757-FA8D-43D9-96E8-D3C0EB6E1DEF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc6:*:*:*:*:x86:*", "matchCriteriaId": "0F417186-D1ED-4A31-92B2-83DEDA1AF272", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:*:*", "matchCriteriaId": "E8CB5481-5EAE-401E-BD7E-D3095CCA9E94", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4:rc7:*:*:*:*:x86:*", "matchCriteriaId": "3D4FCFAE-918C-4886-9A17-08A5B94D35F4", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:*:*", "matchCriteriaId": "A0F36FAC-141D-476D-84C5-A558C199F904", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.1:*:*:*:*:*:x86:*", "matchCriteriaId": "830D2914-C9FE-406F-AFCE-7A04BB9E2896", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:*:*", "matchCriteriaId": "51D64824-25F6-4761-BD6A-29038A143744", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.2:*:*:*:*:*:x86:*", "matchCriteriaId": "F4B791B5-2EB5-403A-90CC-B219F6277D1F", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:*:*", "matchCriteriaId": "E284C8A1-740F-454D-A774-99CD3A21B594", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.3:*:*:*:*:*:x86:*", "matchCriteriaId": "2BA5F34D-7490-4B2B-A7E6-8450F9C1FC31", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:*:*", "matchCriteriaId": "C70D72AE-0CBF-4324-9935-57E28EC6279C", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.4:*:*:*:*:*:x86:*", "matchCriteriaId": "B803FE64-FC8D-4650-9FB9-FEEED4340416", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:*:*", "matchCriteriaId": "F674B06B-7E86-4E41-9126-8152D0DDABAE", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.5:*:*:*:*:*:x86:*", "matchCriteriaId": "4C560A9A-2388-4980-9E88-118C5EB806B7", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.10:*:*:*:*:*:*:*", "matchCriteriaId": "7DA94F50-2A62-4300-BF4D-A342AAE35629", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.11:*:*:*:*:*:*:*", "matchCriteriaId": "252D937B-50DC-444F-AE73-5FCF6203DF27", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.12:*:*:*:*:*:*:*", "matchCriteriaId": "F6D8EE51-02C1-47BC-A92C-0A8ABEFD28FF", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.13:*:*:*:*:*:*:*", "matchCriteriaId": "7F20A5D7-3B38-4911-861A-04C8310D5916", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}, {"criteria": "cpe:2.3:o:linux:linux_kernel:3.4.14:*:*:*:*:*:*:*", "matchCriteriaId": "D472DE3A-71D8-4F40-9DDE-85929A2B047D", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "Race condition in fs/ext4/extents.c in the Linux kernel before 3.4.16 allows local users to obtain sensitive information from a deleted file by reading an extent that was not properly marked as uninitialized."}, {"lang": "es", "value": "Condici\u00f3n de carrera en fs/ext4/extents.c. En el kernel Linux antes de v3.4.16 permite a usuarios locales obtener informaci\u00f3n sensible de un archivo eliminado mediante la lectura de un 'extent' que no fue correctamente marcado como 'no inicializado' .\r\n"}], "evaluatorComment": null, "id": "CVE-2012-4508", "lastModified": "2023-02-13T04:34:36.667", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "LOCAL", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 1.9, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:L/AC:M/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 3.4, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": null}, "published": "2012-12-21T11:47:36.580", "references": [{"source": "secalert@redhat.com", "tags": null, "url": "http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git%3Ba=commit%3Bh=dee1f973ca341c266229faa5a1a5bb268bed3531"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://lists.fedoraproject.org/pipermail/package-announce/2012-November/091110.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2012-1540.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2013-0496.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2013-1519.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://rhn.redhat.com/errata/RHSA-2013-1783.html"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.kernel.org/pub/linux/kernel/v3.x/ChangeLog-3.4.16"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.openwall.com/lists/oss-security/2012/10/25/1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-1645-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-1899-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "http://www.ubuntu.com/usn/USN-1900-1"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://bugzilla.redhat.com/show_bug.cgi?id=869904"}, {"source": "secalert@redhat.com", "tags": ["Patch"], "url": "https://github.com/torvalds/linux/commit/dee1f973ca341c266229faa5a1a5bb268bed3531"}, {"source": "secalert@redhat.com", "tags": null, "url": "https://www.suse.com/support/update/announcement/2012/suse-su-20121679-1.html"}], "sourceIdentifier": "secalert@redhat.com", "vendorComments": null, "vulnStatus": "Modified", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-362"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/torvalds/linux/commit/dee1f973ca341c266229faa5a1a5bb268bed3531"}, "type": "CWE-362"}
33
Determine whether the {function_name} code is vulnerable or not.
[ "<h1><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO detection configuration');?></h1>", "<?php if (isset($errors)) : ?>\n\t<?php include(erLhcoreClassDesign::designtpl('lhkernel/validation_error.tpl.php'));?>\n<?php endif; ?>", "<?php if (isset($updated) && $updated == 'done') : $msg = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Settings updated'); ?>\n\t<?php include(erLhcoreClassDesign::designtpl('lhkernel/alert_success.tpl.php'));?>\n<?php endif; ?>", "\n<div role=\"tabpanel\" ng-non-bindable>", "\t<!-- Nav tabs -->\n\t<ul class=\"nav nav-tabs\" role=\"tablist\">\n\t\t<li role=\"presentation\" class=\"nav-item\"><a class=\"active nav-link\" href=\"#geoconfiguration\" aria-controls=\"geoconfiguration\" role=\"tab\" data-toggle=\"tab\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO detection configuration');?></a></li>\n\t\t<li role=\"presentation\" class=\"nav-item\"><a class=\"nav-link\" id=\"map-activator\" href=\"#mapoptions\" aria-controls=\"mapoptions\" role=\"tab\" data-toggle=\"tab\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Map location')?></a></li>\n\t</ul>", "\t<!-- Tab panes -->\n\t<div class=\"tab-content\">\n\t\t<div role=\"tabpanel\" class=\"tab-pane active\" id=\"geoconfiguration\">\n\t\t\t<form action=\"\" method=\"post\">", " <?php include(erLhcoreClassDesign::designtpl('lhkernel/csfr_token.tpl.php'));?>", " <label><input type=\"checkbox\" id=\"id_GeoDetectionEnabled\" name=\"GeoDetectionEnabled\" value=\"on\" <?php isset($geo_data['geo_detection_enabled']) && $geo_data['geo_detection_enabled'] == 1 ? print 'checked=\"checked\"' : ''?> /> <?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO Enabled');?></label> <br />\n \n\t\t\t\t<div role=\"tabpanel\" class=\"<?php (!isset($geo_data['geo_detection_enabled']) || $geo_data['geo_detection_enabled'] == 0) ? print ' hide' : '' ?>\" id=\"settings-geo\">", "\t\t\t\t\t<!-- Nav tabs -->\n\t\t\t\t\t<ul class=\"nav nav-tabs mb-2\" role=\"tablist\">\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'freegeoip') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#freegeoip\" aria-controls=\"freegeoip\" role=\"tab\" data-toggle=\"tab\">https://ipstack.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'mod_geoip2') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#mod_geoip2\" aria-controls=\"mod_geoip2\" role=\"tab\" data-toggle=\"tab\">mod_geoip2</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'max_mind') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#maxmind\" aria-controls=\"maxmind\" role=\"tab\" data-toggle=\"tab\">MaxMind</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'php_geoip') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#phpgeoip\" aria-controls=\"phpgeoip\" role=\"tab\" data-toggle=\"tab\">PHP-GeoIP</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipinfodbcom') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#panel3\" aria-controls=\"panel3\" role=\"tab\" data-toggle=\"tab\">http://ipinfodb.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'locatorhq') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#panel4\" aria-controls=\"panel4\" role=\"tab\" data-toggle=\"tab\">http://www.locatorhq.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipapi') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#ipapi\" aria-controls=\"ipapi\" role=\"tab\" data-toggle=\"tab\">https://ip-api.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'abstractapi') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#abstractapi\" aria-controls=\"abstractapi\" role=\"tab\" data-toggle=\"tab\">https://www.abstractapi.com</a></li>\n\t\t\t\t\t</ul>", "\t\t\t\t\t<!-- Tab panes -->\n\t\t\t\t\t<div class=\"tab-content\">\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'freegeoip') ? print 'active' : ''?>\" id=\"freegeoip\">\n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"freegeoip\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'freegeoip') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use this service'); ?></label> \n\t\t\t\t\t\t </div>", " <p>Get API Key from - <a href=\"https://ipstack.com\">https://ipstack.com</a></p>", " <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label>\n <input class=\"form-control\" type=\"text\" name=\"freegeoip_key\" value=\"<?php isset($geo_data['freegeoip_key']) ? print $geo_data['freegeoip_key'] : print '' ?>\">\n </div>", "\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'mod_geoip2') ? print 'active' : ''?>\" id=\"mod_geoip2\">\n\t\t\t\t\t\t <div>\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"mod_geoip2\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'mod_geoip2') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use mod_geoip2'); ?></label> \n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country code server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_COUNTRY_CODE\" value=\"<?php isset($geo_data['mod_geo_ip_country_code']) ? print $geo_data['mod_geo_ip_country_code'] : print 'GEOIP_COUNTRY_CODE' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country name server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_COUNTRY_NAME\" value=\"<?php isset($geo_data['mod_geo_ip_country_name']) ? print $geo_data['mod_geo_ip_country_name'] : print 'GEOIP_COUNTRY_NAME' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','City name server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_CITY\" value=\"<?php isset($geo_data['mod_geo_ip_city_name']) ? print $geo_data['mod_geo_ip_city_name'] : print 'GEOIP_CITY' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Region name server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_REGION\" value=\"<?php isset($geo_data['mod_geo_ip_region_name']) ? print $geo_data['mod_geo_ip_region_name'] : print 'GEOIP_REGION' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\t\t\t \n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Latitude variable'); ?></label>\n\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_LATITUDE\" value=\"<?php isset($geo_data['mod_geo_ip_latitude']) ? print $geo_data['mod_geo_ip_latitude'] : print 'GEOIP_LATITUDE' ?>\"> \n\t\t\t\t\t\t\t </div>\n\t\t\t\t\t\t\t \t\t\n\t\t\t\t\t\t\t <div class=\"form-group\">\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Longitude variable'); ?></label> \n\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_LONGITUDE\" value=\"<?php isset($geo_data['mod_geo_ip_longitude']) ? print $geo_data['mod_geo_ip_longitude'] : print 'GEOIP_LONGITUDE' ?>\"> \n\t\t\t\t\t\t\t </div>\n\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t</div>\t\t\t\t\t\t\n\t\t\t\t\t\t</div>", " <div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipapi') ? print 'active' : ''?>\" id=\"ipapi\">\n\t\t\t\t\t\t <div>\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"ipapi\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipapi') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use http://ip-api.com'); ?></label>", " <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?> (Optional)</label>\n <input class=\"form-control\" type=\"text\" name=\"ipapi_key\" value=\"<?php isset($geo_data['ipapi_key']) ? print $geo_data['ipapi_key'] : print '' ?>\">\n </div>", "\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>", " <div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'abstractapi') ? print 'active' : ''?>\" id=\"abstractapi\">\n\t\t\t\t\t\t <div>\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"abstractapi\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'abstractapi') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use https://www.abstractapi.com/ip-geolocation-api'); ?></label>", " <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label>\n <input class=\"form-control\" type=\"text\" name=\"abstractapi_key\" value=\"<?php isset($geo_data['abstractapi_key']) ? print $geo_data['abstractapi_key'] : print '' ?>\">\n </div>", "\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>", "\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'max_mind') ? print 'active' : ''?>\" id=\"maxmind\">\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"max_mind\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'max_mind') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use MaxMind, does not depend on any third party remote service'); ?></label>", "\t\t\t\t\t\t\t\t<p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','You can download city/country database from.'); ?>&nbsp;<a target=\"_blank\" href=\"http://dev.maxmind.com/geoip/geoip2/geolite2/\">MaxMind</a>\n\t\t\t\t\t\t\t\t</p>", "\t\t\t\t\t\t\t\t<p>\n \t<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','bcmath php extension detected'); ?> - <?php echo extension_loaded ('bcmath' ) ? '<span class=\"badge badge-success\">Yes</span>' : '<span class=\"badge badge-danger\">No</span>'; ?>\n \t</p>", " \t <div class=\"form-group\">", "\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Location of city database'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"CityGeoLocation\" value=\"<?php isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? print htmlspecialchars($geo_data['max_mind_city_location']) : print 'var/external/geoip/GeoLite2-City.mmdb' ?>\" />", " </div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t\t\t\t\t\t\t<label><input type=\"radio\" name=\"MaxMindDetectionType\" value=\"country\" <?php (isset($geo_data['max_mind_detection_type']) && $geo_data['max_mind_detection_type'] == 'country') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','User country based detection, faster')?></label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t<?php if (file_exists(\"var/external/geoip/GeoLite2-Country.mmdb\")) : ?> <span class=\"badge badge-success\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File exists'); ?>\">var/external/geoip/GeoLite2-Country.mmdb</span> <?php else : ?><span class=\"badge badge-danger\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File does not exists'); ?>\">var/external/geoip/GeoLite2-Country.mmdb</span><?php endif;?>\n\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t\t\t\t\t\t\t<label><input type=\"radio\" name=\"MaxMindDetectionType\" value=\"city\" <?php (isset($geo_data['max_mind_detection_type']) && $geo_data['max_mind_detection_type'] == 'city') ? print 'checked=\"checked\"' : '' ?> <?php if (!file_exists(isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? $geo_data['max_mind_city_location'] : 'var/external/geoip/GeoLite2-City.mmdb')) : ?> disabled <?php endif;?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','User city based detection, slower')?></label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t<?php if (file_exists(isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? $geo_data['max_mind_city_location'] : 'var/external/geoip/GeoLite2-City.mmdb')) : ?> <span class=\"badge badge-success\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File exists');?>\"><?php isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? print htmlspecialchars($geo_data['max_mind_city_location']) : print 'var/external/geoip/GeoLite2-City.mmdb' ?></span> <?php else : ?><span class=\"badge badge-danger\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File does not exists')?>\"><?php isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? print htmlspecialchars($geo_data['max_mind_city_location']) : print 'var/external/geoip/GeoLite2-City.mmdb' ?></span><?php endif;?>\n\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\tThis product includes GeoLite2 data created by MaxMind, available from <a href=\"http://www.maxmind.com\">http://www.maxmind.com</a>.\n\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'php_geoip') ? print 'active' : ''?>\" id=\"phpgeoip\">\n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"php_geoip\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'php_geoip') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use PHP-GeoIP module'); ?></label>\n\t\t\t\t\t\t\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Support for PHP-GeoIP detected'); ?> - <?php echo function_exists('geoip_country_code_by_name') ? '<span class=\"badge badge-success\">Yes</span>' : '<span class=\"badge badge-danger\">No</span>'; ?></p>\n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipinfodbcom') ? print 'active' : ''?>\" id=\"panel3\">\n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Requests will be comming from');?> - <?php echo erLhcoreClassIPDetect::getServerAddress(); ?></p>", "\t\t\t\t\t\t\t\t <label class=\"inline\"><input type=\"radio\" name=\"UseGeoIP\" value=\"ipinfodbcom\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipinfodbcom') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use this service'); ?></label> \n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ipinfodbAPIKey\" value=\"<?php isset($geo_data['ipinfodbcom_api_key']) ? print htmlspecialchars($geo_data['ipinfodbcom_api_key']) : print '' ?>\">\n\t\t\t\t\t\t\t\t </div> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'locatorhq') ? print 'active' : ''?>\" id=\"panel4\">\n\t\t\t\t\t\t <div class=\"form-group\">", "\t\t\t\t\t\t\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Requests will be comming from');?> - <?php echo erLhcoreClassIPDetect::getServerAddress(); ?></p>", "\t\t\t\t\t\t\t\t<label class=\"inline\"><input type=\"radio\" name=\"UseGeoIP\" value=\"locatorhq\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'locatorhq') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use this service'); ?></label> \n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"locatorhqAPIKey\" value=\"<?php isset($geo_data['locatorhq_api_key']) ? print htmlspecialchars($geo_data['locatorhq_api_key']) : print '' ?>\"> \n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Username'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"locatorhqUsername\" value=\"<?php isset($geo_data['locatorhqusername']) ? print htmlspecialchars($geo_data['locatorhqusername']) : print '' ?>\"> \n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','IP, if your site remote IP is different from detected one, please provide correct remote IP address'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"locatorhqIP\" value=\"<?php isset($geo_data['locatorhqip']) ? print htmlspecialchars($geo_data['locatorhqip']) : print erLhcoreClassIPDetect::getServerAddress() ?>\"> \n </div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<input type=\"submit\" class=\"btn btn-secondary\" name=\"StoreGeoIPConfiguration\" value=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Save'); ?>\" />", "\t\t\t</form>\n\t\t</div>\n\t\t\n\t\t<div role=\"tabpanel\" class=\"tab-pane\" id=\"mapoptions\">\n\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Drag a marker where you want to have map centered by default. Zoom is also saved.')?></p>", "\t\t <div class=\"form-group\">\n\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Google Maps API key, saved automatically. After pasting the key, refresh the page.'); ?></label> \n\t\t <input class=\"form-control\" type=\"text\" id=\"id_GMapsAPIKey\" value=\"<?php isset($geo_location_data['gmaps_api_key']) ? print $geo_location_data['gmaps_api_key'] : print '' ?>\"> \n\t\t </div>", " \t\t<div id=\"map_canvas\" style=\"height:600px;width:100%;\"></div>\t\t\t\n\t\t</div>\n\t\t\n\t</div>\n</div>", "<script>\nvar marker = null;\nvar map = null;", "function loadMapLocationChoosing(){", "\t$('#map-activator').click(function(){\n\t\tsetTimeout(function(){\n\t\t\tgoogle.maps.event.trigger(map, 'resize');\n\t\t\tmap.setCenter(marker.getPosition());\n\t\t},500);\n\t});", "\tvar mapOptions = {\n\t\t zoom: <?php echo $geo_location_data['zoom'] ?>,\n\t\t mapTypeId: google.maps.MapTypeId.ROADMAP,\n\t\t disableDefaultUI: true,\n\t options: {\n\t zoomControl: true,\n\t scrollwheel: true,\n\t streetViewControl: true\n\t },\n\t\t center: new google.maps.LatLng(<?php echo $geo_location_data['lat'] ?>,<?php echo $geo_location_data['lng']?>)\n\t\t };", "\tmap = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);", "\tvar marker = new google.maps.Marker(\n\t{\n\t map:map,\n\t draggable:true,\n\t animation: google.maps.Animation.DROP,\n\t position: new google.maps.LatLng(<?php echo $geo_location_data['lat'] ?>,<?php echo $geo_location_data['lng']?>)\n\t});", "\tgoogle.maps.event.addListener(map, 'zoom_changed', function() {\n\t\t var pos = marker.getPosition();\n\t\t $.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),zoom:map.getZoom(),store_map:1,csfr_token:confLH.csrf_token,lat:pos.lat().toFixed(4),lng:pos.lng().toFixed(4)}, function(data){", "\t });\n\t});", "\tgoogle.maps.event.addListener(marker, 'dragend', function(evt) {\n\t $.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),zoom:map.getZoom(),store_map:1,csfr_token:confLH.csrf_token,lat:evt.latLng.lat().toFixed(4),lng:evt.latLng.lng().toFixed(4)}, function(data){", " \t});\n\t});", "\t$('#id_GMapsAPIKey').keyup(function() {", "\t\tvar pos = marker.getPosition();\n\t\t\n\t\tif (marker != null && map != null && typeof pos != 'undefined') { \t\t\n \t\t$.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),zoom:map.getZoom(),store_map:1,csfr_token:confLH.csrf_token,lat:pos.lat().toFixed(4),lng:pos.lng().toFixed(4)}, function(data){\n \t\t});\n\t\t} else {\n\t\t\tvar pos = marker.getPosition();\n \t\t$.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),store_map:1,csfr_token:confLH.csrf_token}, function(data){\n \t\t});\n\t\t}\n\t});\n};", "$('#id_GeoDetectionEnabled').change(function(){\n if ($(this).is(':checked')){\n $('#settings-geo').removeClass('hide');\n } else {\n $('#settings-geo').addClass('hide');\n }; \n});\n</script>", "<script async defer src=\"https://maps.googleapis.com/maps/api/js?<?php if (erConfigClassLhConfig::getInstance()->getSetting( 'site', 'maps_api_key', false)) {echo 'key=' , erConfigClassLhConfig::getInstance()->getSetting( 'site', 'maps_api_key', false) , '&';} elseif (isset($geo_location_data['gmaps_api_key'])) {echo 'key=' ,$geo_location_data['gmaps_api_key'], '&';}?>callback=loadMapLocationChoosing\"></script>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<h1><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO detection configuration');?></h1>", "<?php if (isset($errors)) : ?>\n\t<?php include(erLhcoreClassDesign::designtpl('lhkernel/validation_error.tpl.php'));?>\n<?php endif; ?>", "<?php if (isset($updated) && $updated == 'done') : $msg = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Settings updated'); ?>\n\t<?php include(erLhcoreClassDesign::designtpl('lhkernel/alert_success.tpl.php'));?>\n<?php endif; ?>", "\n<div role=\"tabpanel\" ng-non-bindable>", "\t<!-- Nav tabs -->\n\t<ul class=\"nav nav-tabs\" role=\"tablist\">\n\t\t<li role=\"presentation\" class=\"nav-item\"><a class=\"active nav-link\" href=\"#geoconfiguration\" aria-controls=\"geoconfiguration\" role=\"tab\" data-toggle=\"tab\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO detection configuration');?></a></li>\n\t\t<li role=\"presentation\" class=\"nav-item\"><a class=\"nav-link\" id=\"map-activator\" href=\"#mapoptions\" aria-controls=\"mapoptions\" role=\"tab\" data-toggle=\"tab\"><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Map location')?></a></li>\n\t</ul>", "\t<!-- Tab panes -->\n\t<div class=\"tab-content\">\n\t\t<div role=\"tabpanel\" class=\"tab-pane active\" id=\"geoconfiguration\">\n\t\t\t<form action=\"\" method=\"post\">", " <?php include(erLhcoreClassDesign::designtpl('lhkernel/csfr_token.tpl.php'));?>", " <label><input type=\"checkbox\" id=\"id_GeoDetectionEnabled\" name=\"GeoDetectionEnabled\" value=\"on\" <?php isset($geo_data['geo_detection_enabled']) && $geo_data['geo_detection_enabled'] == 1 ? print 'checked=\"checked\"' : ''?> /> <?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO Enabled');?></label> <br />\n \n\t\t\t\t<div role=\"tabpanel\" class=\"<?php (!isset($geo_data['geo_detection_enabled']) || $geo_data['geo_detection_enabled'] == 0) ? print ' hide' : '' ?>\" id=\"settings-geo\">", "\t\t\t\t\t<!-- Nav tabs -->\n\t\t\t\t\t<ul class=\"nav nav-tabs mb-2\" role=\"tablist\">\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'freegeoip') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#freegeoip\" aria-controls=\"freegeoip\" role=\"tab\" data-toggle=\"tab\">https://ipstack.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'mod_geoip2') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#mod_geoip2\" aria-controls=\"mod_geoip2\" role=\"tab\" data-toggle=\"tab\">mod_geoip2</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'max_mind') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#maxmind\" aria-controls=\"maxmind\" role=\"tab\" data-toggle=\"tab\">MaxMind</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'php_geoip') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#phpgeoip\" aria-controls=\"phpgeoip\" role=\"tab\" data-toggle=\"tab\">PHP-GeoIP</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipinfodbcom') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#panel3\" aria-controls=\"panel3\" role=\"tab\" data-toggle=\"tab\">http://ipinfodb.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'locatorhq') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#panel4\" aria-controls=\"panel4\" role=\"tab\" data-toggle=\"tab\">http://www.locatorhq.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipapi') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#ipapi\" aria-controls=\"ipapi\" role=\"tab\" data-toggle=\"tab\">https://ip-api.com</a></li>\n\t\t\t\t\t\t<li role=\"presentation\" class=\"nav-item <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'abstractapi') ? print 'active' : ''?>\"><a class=\"nav-link\" href=\"#abstractapi\" aria-controls=\"abstractapi\" role=\"tab\" data-toggle=\"tab\">https://www.abstractapi.com</a></li>\n\t\t\t\t\t</ul>", "\t\t\t\t\t<!-- Tab panes -->\n\t\t\t\t\t<div class=\"tab-content\">\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'freegeoip') ? print 'active' : ''?>\" id=\"freegeoip\">\n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"freegeoip\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'freegeoip') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use this service'); ?></label> \n\t\t\t\t\t\t </div>", " <p>Get API Key from - <a href=\"https://ipstack.com\">https://ipstack.com</a></p>", " <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label>\n <input class=\"form-control\" type=\"text\" name=\"freegeoip_key\" value=\"<?php isset($geo_data['freegeoip_key']) ? print $geo_data['freegeoip_key'] : print '' ?>\">\n </div>", "\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'mod_geoip2') ? print 'active' : ''?>\" id=\"mod_geoip2\">\n\t\t\t\t\t\t <div>\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"mod_geoip2\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'mod_geoip2') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use mod_geoip2'); ?></label> \n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country code server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_COUNTRY_CODE\" value=\"<?php isset($geo_data['mod_geo_ip_country_code']) ? print $geo_data['mod_geo_ip_country_code'] : print 'GEOIP_COUNTRY_CODE' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country name server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_COUNTRY_NAME\" value=\"<?php isset($geo_data['mod_geo_ip_country_name']) ? print $geo_data['mod_geo_ip_country_name'] : print 'GEOIP_COUNTRY_NAME' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','City name server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_CITY\" value=\"<?php isset($geo_data['mod_geo_ip_city_name']) ? print $geo_data['mod_geo_ip_city_name'] : print 'GEOIP_CITY' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Region name server variable'); ?></label> \n\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_REGION\" value=\"<?php isset($geo_data['mod_geo_ip_region_name']) ? print $geo_data['mod_geo_ip_region_name'] : print 'GEOIP_REGION' ?>\"> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t \n\t\t\t\t\t\t <div class=\"form-group\">\t\t\t \n\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Latitude variable'); ?></label>\n\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_LATITUDE\" value=\"<?php isset($geo_data['mod_geo_ip_latitude']) ? print $geo_data['mod_geo_ip_latitude'] : print 'GEOIP_LATITUDE' ?>\"> \n\t\t\t\t\t\t\t </div>\n\t\t\t\t\t\t\t \t\t\n\t\t\t\t\t\t\t <div class=\"form-group\">\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Longitude variable'); ?></label> \n\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ServerVariableGEOIP_LONGITUDE\" value=\"<?php isset($geo_data['mod_geo_ip_longitude']) ? print $geo_data['mod_geo_ip_longitude'] : print 'GEOIP_LONGITUDE' ?>\"> \n\t\t\t\t\t\t\t </div>\n\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t</div>\t\t\t\t\t\t\n\t\t\t\t\t\t</div>", " <div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipapi') ? print 'active' : ''?>\" id=\"ipapi\">\n\t\t\t\t\t\t <div>\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"ipapi\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipapi') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use http://ip-api.com'); ?></label>", " <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?> (Optional)</label>\n <input class=\"form-control\" type=\"text\" name=\"ipapi_key\" value=\"<?php isset($geo_data['ipapi_key']) ? print $geo_data['ipapi_key'] : print '' ?>\">\n </div>", "\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>", " <div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'abstractapi') ? print 'active' : ''?>\" id=\"abstractapi\">\n\t\t\t\t\t\t <div>\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"abstractapi\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'abstractapi') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use https://www.abstractapi.com/ip-geolocation-api'); ?></label>", " <div class=\"form-group\">\n <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label>\n <input class=\"form-control\" type=\"text\" name=\"abstractapi_key\" value=\"<?php isset($geo_data['abstractapi_key']) ? print $geo_data['abstractapi_key'] : print '' ?>\">\n </div>", "\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>", "\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'max_mind') ? print 'active' : ''?>\" id=\"maxmind\">\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"max_mind\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'max_mind') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use MaxMind, does not depend on any third party remote service'); ?></label>", "\t\t\t\t\t\t\t\t<p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','You can download city/country database from.'); ?>&nbsp;<a target=\"_blank\" href=\"http://dev.maxmind.com/geoip/geoip2/geolite2/\">MaxMind</a>\n\t\t\t\t\t\t\t\t</p>", "\t\t\t\t\t\t\t\t<p>\n \t<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','bcmath php extension detected'); ?> - <?php echo extension_loaded ('bcmath' ) ? '<span class=\"badge badge-success\">Yes</span>' : '<span class=\"badge badge-danger\">No</span>'; ?>\n \t</p>", " \t <div class=\"form-group\">", "\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Location of city database. Make sure you uploaded file in this location.'); ?></label>\n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" readonly value=\"<?php isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? print htmlspecialchars($geo_data['max_mind_city_location']) : print 'var/external/geoip/GeoLite2-City.mmdb' ?>\" />", " </div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t\t\t\t\t\t\t<label><input type=\"radio\" name=\"MaxMindDetectionType\" value=\"country\" <?php (isset($geo_data['max_mind_detection_type']) && $geo_data['max_mind_detection_type'] == 'country') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','User country based detection, faster')?></label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t<?php if (file_exists(\"var/external/geoip/GeoLite2-Country.mmdb\")) : ?> <span class=\"badge badge-success\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File exists'); ?>\">var/external/geoip/GeoLite2-Country.mmdb</span> <?php else : ?><span class=\"badge badge-danger\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File does not exists'); ?>\">var/external/geoip/GeoLite2-Country.mmdb</span><?php endif;?>\n\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\"row\">\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t\t\t\t\t\t\t<label><input type=\"radio\" name=\"MaxMindDetectionType\" value=\"city\" <?php (isset($geo_data['max_mind_detection_type']) && $geo_data['max_mind_detection_type'] == 'city') ? print 'checked=\"checked\"' : '' ?> <?php if (!file_exists(isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? $geo_data['max_mind_city_location'] : 'var/external/geoip/GeoLite2-City.mmdb')) : ?> disabled <?php endif;?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','User city based detection, slower')?></label>\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t<div class=\"col-6\">\n\t\t\t\t<?php if (file_exists(isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? $geo_data['max_mind_city_location'] : 'var/external/geoip/GeoLite2-City.mmdb')) : ?> <span class=\"badge badge-success\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File exists');?>\"><?php isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? print htmlspecialchars($geo_data['max_mind_city_location']) : print 'var/external/geoip/GeoLite2-City.mmdb' ?></span> <?php else : ?><span class=\"badge badge-danger\" title=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','File does not exists')?>\"><?php isset($geo_data['max_mind_city_location']) && ($geo_data['max_mind_city_location'] != '') ? print htmlspecialchars($geo_data['max_mind_city_location']) : print 'var/external/geoip/GeoLite2-City.mmdb' ?></span><?php endif;?>\n\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<p>\n\t\t\t\t\t\t\t\t\tThis product includes GeoLite2 data created by MaxMind, available from <a href=\"http://www.maxmind.com\">http://www.maxmind.com</a>.\n\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'php_geoip') ? print 'active' : ''?>\" id=\"phpgeoip\">\n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <label><input type=\"radio\" name=\"UseGeoIP\" value=\"php_geoip\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'php_geoip') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use PHP-GeoIP module'); ?></label>\n\t\t\t\t\t\t\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Support for PHP-GeoIP detected'); ?> - <?php echo function_exists('geoip_country_code_by_name') ? '<span class=\"badge badge-success\">Yes</span>' : '<span class=\"badge badge-danger\">No</span>'; ?></p>\n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipinfodbcom') ? print 'active' : ''?>\" id=\"panel3\">\n\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Requests will be comming from');?> - <?php echo erLhcoreClassIPDetect::getServerAddress(); ?></p>", "\t\t\t\t\t\t\t\t <label class=\"inline\"><input type=\"radio\" name=\"UseGeoIP\" value=\"ipinfodbcom\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'ipinfodbcom') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use this service'); ?></label> \n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t\t <div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"ipinfodbAPIKey\" value=\"<?php isset($geo_data['ipinfodbcom_api_key']) ? print htmlspecialchars($geo_data['ipinfodbcom_api_key']) : print '' ?>\">\n\t\t\t\t\t\t\t\t </div> \n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<div role=\"tabpanel\" class=\"tab-pane <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'locatorhq') ? print 'active' : ''?>\" id=\"panel4\">\n\t\t\t\t\t\t <div class=\"form-group\">", "\t\t\t\t\t\t\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Requests will be comming from');?> - <?php echo erLhcoreClassIPDetect::getServerAddress(); ?></p>", "\t\t\t\t\t\t\t\t<label class=\"inline\"><input type=\"radio\" name=\"UseGeoIP\" value=\"locatorhq\" <?php isset($geo_data['geo_detection_enabled']) && ($geo_data['geo_service_identifier'] == 'locatorhq') ? print 'checked=\"checked\"' : '' ?> /><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Use this service'); ?></label> \n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','API Key'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"locatorhqAPIKey\" value=\"<?php isset($geo_data['locatorhq_api_key']) ? print htmlspecialchars($geo_data['locatorhq_api_key']) : print '' ?>\"> \n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Username'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"locatorhqUsername\" value=\"<?php isset($geo_data['locatorhqusername']) ? print htmlspecialchars($geo_data['locatorhqusername']) : print '' ?>\"> \n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','IP, if your site remote IP is different from detected one, please provide correct remote IP address'); ?></label> \n\t\t\t\t\t\t\t\t <input class=\"form-control\" type=\"text\" name=\"locatorhqIP\" value=\"<?php isset($geo_data['locatorhqip']) ? print htmlspecialchars($geo_data['locatorhqip']) : print erLhcoreClassIPDetect::getServerAddress() ?>\"> \n </div>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t </div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<input type=\"submit\" class=\"btn btn-secondary\" name=\"StoreGeoIPConfiguration\" value=\"<?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Save'); ?>\" />", "\t\t\t</form>\n\t\t</div>\n\t\t\n\t\t<div role=\"tabpanel\" class=\"tab-pane\" id=\"mapoptions\">\n\t\t <p><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Drag a marker where you want to have map centered by default. Zoom is also saved.')?></p>", "\t\t <div class=\"form-group\">\n\t\t <label><?php echo erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Google Maps API key, saved automatically. After pasting the key, refresh the page.'); ?></label> \n\t\t <input class=\"form-control\" type=\"text\" id=\"id_GMapsAPIKey\" value=\"<?php isset($geo_location_data['gmaps_api_key']) ? print $geo_location_data['gmaps_api_key'] : print '' ?>\"> \n\t\t </div>", " \t\t<div id=\"map_canvas\" style=\"height:600px;width:100%;\"></div>\t\t\t\n\t\t</div>\n\t\t\n\t</div>\n</div>", "<script>\nvar marker = null;\nvar map = null;", "function loadMapLocationChoosing(){", "\t$('#map-activator').click(function(){\n\t\tsetTimeout(function(){\n\t\t\tgoogle.maps.event.trigger(map, 'resize');\n\t\t\tmap.setCenter(marker.getPosition());\n\t\t},500);\n\t});", "\tvar mapOptions = {\n\t\t zoom: <?php echo $geo_location_data['zoom'] ?>,\n\t\t mapTypeId: google.maps.MapTypeId.ROADMAP,\n\t\t disableDefaultUI: true,\n\t options: {\n\t zoomControl: true,\n\t scrollwheel: true,\n\t streetViewControl: true\n\t },\n\t\t center: new google.maps.LatLng(<?php echo $geo_location_data['lat'] ?>,<?php echo $geo_location_data['lng']?>)\n\t\t };", "\tmap = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);", "\tvar marker = new google.maps.Marker(\n\t{\n\t map:map,\n\t draggable:true,\n\t animation: google.maps.Animation.DROP,\n\t position: new google.maps.LatLng(<?php echo $geo_location_data['lat'] ?>,<?php echo $geo_location_data['lng']?>)\n\t});", "\tgoogle.maps.event.addListener(map, 'zoom_changed', function() {\n\t\t var pos = marker.getPosition();\n\t\t $.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),zoom:map.getZoom(),store_map:1,csfr_token:confLH.csrf_token,lat:pos.lat().toFixed(4),lng:pos.lng().toFixed(4)}, function(data){", "\t });\n\t});", "\tgoogle.maps.event.addListener(marker, 'dragend', function(evt) {\n\t $.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),zoom:map.getZoom(),store_map:1,csfr_token:confLH.csrf_token,lat:evt.latLng.lat().toFixed(4),lng:evt.latLng.lng().toFixed(4)}, function(data){", " \t});\n\t});", "\t$('#id_GMapsAPIKey').keyup(function() {", "\t\tvar pos = marker.getPosition();\n\t\t\n\t\tif (marker != null && map != null && typeof pos != 'undefined') { \t\t\n \t\t$.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),zoom:map.getZoom(),store_map:1,csfr_token:confLH.csrf_token,lat:pos.lat().toFixed(4),lng:pos.lng().toFixed(4)}, function(data){\n \t\t});\n\t\t} else {\n\t\t\tvar pos = marker.getPosition();\n \t\t$.postJSON('<?php echo erLhcoreClassDesign::baseurl('chat/geoconfiguration')?>/',{gmaps_api_key:$('#id_GMapsAPIKey').val(),store_map:1,csfr_token:confLH.csrf_token}, function(data){\n \t\t});\n\t\t}\n\t});\n};", "$('#id_GeoDetectionEnabled').change(function(){\n if ($(this).is(':checked')){\n $('#settings-geo').removeClass('hide');\n } else {\n $('#settings-geo').addClass('hide');\n }; \n});\n</script>", "<script async defer src=\"https://maps.googleapis.com/maps/api/js?<?php if (erConfigClassLhConfig::getInstance()->getSetting( 'site', 'maps_api_key', false)) {echo 'key=' , erConfigClassLhConfig::getInstance()->getSetting( 'site', 'maps_api_key', false) , '&';} elseif (isset($geo_location_data['gmaps_api_key'])) {echo 'key=' ,$geo_location_data['gmaps_api_key'], '&';}?>callback=loadMapLocationChoosing\"></script>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved.\n * @license http://ez.no/licenses/new_bsd New BSD License\n * @version 1.8\n * @filesource\n * @package Base\n */", "/**\n * Provides a selection of static independent methods to provide functionality\n * for file and file system handling.\n *\n * This example shows how to use the findRecursive method:\n * <code>\n * <?php\n * // lists all the files under /etc (including subdirectories) that end in\n * // .conf\n * $confFiles = ezcBaseFile::findRecursive( \"/etc\", array( '@\\.conf$@' ) );\n *\n * // lists all autoload files in the components source tree and excludes the\n * // ones in the autoload subdirectory. Statistics are returned in the $stats\n * // variable which is passed by reference.\n * $files = ezcBaseFile::findRecursive(\n * \"/dat/dev/ezcomponents\",\n * array( '@src/.*_autoload.php$@' ),\n * array( '@/autoload/@' ),\n * $stats\n * );\n *\n * // lists all binaries in /bin except the ones starting with a \"g\"\n * $data = ezcBaseFile::findRecursive( \"/bin\", array(), array( '@^/bin/g@' ) );\n * ?>\n * </code>\n *\n * @package Base\n * @version 1.8\n * @mainclass\n */\nclass ezcBaseFile\n{\n /**\n * This is the callback used by findRecursive to collect data.\n *\n * This callback method works together with walkRecursive() and is called\n * for every file/and or directory. The $context is a callback specific\n * container in which data can be stored and shared between the different\n * calls to the callback function. The walkRecursive() function also passes\n * in the full absolute directory in $sourceDir, the filename in $fileName\n * and file information (such as size, modes, types) as an array as\n * returned by PHP's stat() in the $fileInfo parameter.\n *\n * @param ezcBaseFileFindContext $context\n * @param string $sourceDir\n * @param string $fileName\n * @param array(stat) $fileInfo\n */\n static protected function findRecursiveCallback( ezcBaseFileFindContext $context, $sourceDir, $fileName, $fileInfo )\n {\n // ignore if we have a directory\n if ( $fileInfo['mode'] & 0x4000 )\n {\n return;\n }", " // update the statistics\n $context->elements[] = $sourceDir . DIRECTORY_SEPARATOR . $fileName;\n $context->count++;\n $context->size += $fileInfo['size'];\n }", " /**\n * Walks files and directories recursively on a file system\n *\n * This method walks over a directory and calls a callback from every file\n * and directory it finds. You can use $includeFilters to include only\n * specific files, and $excludeFilters to exclude certain files from being\n * returned. The function will always go into subdirectories even if the\n * entry would not have passed the filters.\n *\n * The callback is passed in the $callback parameter, and the\n * $callbackContext will be send to the callback function/method as\n * parameter so that you can store data in there that persists with all the\n * calls and recursive calls to this method. It's up to the callback method\n * to do something useful with this. The callback function's parameters are\n * in order:\n *\n * <ul>\n * <li>ezcBaseFileFindContext $context</li>\n * <li>string $sourceDir</li>\n * <li>string $fileName</li>\n * <li>array(stat) $fileInfo</li>\n * </ul>\n *\n * See {@see findRecursiveCallback()} for an example of a callback function.\n *\n * Filters are regular expressions and are therefore required to have\n * starting and ending delimiters. The Perl Compatible syntax is used as\n * regular expression language.\n *\n * @param string $sourceDir\n * @param array(string) $includeFilters\n * @param array(string) $excludeFilters\n * @param callback $callback\n * @param mixed $callbackContext\n *\n * @throws ezcBaseFileNotFoundException if the $sourceDir directory is not\n * a directory or does not exist.\n * @throws ezcBaseFilePermissionException if the $sourceDir directory could\n * not be opened for reading.\n * @return array\n */", " static public function walkRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), $callback, &$callbackContext )", " {\n if ( !is_dir( $sourceDir ) )\n {\n throw new ezcBaseFileNotFoundException( $sourceDir, 'directory' );\n }\n $elements = array();\n $d = @dir( $sourceDir );\n if ( !$d )\n {\n throw new ezcBaseFilePermissionException( $sourceDir, ezcBaseFileException::READ );\n }", " while ( ( $entry = $d->read() ) !== false )\n {\n if ( $entry == '.' || $entry == '..' )\n {\n continue;\n }", " $fileInfo = @stat( $sourceDir . DIRECTORY_SEPARATOR . $entry );\n if ( !$fileInfo )\n {\n $fileInfo = array( 'size' => 0, 'mode' => 0 );\n }", " if ( $fileInfo['mode'] & 0x4000 )\n {\n // We need to ignore the Permission exceptions here as it can\n // be normal that a directory can not be accessed. We only need\n // the exception if the top directory could not be read.\n try\n {\n call_user_func_array( $callback, array( $callbackContext, $sourceDir, $entry, $fileInfo ) );\n $subList = self::walkRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry, $includeFilters, $excludeFilters, $callback, $callbackContext );\n $elements = array_merge( $elements, $subList );\n }\n catch ( ezcBaseFilePermissionException $e )\n {\n }\n }\n else\n {\n // By default a file is included in the return list\n $ok = true;\n // Iterate over the $includeFilters and prohibit the file from\n // being returned when atleast one of them does not match\n foreach ( $includeFilters as $filter )\n {\n if ( !preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) )\n {\n $ok = false;\n break;\n }\n }\n // Iterate over the $excludeFilters and prohibit the file from\n // being returns when atleast one of them matches\n foreach ( $excludeFilters as $filter )\n {\n if ( preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) )\n {\n $ok = false;\n break;\n }\n }", " // If everything's allright, call the callback and add the\n // entry to the elements array\n if ( $ok )\n {\n call_user_func( $callback, $callbackContext, $sourceDir, $entry, $fileInfo );\n $elements[] = $sourceDir . DIRECTORY_SEPARATOR . $entry;\n }\n }\n }\n sort( $elements );\n return $elements;\n }", " /**\n * Finds files recursively on a file system\n *\n * With this method you can scan the file system for files. You can use\n * $includeFilters to include only specific files, and $excludeFilters to\n * exclude certain files from being returned. The function will always go\n * into subdirectories even if the entry would not have passed the filters.\n * It uses the {@see walkRecursive()} method to do the actually recursion.\n *\n * Filters are regular expressions and are therefore required to have\n * starting and ending delimiters. The Perl Compatible syntax is used as\n * regular expression language.\n *\n * If you pass an empty array to the $statistics argument, the function\n * will in details about the number of files found into the 'count' array\n * element, and the total filesize in the 'size' array element. Because this\n * argument is passed by reference, you *have* to pass a variable and you\n * can not pass a constant value such as \"array()\".\n *\n * @param string $sourceDir\n * @param array(string) $includeFilters\n * @param array(string) $excludeFilters\n * @param array() $statistics\n *\n * @throws ezcBaseFileNotFoundException if the $sourceDir directory is not\n * a directory or does not exist.\n * @throws ezcBaseFilePermissionException if the $sourceDir directory could\n * not be opened for reading.\n * @return array\n */\n static public function findRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), &$statistics = null )\n {\n // init statistics array\n if ( !is_array( $statistics ) || !array_key_exists( 'size', $statistics ) || !array_key_exists( 'count', $statistics ) )\n {\n $statistics['size'] = 0;\n $statistics['count'] = 0;\n }", " // create the context, and then start walking over the array\n $context = new ezcBaseFileFindContext;\n self::walkRecursive( $sourceDir, $includeFilters, $excludeFilters, array( 'ezcBaseFile', 'findRecursiveCallback' ), $context );", " // collect the statistics\n $statistics['size'] = $context->size;\n $statistics['count'] = $context->count;", " // return the found and pattern-matched files\n sort( $context->elements );\n return $context->elements;\n }", "\n /**\n * Removes files and directories recursively from a file system\n *\n * This method recursively removes the $directory and all its contents.\n * You should be <b>extremely</b> careful with this method as it has the\n * potential to erase everything that the current user has access to.\n *\n * @param string $directory\n */\n static public function removeRecursive( $directory )\n {\n $sourceDir = realpath( $directory );\n if ( !$sourceDir )\n {\n throw new ezcBaseFileNotFoundException( $directory, 'directory' );\n }\n $d = @dir( $sourceDir );\n if ( !$d )\n {\n throw new ezcBaseFilePermissionException( $directory, ezcBaseFileException::READ );\n }\n // check if we can remove the dir\n $parentDir = realpath( $directory . DIRECTORY_SEPARATOR . '..' );\n if ( !is_writable( $parentDir ) )\n {\n throw new ezcBaseFilePermissionException( $parentDir, ezcBaseFileException::WRITE );\n }\n // loop over contents\n while ( ( $entry = $d->read() ) !== false )\n {\n if ( $entry == '.' || $entry == '..' )\n {\n continue;\n }", " if ( is_dir( $sourceDir . DIRECTORY_SEPARATOR . $entry ) )\n {\n self::removeRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry );\n }\n else\n {\n if ( @unlink( $sourceDir . DIRECTORY_SEPARATOR . $entry ) === false )\n {\n throw new ezcBaseFilePermissionException( $directory . DIRECTORY_SEPARATOR . $entry, ezcBaseFileException::REMOVE );\n }\n }\n }\n $d->close();\n rmdir( $sourceDir );\n }", " /**\n * Recursively copy a file or directory.\n *\n * Recursively copy a file or directory in $source to the given\n * destination. If a depth is given, the operation will stop, if the given\n * recursion depth is reached. A depth of -1 means no limit, while a depth\n * of 0 means, that only the current file or directory will be copied,\n * without any recursion.\n *\n * You may optionally define modes used to create files and directories.\n *\n * @throws ezcBaseFileNotFoundException\n * If the $sourceDir directory is not a directory or does not exist.\n * @throws ezcBaseFilePermissionException\n * If the $sourceDir directory could not be opened for reading, or the\n * destination is not writeable.\n *\n * @param string $source\n * @param string $destination\n * @param int $depth\n * @param int $dirMode\n * @param int $fileMode\n * @return void\n */\n static public function copyRecursive( $source, $destination, $depth = -1, $dirMode = 0775, $fileMode = 0664 )\n {\n // Check if source file exists at all.\n if ( !is_file( $source ) && !is_dir( $source ) )\n {\n throw new ezcBaseFileNotFoundException( $source );\n }", " // Destination file should NOT exist\n if ( is_file( $destination ) || is_dir( $destination ) )\n {\n throw new ezcBaseFilePermissionException( $destination, ezcBaseFileException::WRITE );\n }", " // Skip non readable files in source directory\n if ( !is_readable( $source ) )\n {\n return;\n }", " // Copy\n if ( is_dir( $source ) )\n {\n mkdir( $destination );\n // To ignore umask, umask() should not be changed with\n // multithreaded servers...\n chmod( $destination, $dirMode );\n }\n elseif ( is_file( $source ) )\n {\n copy( $source, $destination );\n chmod( $destination, $fileMode );\n }", " if ( ( $depth === 0 ) ||\n ( !is_dir( $source ) ) )\n {\n // Do not recurse (any more)\n return;\n }", " // Recurse\n $dh = opendir( $source );\n while ( ( $file = readdir( $dh ) ) !== false )\n {\n if ( ( $file === '.' ) ||\n ( $file === '..' ) )\n {\n continue;\n }", " self::copyRecursive(\n $source . '/' . $file,\n $destination . '/' . $file,\n $depth - 1, $dirMode, $fileMode\n );\n }\n }", " /**\n * Calculates the relative path of the file/directory '$path' to a given\n * $base path.\n *\n * $path and $base should be fully absolute paths. This function returns the\n * answer of \"How do I go from $base to $path\". If the $path and $base are\n * the same path, the function returns '.'. This method does not touch the\n * filesystem.\n *\n * @param string $path\n * @param string $base\n * @return string\n */\n static public function calculateRelativePath( $path, $base )\n {\n // Sanitize the paths to use the correct directory separator for the platform\n $path = strtr( $path, '\\\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR );\n $base = strtr( $base, '\\\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR );", " $base = explode( DIRECTORY_SEPARATOR, $base );\n $path = explode( DIRECTORY_SEPARATOR, $path );", " // If the paths are the same we return\n if ( $base === $path )\n {\n return '.';\n }", " $result = '';", " $pathPart = array_shift( $path );\n $basePart = array_shift( $base );\n while ( $pathPart == $basePart )\n {\n $pathPart = array_shift( $path );\n $basePart = array_shift( $base );\n }", " if ( $pathPart != null )\n {\n array_unshift( $path, $pathPart );\n }\n if ( $basePart != null )\n {\n array_unshift( $base, $basePart );\n }", " $result = str_repeat( '..' . DIRECTORY_SEPARATOR, count( $base ) );\n // prevent a trailing DIRECTORY_SEPARATOR in case there is only a ..\n if ( count( $path ) == 0 )\n {\n $result = substr( $result, 0, -strlen( DIRECTORY_SEPARATOR ) );\n }\n $result .= join( DIRECTORY_SEPARATOR, $path );", " return $result;\n }", " /**\n * Returns whether the passed $path is an absolute path, giving the current $os.\n *\n * With the $os parameter you can tell this function to use the semantics\n * for a different operating system to determine whether a path is\n * absolute. The $os argument defaults to the OS that the script is running\n * on.\n *\n * @param string $path\n * @param string $os\n * @return bool\n */\n public static function isAbsolutePath( $path, $os = null )\n {\n if ( $os === null )\n {\n $os = ezcBaseFeatures::os();\n }", " // Stream wrapper like phar can also be considered absolute paths\n if ( preg_match( '(^[a-z]{3,}://)S', $path ) )\n {\n return true;\n }", " switch ( $os )\n {\n case 'Windows':\n // Sanitize the paths to use the correct directory separator for the platform\n $path = strtr( $path, '\\\\/', '\\\\\\\\' );", " // Absolute paths with drive letter: X:\\\n if ( preg_match( '@^[A-Z]:\\\\\\\\@i', $path ) )\n {\n return true;\n }", " // Absolute paths with network paths: \\\\server\\share\\\n if ( preg_match( '@^\\\\\\\\\\\\\\\\[A-Z]+\\\\\\\\[^\\\\\\\\]@i', $path ) )\n {\n return true;\n }\n break;\n case 'Mac':\n case 'Linux':\n case 'FreeBSD':\n default:\n // Sanitize the paths to use the correct directory separator for the platform\n $path = strtr( $path, '\\\\/', '//' );", " if ( $path[0] == '/' )\n {\n return true;\n }\n }\n return false;\n }\n}\n?>" ]
[ 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved.\n * @license http://ez.no/licenses/new_bsd New BSD License\n * @version 1.8\n * @filesource\n * @package Base\n */", "/**\n * Provides a selection of static independent methods to provide functionality\n * for file and file system handling.\n *\n * This example shows how to use the findRecursive method:\n * <code>\n * <?php\n * // lists all the files under /etc (including subdirectories) that end in\n * // .conf\n * $confFiles = ezcBaseFile::findRecursive( \"/etc\", array( '@\\.conf$@' ) );\n *\n * // lists all autoload files in the components source tree and excludes the\n * // ones in the autoload subdirectory. Statistics are returned in the $stats\n * // variable which is passed by reference.\n * $files = ezcBaseFile::findRecursive(\n * \"/dat/dev/ezcomponents\",\n * array( '@src/.*_autoload.php$@' ),\n * array( '@/autoload/@' ),\n * $stats\n * );\n *\n * // lists all binaries in /bin except the ones starting with a \"g\"\n * $data = ezcBaseFile::findRecursive( \"/bin\", array(), array( '@^/bin/g@' ) );\n * ?>\n * </code>\n *\n * @package Base\n * @version 1.8\n * @mainclass\n */\nclass ezcBaseFile\n{\n /**\n * This is the callback used by findRecursive to collect data.\n *\n * This callback method works together with walkRecursive() and is called\n * for every file/and or directory. The $context is a callback specific\n * container in which data can be stored and shared between the different\n * calls to the callback function. The walkRecursive() function also passes\n * in the full absolute directory in $sourceDir, the filename in $fileName\n * and file information (such as size, modes, types) as an array as\n * returned by PHP's stat() in the $fileInfo parameter.\n *\n * @param ezcBaseFileFindContext $context\n * @param string $sourceDir\n * @param string $fileName\n * @param array(stat) $fileInfo\n */\n static protected function findRecursiveCallback( ezcBaseFileFindContext $context, $sourceDir, $fileName, $fileInfo )\n {\n // ignore if we have a directory\n if ( $fileInfo['mode'] & 0x4000 )\n {\n return;\n }", " // update the statistics\n $context->elements[] = $sourceDir . DIRECTORY_SEPARATOR . $fileName;\n $context->count++;\n $context->size += $fileInfo['size'];\n }", " /**\n * Walks files and directories recursively on a file system\n *\n * This method walks over a directory and calls a callback from every file\n * and directory it finds. You can use $includeFilters to include only\n * specific files, and $excludeFilters to exclude certain files from being\n * returned. The function will always go into subdirectories even if the\n * entry would not have passed the filters.\n *\n * The callback is passed in the $callback parameter, and the\n * $callbackContext will be send to the callback function/method as\n * parameter so that you can store data in there that persists with all the\n * calls and recursive calls to this method. It's up to the callback method\n * to do something useful with this. The callback function's parameters are\n * in order:\n *\n * <ul>\n * <li>ezcBaseFileFindContext $context</li>\n * <li>string $sourceDir</li>\n * <li>string $fileName</li>\n * <li>array(stat) $fileInfo</li>\n * </ul>\n *\n * See {@see findRecursiveCallback()} for an example of a callback function.\n *\n * Filters are regular expressions and are therefore required to have\n * starting and ending delimiters. The Perl Compatible syntax is used as\n * regular expression language.\n *\n * @param string $sourceDir\n * @param array(string) $includeFilters\n * @param array(string) $excludeFilters\n * @param callback $callback\n * @param mixed $callbackContext\n *\n * @throws ezcBaseFileNotFoundException if the $sourceDir directory is not\n * a directory or does not exist.\n * @throws ezcBaseFilePermissionException if the $sourceDir directory could\n * not be opened for reading.\n * @return array\n */", " static public function walkRecursive( $sourceDir, array $includeFilters, array $excludeFilters, $callback, &$callbackContext )", " {\n if ( !is_dir( $sourceDir ) )\n {\n throw new ezcBaseFileNotFoundException( $sourceDir, 'directory' );\n }\n $elements = array();\n $d = @dir( $sourceDir );\n if ( !$d )\n {\n throw new ezcBaseFilePermissionException( $sourceDir, ezcBaseFileException::READ );\n }", " while ( ( $entry = $d->read() ) !== false )\n {\n if ( $entry == '.' || $entry == '..' )\n {\n continue;\n }", " $fileInfo = @stat( $sourceDir . DIRECTORY_SEPARATOR . $entry );\n if ( !$fileInfo )\n {\n $fileInfo = array( 'size' => 0, 'mode' => 0 );\n }", " if ( $fileInfo['mode'] & 0x4000 )\n {\n // We need to ignore the Permission exceptions here as it can\n // be normal that a directory can not be accessed. We only need\n // the exception if the top directory could not be read.\n try\n {\n call_user_func_array( $callback, array( $callbackContext, $sourceDir, $entry, $fileInfo ) );\n $subList = self::walkRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry, $includeFilters, $excludeFilters, $callback, $callbackContext );\n $elements = array_merge( $elements, $subList );\n }\n catch ( ezcBaseFilePermissionException $e )\n {\n }\n }\n else\n {\n // By default a file is included in the return list\n $ok = true;\n // Iterate over the $includeFilters and prohibit the file from\n // being returned when atleast one of them does not match\n foreach ( $includeFilters as $filter )\n {\n if ( !preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) )\n {\n $ok = false;\n break;\n }\n }\n // Iterate over the $excludeFilters and prohibit the file from\n // being returns when atleast one of them matches\n foreach ( $excludeFilters as $filter )\n {\n if ( preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) )\n {\n $ok = false;\n break;\n }\n }", " // If everything's allright, call the callback and add the\n // entry to the elements array\n if ( $ok )\n {\n call_user_func( $callback, $callbackContext, $sourceDir, $entry, $fileInfo );\n $elements[] = $sourceDir . DIRECTORY_SEPARATOR . $entry;\n }\n }\n }\n sort( $elements );\n return $elements;\n }", " /**\n * Finds files recursively on a file system\n *\n * With this method you can scan the file system for files. You can use\n * $includeFilters to include only specific files, and $excludeFilters to\n * exclude certain files from being returned. The function will always go\n * into subdirectories even if the entry would not have passed the filters.\n * It uses the {@see walkRecursive()} method to do the actually recursion.\n *\n * Filters are regular expressions and are therefore required to have\n * starting and ending delimiters. The Perl Compatible syntax is used as\n * regular expression language.\n *\n * If you pass an empty array to the $statistics argument, the function\n * will in details about the number of files found into the 'count' array\n * element, and the total filesize in the 'size' array element. Because this\n * argument is passed by reference, you *have* to pass a variable and you\n * can not pass a constant value such as \"array()\".\n *\n * @param string $sourceDir\n * @param array(string) $includeFilters\n * @param array(string) $excludeFilters\n * @param array() $statistics\n *\n * @throws ezcBaseFileNotFoundException if the $sourceDir directory is not\n * a directory or does not exist.\n * @throws ezcBaseFilePermissionException if the $sourceDir directory could\n * not be opened for reading.\n * @return array\n */\n static public function findRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), &$statistics = null )\n {\n // init statistics array\n if ( !is_array( $statistics ) || !array_key_exists( 'size', $statistics ) || !array_key_exists( 'count', $statistics ) )\n {\n $statistics['size'] = 0;\n $statistics['count'] = 0;\n }", " // create the context, and then start walking over the array\n $context = new ezcBaseFileFindContext;\n self::walkRecursive( $sourceDir, $includeFilters, $excludeFilters, array( 'ezcBaseFile', 'findRecursiveCallback' ), $context );", " // collect the statistics\n $statistics['size'] = $context->size;\n $statistics['count'] = $context->count;", " // return the found and pattern-matched files\n sort( $context->elements );\n return $context->elements;\n }", "\n /**\n * Removes files and directories recursively from a file system\n *\n * This method recursively removes the $directory and all its contents.\n * You should be <b>extremely</b> careful with this method as it has the\n * potential to erase everything that the current user has access to.\n *\n * @param string $directory\n */\n static public function removeRecursive( $directory )\n {\n $sourceDir = realpath( $directory );\n if ( !$sourceDir )\n {\n throw new ezcBaseFileNotFoundException( $directory, 'directory' );\n }\n $d = @dir( $sourceDir );\n if ( !$d )\n {\n throw new ezcBaseFilePermissionException( $directory, ezcBaseFileException::READ );\n }\n // check if we can remove the dir\n $parentDir = realpath( $directory . DIRECTORY_SEPARATOR . '..' );\n if ( !is_writable( $parentDir ) )\n {\n throw new ezcBaseFilePermissionException( $parentDir, ezcBaseFileException::WRITE );\n }\n // loop over contents\n while ( ( $entry = $d->read() ) !== false )\n {\n if ( $entry == '.' || $entry == '..' )\n {\n continue;\n }", " if ( is_dir( $sourceDir . DIRECTORY_SEPARATOR . $entry ) )\n {\n self::removeRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry );\n }\n else\n {\n if ( @unlink( $sourceDir . DIRECTORY_SEPARATOR . $entry ) === false )\n {\n throw new ezcBaseFilePermissionException( $directory . DIRECTORY_SEPARATOR . $entry, ezcBaseFileException::REMOVE );\n }\n }\n }\n $d->close();\n rmdir( $sourceDir );\n }", " /**\n * Recursively copy a file or directory.\n *\n * Recursively copy a file or directory in $source to the given\n * destination. If a depth is given, the operation will stop, if the given\n * recursion depth is reached. A depth of -1 means no limit, while a depth\n * of 0 means, that only the current file or directory will be copied,\n * without any recursion.\n *\n * You may optionally define modes used to create files and directories.\n *\n * @throws ezcBaseFileNotFoundException\n * If the $sourceDir directory is not a directory or does not exist.\n * @throws ezcBaseFilePermissionException\n * If the $sourceDir directory could not be opened for reading, or the\n * destination is not writeable.\n *\n * @param string $source\n * @param string $destination\n * @param int $depth\n * @param int $dirMode\n * @param int $fileMode\n * @return void\n */\n static public function copyRecursive( $source, $destination, $depth = -1, $dirMode = 0775, $fileMode = 0664 )\n {\n // Check if source file exists at all.\n if ( !is_file( $source ) && !is_dir( $source ) )\n {\n throw new ezcBaseFileNotFoundException( $source );\n }", " // Destination file should NOT exist\n if ( is_file( $destination ) || is_dir( $destination ) )\n {\n throw new ezcBaseFilePermissionException( $destination, ezcBaseFileException::WRITE );\n }", " // Skip non readable files in source directory\n if ( !is_readable( $source ) )\n {\n return;\n }", " // Copy\n if ( is_dir( $source ) )\n {\n mkdir( $destination );\n // To ignore umask, umask() should not be changed with\n // multithreaded servers...\n chmod( $destination, $dirMode );\n }\n elseif ( is_file( $source ) )\n {\n copy( $source, $destination );\n chmod( $destination, $fileMode );\n }", " if ( ( $depth === 0 ) ||\n ( !is_dir( $source ) ) )\n {\n // Do not recurse (any more)\n return;\n }", " // Recurse\n $dh = opendir( $source );\n while ( ( $file = readdir( $dh ) ) !== false )\n {\n if ( ( $file === '.' ) ||\n ( $file === '..' ) )\n {\n continue;\n }", " self::copyRecursive(\n $source . '/' . $file,\n $destination . '/' . $file,\n $depth - 1, $dirMode, $fileMode\n );\n }\n }", " /**\n * Calculates the relative path of the file/directory '$path' to a given\n * $base path.\n *\n * $path and $base should be fully absolute paths. This function returns the\n * answer of \"How do I go from $base to $path\". If the $path and $base are\n * the same path, the function returns '.'. This method does not touch the\n * filesystem.\n *\n * @param string $path\n * @param string $base\n * @return string\n */\n static public function calculateRelativePath( $path, $base )\n {\n // Sanitize the paths to use the correct directory separator for the platform\n $path = strtr( $path, '\\\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR );\n $base = strtr( $base, '\\\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR );", " $base = explode( DIRECTORY_SEPARATOR, $base );\n $path = explode( DIRECTORY_SEPARATOR, $path );", " // If the paths are the same we return\n if ( $base === $path )\n {\n return '.';\n }", " $result = '';", " $pathPart = array_shift( $path );\n $basePart = array_shift( $base );\n while ( $pathPart == $basePart )\n {\n $pathPart = array_shift( $path );\n $basePart = array_shift( $base );\n }", " if ( $pathPart != null )\n {\n array_unshift( $path, $pathPart );\n }\n if ( $basePart != null )\n {\n array_unshift( $base, $basePart );\n }", " $result = str_repeat( '..' . DIRECTORY_SEPARATOR, count( $base ) );\n // prevent a trailing DIRECTORY_SEPARATOR in case there is only a ..\n if ( count( $path ) == 0 )\n {\n $result = substr( $result, 0, -strlen( DIRECTORY_SEPARATOR ) );\n }\n $result .= join( DIRECTORY_SEPARATOR, $path );", " return $result;\n }", " /**\n * Returns whether the passed $path is an absolute path, giving the current $os.\n *\n * With the $os parameter you can tell this function to use the semantics\n * for a different operating system to determine whether a path is\n * absolute. The $os argument defaults to the OS that the script is running\n * on.\n *\n * @param string $path\n * @param string $os\n * @return bool\n */\n public static function isAbsolutePath( $path, $os = null )\n {\n if ( $os === null )\n {\n $os = ezcBaseFeatures::os();\n }", " // Stream wrapper like phar can also be considered absolute paths\n if ( preg_match( '(^[a-z]{3,}://)S', $path ) )\n {\n return true;\n }", " switch ( $os )\n {\n case 'Windows':\n // Sanitize the paths to use the correct directory separator for the platform\n $path = strtr( $path, '\\\\/', '\\\\\\\\' );", " // Absolute paths with drive letter: X:\\\n if ( preg_match( '@^[A-Z]:\\\\\\\\@i', $path ) )\n {\n return true;\n }", " // Absolute paths with network paths: \\\\server\\share\\\n if ( preg_match( '@^\\\\\\\\\\\\\\\\[A-Z]+\\\\\\\\[^\\\\\\\\]@i', $path ) )\n {\n return true;\n }\n break;\n case 'Mac':\n case 'Linux':\n case 'FreeBSD':\n default:\n // Sanitize the paths to use the correct directory separator for the platform\n $path = strtr( $path, '\\\\/', '//' );", " if ( $path[0] == '/' )\n {\n return true;\n }\n }\n return false;\n }\n}\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * File containing the ezcConsoleOption class.\n *\n * @package ConsoleTools\n * @version 1.6.1\n * @copyright Copyright (C) 2005-2010 eZ Systems AS. All rights reserved.\n * @license http://ez.no/licenses/new_bsd New BSD License\n * @filesource\n */", "/**\n * Objects of this class store data about a single option for ezcConsoleInput.\n *\n * This class represents a single command line option, which can be handled by \n * the ezcConsoleInput class. This classes only purpose is the storage of\n * the parameter data, the handling of options and arguments is done by the\n * class {@link ezcConsoleInput}.\n * \n * @property-read string $short\n * Short name of the parameter without '-' (eg. 'f').\n * @property-read string $long\n * Long name of the parameter without '--' (eg. 'file').\n * @property int $type\n * Value type of this parameter, default is ezcConsoleInput::TYPE_NONE.\n * See {@link ezcConsoleInput::TYPE_NONE},\n * {@link ezcConsoleInput::TYPE_INT} and\n * {@link ezcConsoleInput::TYPE_STRING}.\n * @property mixed $default\n * Default value if the parameter is submitted without value. If a\n * parameter is eg. of type ezcConsoleInput::TYPE_STRING and\n * therefore expects a value when being submitted, it may be\n * submitted without a value and automatically get the default value\n * specified here.\n * @property bool $multiple\n * Is the submission of multiple instances of this parameters\n * allowed? \n * @property string $shorthelp\n * Short help text. Usually displayed when showing parameter help\n * overview.\n * @property string $longhelp\n * Long help text. Usually displayed when showing parameter detailed\n * help.\n * @property bool $arguments\n * Whether arguments to the program are allowed, when this parameter\n * is submitted. \n * @property bool $mandatory\n * Whether a parameter is mandatory to be set. If this flag is true,\n * the parameter must be submitted whenever the program is run.\n * @property bool $isHelpOption\n * Whether a parameter is a help option. If this flag is true, and\n * the parameter is set, all options marked as mandatory may be\n * skipped.\n *\n * @package ConsoleTools\n * @version 1.6.1\n */\nclass ezcConsoleOption\n{\n /**\n * Container to hold the properties\n *\n * @var array(string=>mixed)\n */\n protected $properties;", " /**\n * Dependency rules of this parameter.\n * \n * @see ezcConsoleOption::addDependency()\n * @see ezcConsoleOption::removeDependency()\n * @see ezcConsoleOption::hasDependency()\n * @see ezcConsoleOption::getDependencies()\n * @see ezcConsoleOption::resetDependencies()\n * \n * @var array(string=>ezcConsoleParamemterRule)\n */\n protected $dependencies = array();", " /**\n * Exclusion rules of this parameter.\n * \n * @see ezcConsoleOption::addExclusion()\n * @see ezcConsoleOption::removeExclusion()\n * @see ezcConsoleOption::hasExclusion()\n * @see ezcConsoleOption::getExclusions()\n * @see ezcConsoleOption::resetExclusions()\n * \n * @var array(string=>ezcConsoleParamemterRule)\n */\n protected $exclusions = array();", " /**\n * The value the parameter was assigned to when being submitted.\n * Boolean false indicates the parameter was not submitted, boolean\n * true means the parameter was submitted, but did not have a value.\n * In any other case, this caries the submitted value.\n * \n * @var mixed\n */\n public $value = false;", " /**\n * Create a new parameter struct.\n * Creates a new basic parameter struct with the base information \"$short\"\n * (the short name of the parameter) and \"$long\" (the long version). You\n * simply apply these parameters as strings (without '-' or '--'). So\n *\n * <code>\n * $param = new ezcConsoleOption( 'f', 'file' );\n * </code>\n *\n * will result in a parameter that can be accessed using\n * \n * <code>\n * $ mytool -f\n * </code>\n *\n * or\n * \n * <code>\n * $ mytool --file\n * </code>\n * .\n *\n * The newly created parameter contains only it's 2 names and each other \n * attribute is set to it's default value. You can simply manipulate\n * those attributes by accessing them directly.\n * \n * @param string $short Short name of the parameter without '-' (eg. 'f').\n * @param string $long Long name of the parameter without '--' (eg. 'file').\n * @param int $type Value type of the parameter. One of ezcConsoleInput::TYPE_*.\n * @param mixed $default Default value the parameter holds if not submitted.\n * @param bool $multiple If the parameter may be submitted multiple times.\n * @param string $shorthelp Short help text.\n * @param string $longhelp Long help text.\n * @param array(ezcConsoleOptionRule) $dependencies Dependency rules.\n * @param array(ezcConsoleOptionRule) $exclusions Exclusion rules.\n * @param bool $arguments Whether supplying arguments is allowed when this parameter is set.\n * @param bool $mandatory Whether the parameter must be always submitted.\n * @param bool $isHelpOption Indicates that the given parameter is a help \n * option. If a help option is set, all rule \n * checking is skipped (dependency/exclusion/\n * mandatory).\n *\n * @throws ezcConsoleInvalidOptionNameException If the option names start with a \"-\" \n * sign or contain whitespaces.\n */\n public function __construct( ", " $short = '', \n $long, ", " $type = ezcConsoleInput::TYPE_NONE, \n $default = null, \n $multiple = false,\n $shorthelp = 'No help available.',\n $longhelp = 'Sorry, there is no help text available for this parameter.', \n array $dependencies = array(),\n array $exclusions = array(), \n $arguments = true,\n $mandatory = false,\n $isHelpOption = false\n )\n {\n $this->properties['short'] = '';\n $this->properties['long'] = '';\n $this->properties['arguments'] = $arguments;", " if ( !self::validateOptionName( $short ) )\n {\n throw new ezcConsoleInvalidOptionNameException( $short );\n }\n $this->properties['short'] = $short;\n \n if ( !self::validateOptionName( $long ) )\n {\n throw new ezcConsoleInvalidOptionNameException( $long );\n }\n $this->properties['long'] = $long;\n \n $this->__set( \"type\", $type !== null ? $type : ezcConsoleInput::TYPE_NONE );\n $this->__set( \"multiple\", $multiple !== null ? $multiple : false );\n $this->__set( \"default\", $default !== null ? $default : null );\n $this->__set( \"shorthelp\", $shorthelp !== null ? $shorthelp : 'No help available.' );\n $this->__set( \"longhelp\", $longhelp !== null ? $longhelp : 'Sorry, there is no help text available for this parameter.' );\n \n $dependencies = $dependencies !== null && is_array( $dependencies ) ? $dependencies : array();\n foreach ( $dependencies as $dep )\n {\n $this->addDependency( $dep );\n }\n \n $exclusions = $exclusions !== null && is_array( $exclusions ) ? $exclusions : array();\n foreach ( $exclusions as $exc )\n {\n $this->addExclusion( $exc );\n }", " $this->__set( \"mandatory\", $mandatory !== null ? $mandatory : false );\n $this->__set( \"isHelpOption\", $isHelpOption !== null ? $isHelpOption : false );\n }", " /**\n * Add a new dependency for a parameter.\n * This registeres a new dependency rule with the parameter. If you try\n * to add an already registered rule it will simply be ignored. Else,\n * the submitted rule will be added to the parameter as a dependency.\n *\n * @param ezcConsoleOptionRule $rule The rule to add.\n * @return void\n */\n public function addDependency( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->dependencies as $existRule )\n {\n if ( $rule == $existRule )\n {\n return;\n }\n }\n $this->dependencies[] = $rule;\n }\n \n /**\n * Remove a dependency rule from a parameter.\n * This removes a given rule from a parameter, if it exists. If the rule is\n * not registered with the parameter, the method call will simply be ignored.\n * \n * @param ezcConsoleOptionRule $rule The rule to be removed.\n * @return void\n */\n public function removeDependency( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->dependencies as $id => $existRule )\n {\n if ( $rule == $existRule )\n {\n unset( $this->dependencies[$id] );\n }\n }\n }\n \n /**\n * Remove all dependency rule referring to a parameter.\n * This removes all dependency rules from a parameter, that refer to as specific \n * parameter. If no rule is registered with this parameter as reference, the \n * method call will simply be ignored.\n * \n * @param ezcConsoleOption $param The param to be check for rules.\n * @return void\n */\n public function removeAllDependencies( ezcConsoleOption $param )\n {\n foreach ( $this->dependencies as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n unset( $this->dependencies[$id] );\n }\n }\n }\n \n /**\n * Returns if a dependency to the given option exists.\n * Returns true if a dependency rule to the given option is registered,\n * otherwise false.\n * \n * @param ezcConsoleOption $param The param to check if a dependency exists to.\n * @return bool True if rule is registered, otherwise false.\n */\n public function hasDependency( ezcConsoleOption $param )\n {\n foreach ( $this->dependencies as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n return true;\n }\n }\n return false;\n }\n \n /**\n * Returns the dependency rules registered with this parameter.\n * Returns an array of registered dependencies.\n *\n * For example:\n * <code>\n * array(\n * 0 => ezcConsoleOptionRule,\n * 1 => ezcConsoleOptionRule,\n * 2 => ezcConsoleOptionRule,\n * );\n * </code>\n * \n * @return array(ezcConsoleOptionRule) Dependency definition.\n */\n public function getDependencies()\n {\n return $this->dependencies;\n }", " /**\n * Reset existing dependency rules.\n * Deletes all registered dependency rules from the option definition.\n * \n * @return void\n */\n public function resetDependencies() \n {\n $this->dependencies = array();\n }", " /**\n * Add a new exclusion for an option.\n * This registeres a new exclusion rule with the option. If you try\n * to add an already registered rule it will simply be ignored. Else,\n * the submitted rule will be added to the option as a exclusion.\n *\n * @param ezcConsoleOptionRule $rule The rule to add.\n * @return void\n */\n public function addExclusion( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->exclusions as $existRule )\n {\n if ( $rule == $existRule )\n {\n return;\n }\n }\n $this->exclusions[] = $rule;\n }\n \n /**\n * Remove a exclusion rule from a option.\n * This removes a given rule from a option, if it exists. If the rule is\n * not registered with the option, the method call will simply be ignored.\n * \n * @param ezcConsoleOptionRule $rule The rule to be removed.\n * @return void\n */\n public function removeExclusion( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->exclusions as $id => $existRule )\n {\n if ( $rule == $existRule )\n {\n unset( $this->exclusions[$id] );\n }\n }\n }\n \n /**\n * Remove all exclusion rule referring to a option.\n * This removes all exclusion rules from a option, that refer to as specific \n * option. If no rule is registered with this option as reference, the \n * method call will simply be ignored.\n * \n * @param ezcConsoleOption $param The option to remove rule for.\n * @return void\n */\n public function removeAllExclusions( ezcConsoleOption $param )\n {\n foreach ( $this->exclusions as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n unset( $this->exclusions[$id] );\n }\n }\n }\n \n /**\n * Returns if a given exclusion rule is registered with the option.\n * Returns true if a exclusion rule to the given option is registered,\n * otherwise false.\n * \n * @param ezcConsoleOption $param The param to check if exclusions exist for.\n * @return bool True if rule is registered, otherwise false.\n */\n public function hasExclusion( ezcConsoleOption $param )\n {\n foreach ( $this->exclusions as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n return true;\n }\n }\n return false;\n }\n \n /**\n * Returns the exclusion rules registered with this parameter.\n * Returns an array of registered exclusions.\n *\n * For example:\n * <code>\n * array(\n * 0 => ezcConsoleOptionRule,\n * 1 => ezcConsoleOptionRule,\n * 2 => ezcConsoleOptionRule,\n * );\n * </code>\n * \n * @return array(ezcConsoleOptionRule) Exclusions definition.\n */\n public function getExclusions()\n {\n return $this->exclusions;\n }", " /**\n * Reset existing exclusion rules.\n * Deletes all registered exclusion rules from the option definition.\n *\n * @return void\n */\n public function resetExclusions() \n {\n $this->exclusions = array();\n }\n \n /**\n * Property read access.\n * Provides read access to the properties of the object.\n * \n * @param string $key The name of the property.\n * @return mixed The value if property exists and isset, otherwise null.\n * @ignore\n */\n public function __get( $key )\n {\n switch ( $key )\n {\n case 'short':\n case 'long':\n case 'type':\n case 'default':\n case 'multiple':\n case 'shorthelp':\n case 'longhelp':\n case 'arguments':\n case 'isHelpOption':\n case 'mandatory':\n return $this->properties[$key];\n case 'dependencies':\n default:\n throw new ezcBasePropertyNotFoundException( $key );\n }\n }", " /**\n * Property write access.\n * \n * @param string $key Name of the property.\n * @param mixed $val The value for the property.\n *\n * @throws ezcBasePropertyPermissionException\n * If the property you try to access is read-only.\n * @throws ezcBasePropertyNotFoundException \n * If the the desired property is not found.\n * @ignore\n */\n public function __set( $key, $val )\n {\n switch ( $key )\n {\n case 'type':\n if ( $val !== ezcConsoleInput::TYPE_NONE \n && $val !== ezcConsoleInput::TYPE_INT \n && $val !== ezcConsoleInput::TYPE_STRING )\n {\n throw new ezcBaseValueException( \n $key, \n $val, \n 'ezcConsoleInput::TYPE_STRING, ezcConsoleInput::TYPE_INT or ezcConsoleInput::TYPE_NONE' \n );\n }\n break;\n case 'default':\n if ( ( is_scalar( $val ) === false && $val !== null ) )\n {\n // Newly allow arrays, if multiple is true\n if ( $this->multiple === true && is_array( $val ) === true )\n {\n break;\n }\n throw new ezcBaseValueException( $key, $val, 'a string or a number, if multiple == true also an array' );\n }\n break;\n case 'multiple':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'shorthelp':\n if ( !is_string( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'string' );\n }\n break;\n case 'longhelp':\n if ( !is_string( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'string' );\n }\n break;\n case 'arguments':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'mandatory':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'isHelpOption':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'long':\n case 'short':\n throw new ezcBasePropertyPermissionException( $key, ezcBasePropertyPermissionException::READ );\n break;\n default:\n throw new ezcBasePropertyNotFoundException( $key );\n break;\n }\n $this->properties[$key] = $val;\n }\n \n /**\n * Property isset access.\n * \n * @param string $key Name of the property.\n * @return bool True is the property is set, otherwise false.\n * @ignore\n */\n public function __isset( $key )\n {\n switch ( $key )\n {\n case 'short':\n case 'long':\n case 'type':\n case 'default':\n case 'multiple':\n case 'shorthelp':\n case 'longhelp':\n case 'arguments':\n case 'isHelpOption':\n case 'mandatory':\n return ( $this->properties[$key] !== null );\n }\n return false;\n }", " /**\n * Returns if a given name if valid for use as a parameter name a parameter. \n * Checks if a given parameter name is generally valid for use. It checks a)\n * that the name does not start with '-' or '--' and b) if it contains\n * whitespaces. Note, that this method does not check any conflicts with already\n * used parameter names.\n * \n * @param string $name The name to check.\n * @return bool True if the name is valid, otherwise false.\n */\n public static function validateOptionName( $name )\n {\n if ( substr( $name, 0, 1 ) === '-' || strpos( $name, ' ' ) !== false )\n {\n return false;\n }\n return true;\n }\n}", "?>" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/**\n * File containing the ezcConsoleOption class.\n *\n * @package ConsoleTools\n * @version 1.6.1\n * @copyright Copyright (C) 2005-2010 eZ Systems AS. All rights reserved.\n * @license http://ez.no/licenses/new_bsd New BSD License\n * @filesource\n */", "/**\n * Objects of this class store data about a single option for ezcConsoleInput.\n *\n * This class represents a single command line option, which can be handled by \n * the ezcConsoleInput class. This classes only purpose is the storage of\n * the parameter data, the handling of options and arguments is done by the\n * class {@link ezcConsoleInput}.\n * \n * @property-read string $short\n * Short name of the parameter without '-' (eg. 'f').\n * @property-read string $long\n * Long name of the parameter without '--' (eg. 'file').\n * @property int $type\n * Value type of this parameter, default is ezcConsoleInput::TYPE_NONE.\n * See {@link ezcConsoleInput::TYPE_NONE},\n * {@link ezcConsoleInput::TYPE_INT} and\n * {@link ezcConsoleInput::TYPE_STRING}.\n * @property mixed $default\n * Default value if the parameter is submitted without value. If a\n * parameter is eg. of type ezcConsoleInput::TYPE_STRING and\n * therefore expects a value when being submitted, it may be\n * submitted without a value and automatically get the default value\n * specified here.\n * @property bool $multiple\n * Is the submission of multiple instances of this parameters\n * allowed? \n * @property string $shorthelp\n * Short help text. Usually displayed when showing parameter help\n * overview.\n * @property string $longhelp\n * Long help text. Usually displayed when showing parameter detailed\n * help.\n * @property bool $arguments\n * Whether arguments to the program are allowed, when this parameter\n * is submitted. \n * @property bool $mandatory\n * Whether a parameter is mandatory to be set. If this flag is true,\n * the parameter must be submitted whenever the program is run.\n * @property bool $isHelpOption\n * Whether a parameter is a help option. If this flag is true, and\n * the parameter is set, all options marked as mandatory may be\n * skipped.\n *\n * @package ConsoleTools\n * @version 1.6.1\n */\nclass ezcConsoleOption\n{\n /**\n * Container to hold the properties\n *\n * @var array(string=>mixed)\n */\n protected $properties;", " /**\n * Dependency rules of this parameter.\n * \n * @see ezcConsoleOption::addDependency()\n * @see ezcConsoleOption::removeDependency()\n * @see ezcConsoleOption::hasDependency()\n * @see ezcConsoleOption::getDependencies()\n * @see ezcConsoleOption::resetDependencies()\n * \n * @var array(string=>ezcConsoleParamemterRule)\n */\n protected $dependencies = array();", " /**\n * Exclusion rules of this parameter.\n * \n * @see ezcConsoleOption::addExclusion()\n * @see ezcConsoleOption::removeExclusion()\n * @see ezcConsoleOption::hasExclusion()\n * @see ezcConsoleOption::getExclusions()\n * @see ezcConsoleOption::resetExclusions()\n * \n * @var array(string=>ezcConsoleParamemterRule)\n */\n protected $exclusions = array();", " /**\n * The value the parameter was assigned to when being submitted.\n * Boolean false indicates the parameter was not submitted, boolean\n * true means the parameter was submitted, but did not have a value.\n * In any other case, this caries the submitted value.\n * \n * @var mixed\n */\n public $value = false;", " /**\n * Create a new parameter struct.\n * Creates a new basic parameter struct with the base information \"$short\"\n * (the short name of the parameter) and \"$long\" (the long version). You\n * simply apply these parameters as strings (without '-' or '--'). So\n *\n * <code>\n * $param = new ezcConsoleOption( 'f', 'file' );\n * </code>\n *\n * will result in a parameter that can be accessed using\n * \n * <code>\n * $ mytool -f\n * </code>\n *\n * or\n * \n * <code>\n * $ mytool --file\n * </code>\n * .\n *\n * The newly created parameter contains only it's 2 names and each other \n * attribute is set to it's default value. You can simply manipulate\n * those attributes by accessing them directly.\n * \n * @param string $short Short name of the parameter without '-' (eg. 'f').\n * @param string $long Long name of the parameter without '--' (eg. 'file').\n * @param int $type Value type of the parameter. One of ezcConsoleInput::TYPE_*.\n * @param mixed $default Default value the parameter holds if not submitted.\n * @param bool $multiple If the parameter may be submitted multiple times.\n * @param string $shorthelp Short help text.\n * @param string $longhelp Long help text.\n * @param array(ezcConsoleOptionRule) $dependencies Dependency rules.\n * @param array(ezcConsoleOptionRule) $exclusions Exclusion rules.\n * @param bool $arguments Whether supplying arguments is allowed when this parameter is set.\n * @param bool $mandatory Whether the parameter must be always submitted.\n * @param bool $isHelpOption Indicates that the given parameter is a help \n * option. If a help option is set, all rule \n * checking is skipped (dependency/exclusion/\n * mandatory).\n *\n * @throws ezcConsoleInvalidOptionNameException If the option names start with a \"-\" \n * sign or contain whitespaces.\n */\n public function __construct( ", " $short = '',\n $long = '',", " $type = ezcConsoleInput::TYPE_NONE, \n $default = null, \n $multiple = false,\n $shorthelp = 'No help available.',\n $longhelp = 'Sorry, there is no help text available for this parameter.', \n array $dependencies = array(),\n array $exclusions = array(), \n $arguments = true,\n $mandatory = false,\n $isHelpOption = false\n )\n {\n $this->properties['short'] = '';\n $this->properties['long'] = '';\n $this->properties['arguments'] = $arguments;", " if ( !self::validateOptionName( $short ) )\n {\n throw new ezcConsoleInvalidOptionNameException( $short );\n }\n $this->properties['short'] = $short;\n \n if ( !self::validateOptionName( $long ) )\n {\n throw new ezcConsoleInvalidOptionNameException( $long );\n }\n $this->properties['long'] = $long;\n \n $this->__set( \"type\", $type !== null ? $type : ezcConsoleInput::TYPE_NONE );\n $this->__set( \"multiple\", $multiple !== null ? $multiple : false );\n $this->__set( \"default\", $default !== null ? $default : null );\n $this->__set( \"shorthelp\", $shorthelp !== null ? $shorthelp : 'No help available.' );\n $this->__set( \"longhelp\", $longhelp !== null ? $longhelp : 'Sorry, there is no help text available for this parameter.' );\n \n $dependencies = $dependencies !== null && is_array( $dependencies ) ? $dependencies : array();\n foreach ( $dependencies as $dep )\n {\n $this->addDependency( $dep );\n }\n \n $exclusions = $exclusions !== null && is_array( $exclusions ) ? $exclusions : array();\n foreach ( $exclusions as $exc )\n {\n $this->addExclusion( $exc );\n }", " $this->__set( \"mandatory\", $mandatory !== null ? $mandatory : false );\n $this->__set( \"isHelpOption\", $isHelpOption !== null ? $isHelpOption : false );\n }", " /**\n * Add a new dependency for a parameter.\n * This registeres a new dependency rule with the parameter. If you try\n * to add an already registered rule it will simply be ignored. Else,\n * the submitted rule will be added to the parameter as a dependency.\n *\n * @param ezcConsoleOptionRule $rule The rule to add.\n * @return void\n */\n public function addDependency( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->dependencies as $existRule )\n {\n if ( $rule == $existRule )\n {\n return;\n }\n }\n $this->dependencies[] = $rule;\n }\n \n /**\n * Remove a dependency rule from a parameter.\n * This removes a given rule from a parameter, if it exists. If the rule is\n * not registered with the parameter, the method call will simply be ignored.\n * \n * @param ezcConsoleOptionRule $rule The rule to be removed.\n * @return void\n */\n public function removeDependency( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->dependencies as $id => $existRule )\n {\n if ( $rule == $existRule )\n {\n unset( $this->dependencies[$id] );\n }\n }\n }\n \n /**\n * Remove all dependency rule referring to a parameter.\n * This removes all dependency rules from a parameter, that refer to as specific \n * parameter. If no rule is registered with this parameter as reference, the \n * method call will simply be ignored.\n * \n * @param ezcConsoleOption $param The param to be check for rules.\n * @return void\n */\n public function removeAllDependencies( ezcConsoleOption $param )\n {\n foreach ( $this->dependencies as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n unset( $this->dependencies[$id] );\n }\n }\n }\n \n /**\n * Returns if a dependency to the given option exists.\n * Returns true if a dependency rule to the given option is registered,\n * otherwise false.\n * \n * @param ezcConsoleOption $param The param to check if a dependency exists to.\n * @return bool True if rule is registered, otherwise false.\n */\n public function hasDependency( ezcConsoleOption $param )\n {\n foreach ( $this->dependencies as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n return true;\n }\n }\n return false;\n }\n \n /**\n * Returns the dependency rules registered with this parameter.\n * Returns an array of registered dependencies.\n *\n * For example:\n * <code>\n * array(\n * 0 => ezcConsoleOptionRule,\n * 1 => ezcConsoleOptionRule,\n * 2 => ezcConsoleOptionRule,\n * );\n * </code>\n * \n * @return array(ezcConsoleOptionRule) Dependency definition.\n */\n public function getDependencies()\n {\n return $this->dependencies;\n }", " /**\n * Reset existing dependency rules.\n * Deletes all registered dependency rules from the option definition.\n * \n * @return void\n */\n public function resetDependencies() \n {\n $this->dependencies = array();\n }", " /**\n * Add a new exclusion for an option.\n * This registeres a new exclusion rule with the option. If you try\n * to add an already registered rule it will simply be ignored. Else,\n * the submitted rule will be added to the option as a exclusion.\n *\n * @param ezcConsoleOptionRule $rule The rule to add.\n * @return void\n */\n public function addExclusion( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->exclusions as $existRule )\n {\n if ( $rule == $existRule )\n {\n return;\n }\n }\n $this->exclusions[] = $rule;\n }\n \n /**\n * Remove a exclusion rule from a option.\n * This removes a given rule from a option, if it exists. If the rule is\n * not registered with the option, the method call will simply be ignored.\n * \n * @param ezcConsoleOptionRule $rule The rule to be removed.\n * @return void\n */\n public function removeExclusion( ezcConsoleOptionRule $rule )\n {\n foreach ( $this->exclusions as $id => $existRule )\n {\n if ( $rule == $existRule )\n {\n unset( $this->exclusions[$id] );\n }\n }\n }\n \n /**\n * Remove all exclusion rule referring to a option.\n * This removes all exclusion rules from a option, that refer to as specific \n * option. If no rule is registered with this option as reference, the \n * method call will simply be ignored.\n * \n * @param ezcConsoleOption $param The option to remove rule for.\n * @return void\n */\n public function removeAllExclusions( ezcConsoleOption $param )\n {\n foreach ( $this->exclusions as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n unset( $this->exclusions[$id] );\n }\n }\n }\n \n /**\n * Returns if a given exclusion rule is registered with the option.\n * Returns true if a exclusion rule to the given option is registered,\n * otherwise false.\n * \n * @param ezcConsoleOption $param The param to check if exclusions exist for.\n * @return bool True if rule is registered, otherwise false.\n */\n public function hasExclusion( ezcConsoleOption $param )\n {\n foreach ( $this->exclusions as $id => $rule )\n {\n if ( $rule->option == $param )\n {\n return true;\n }\n }\n return false;\n }\n \n /**\n * Returns the exclusion rules registered with this parameter.\n * Returns an array of registered exclusions.\n *\n * For example:\n * <code>\n * array(\n * 0 => ezcConsoleOptionRule,\n * 1 => ezcConsoleOptionRule,\n * 2 => ezcConsoleOptionRule,\n * );\n * </code>\n * \n * @return array(ezcConsoleOptionRule) Exclusions definition.\n */\n public function getExclusions()\n {\n return $this->exclusions;\n }", " /**\n * Reset existing exclusion rules.\n * Deletes all registered exclusion rules from the option definition.\n *\n * @return void\n */\n public function resetExclusions() \n {\n $this->exclusions = array();\n }\n \n /**\n * Property read access.\n * Provides read access to the properties of the object.\n * \n * @param string $key The name of the property.\n * @return mixed The value if property exists and isset, otherwise null.\n * @ignore\n */\n public function __get( $key )\n {\n switch ( $key )\n {\n case 'short':\n case 'long':\n case 'type':\n case 'default':\n case 'multiple':\n case 'shorthelp':\n case 'longhelp':\n case 'arguments':\n case 'isHelpOption':\n case 'mandatory':\n return $this->properties[$key];\n case 'dependencies':\n default:\n throw new ezcBasePropertyNotFoundException( $key );\n }\n }", " /**\n * Property write access.\n * \n * @param string $key Name of the property.\n * @param mixed $val The value for the property.\n *\n * @throws ezcBasePropertyPermissionException\n * If the property you try to access is read-only.\n * @throws ezcBasePropertyNotFoundException \n * If the the desired property is not found.\n * @ignore\n */\n public function __set( $key, $val )\n {\n switch ( $key )\n {\n case 'type':\n if ( $val !== ezcConsoleInput::TYPE_NONE \n && $val !== ezcConsoleInput::TYPE_INT \n && $val !== ezcConsoleInput::TYPE_STRING )\n {\n throw new ezcBaseValueException( \n $key, \n $val, \n 'ezcConsoleInput::TYPE_STRING, ezcConsoleInput::TYPE_INT or ezcConsoleInput::TYPE_NONE' \n );\n }\n break;\n case 'default':\n if ( ( is_scalar( $val ) === false && $val !== null ) )\n {\n // Newly allow arrays, if multiple is true\n if ( $this->multiple === true && is_array( $val ) === true )\n {\n break;\n }\n throw new ezcBaseValueException( $key, $val, 'a string or a number, if multiple == true also an array' );\n }\n break;\n case 'multiple':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'shorthelp':\n if ( !is_string( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'string' );\n }\n break;\n case 'longhelp':\n if ( !is_string( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'string' );\n }\n break;\n case 'arguments':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'mandatory':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'isHelpOption':\n if ( !is_bool( $val ) )\n {\n throw new ezcBaseValueException( $key, $val, 'bool' );\n }\n break;\n case 'long':\n case 'short':\n throw new ezcBasePropertyPermissionException( $key, ezcBasePropertyPermissionException::READ );\n break;\n default:\n throw new ezcBasePropertyNotFoundException( $key );\n break;\n }\n $this->properties[$key] = $val;\n }\n \n /**\n * Property isset access.\n * \n * @param string $key Name of the property.\n * @return bool True is the property is set, otherwise false.\n * @ignore\n */\n public function __isset( $key )\n {\n switch ( $key )\n {\n case 'short':\n case 'long':\n case 'type':\n case 'default':\n case 'multiple':\n case 'shorthelp':\n case 'longhelp':\n case 'arguments':\n case 'isHelpOption':\n case 'mandatory':\n return ( $this->properties[$key] !== null );\n }\n return false;\n }", " /**\n * Returns if a given name if valid for use as a parameter name a parameter. \n * Checks if a given parameter name is generally valid for use. It checks a)\n * that the name does not start with '-' or '--' and b) if it contains\n * whitespaces. Note, that this method does not check any conflicts with already\n * used parameter names.\n * \n * @param string $name The name to check.\n * @return bool True if the name is valid, otherwise false.\n */\n public static function validateOptionName( $name )\n {\n if ( substr( $name, 0, 1 ) === '-' || strpos( $name, ' ' ) !== false )\n {\n return false;\n }\n return true;\n }\n}", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "$response = erLhcoreClassChatEventDispatcher::getInstance()->dispatch('chat.geoconfiguration', array());", "$tpl = erLhcoreClassTemplate::getInstance( 'lhchat/geoconfiguration.tpl.php');", "$geoData = erLhcoreClassModelChatConfig::fetch('geo_data');\n$data = (array)$geoData->data;", "$geoLocationData = erLhcoreClassModelChatConfig::fetch('geo_location_data');\n$dataLocation = (array)$geoLocationData->data;", "if ( isset($_POST['store_map']) ) {\n\t$definition = array(\n\t\t\t'zoom' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'int',array('min_range' => 1)\n\t\t\t),\n\t\t\t'lat' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'float'\n\t\t\t),\n\t\t\t'lng' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'float'\n\t\t\t),\n\t\t\t'gmaps_api_key' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'unsafe_raw'\n\t\t\t)\n\t);", "\t$Errors = array();", "\t$form = new ezcInputForm( INPUT_POST, $definition );\n\t$Errors = array();", "\tif (!isset($_POST['csfr_token']) || !$currentUser->validateCSFRToken($_POST['csfr_token'])) {\n\t\terLhcoreClassModule::redirect('chat/geoconfiguration');\n\t\texit;\n\t}", "\tif ( $form->hasValidData( 'zoom' )) {\n\t\t$dataLocation['zoom'] = $form->zoom;\n\t} else {\n\t\t$dataLocation['zoom'] = 3;\n\t}", "\tif ( $form->hasValidData( 'gmaps_api_key' )) {\n\t\t$dataLocation['gmaps_api_key'] = $form->gmaps_api_key;\n\t} else {\n\t\t$dataLocation['gmaps_api_key'] = '';\n\t}", "\tif ( $form->hasValidData( 'lat' )) {\n\t\t$dataLocation['lat'] = $form->lat;\n\t} else {\n\t\t$dataLocation['lat'] = '35.416';\n\t}", "\tif ( $form->hasValidData( 'lng' )) {\n\t\t$dataLocation['lng'] = $form->lng;\n\t} else {\n\t\t$dataLocation['lng'] = '19.121';\n\t}", "\t$geoLocationData->value = serialize($dataLocation);\n\t$geoLocationData->saveThis();\n\texit;\n}", "", "if ( isset($_POST['StoreGeoIPConfiguration']) ) {", " $definition = array(\n 'UseGeoIP' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'GeoDetectionEnabled' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_COUNTRY_CODE' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_COUNTRY_NAME' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_CITY' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_LATITUDE' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_REGION' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_LONGITUDE' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'locatorhqAPIKey' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ipinfodbAPIKey' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'locatorhqUsername' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'locatorhqIP' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'MaxMindDetectionType' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),", " 'CityGeoLocation' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),", " 'ipapi_key' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'abstractapi_key' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n )\n );", " $Errors = array();", " $form = new ezcInputForm( INPUT_POST, $definition );\n $Errors = array();", " if ( $form->hasValidData( 'GeoDetectionEnabled' ) && $form->GeoDetectionEnabled == true ) {\n $data['geo_detection_enabled'] = 1;\n } else {\n $data['geo_detection_enabled'] = 0;\n }", " if (!isset($_POST['csfr_token']) || !$currentUser->validateCSFRToken($_POST['csfr_token'])) {\n \terLhcoreClassModule::redirect('chat/geoconfiguration');\n \texit;\n }", " if ($data['geo_detection_enabled'] == 1) {\n if ( $form->hasValidData( 'UseGeoIP' ) ) {", " if ($form->UseGeoIP == 'mod_geoip2'){", " $data['geo_service_identifier'] = 'mod_geoip2';", " if ( $form->hasValidData( 'ServerVariableGEOIP_COUNTRY_CODE' ) && $form->ServerVariableGEOIP_COUNTRY_CODE != '' && isset($_SERVER[$form->ServerVariableGEOIP_COUNTRY_CODE]) ) {\n $data['mod_geo_ip_country_code'] = $form->ServerVariableGEOIP_COUNTRY_CODE;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country code variable does not exist!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_COUNTRY_NAME' ) && $form->ServerVariableGEOIP_COUNTRY_NAME != '' && isset($_SERVER[$form->ServerVariableGEOIP_COUNTRY_NAME]) ) {\n $data['mod_geo_ip_country_name'] = $form->ServerVariableGEOIP_COUNTRY_NAME;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country name variable does not exist!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_CITY' ) && $form->ServerVariableGEOIP_CITY != '' ) {\n $data['mod_geo_ip_city_name'] = $form->ServerVariableGEOIP_CITY;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter city variable!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_REGION' ) && $form->ServerVariableGEOIP_REGION != '' ) {\n $data['mod_geo_ip_region_name'] = $form->ServerVariableGEOIP_REGION;\n } else {\n $data['mod_geo_ip_region_name'] = '';\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_LATITUDE' ) && $form->ServerVariableGEOIP_LATITUDE != '' ) {\n $data['mod_geo_ip_latitude'] = $form->ServerVariableGEOIP_LATITUDE;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter latitude variable!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_LONGITUDE' ) && $form->ServerVariableGEOIP_LONGITUDE != '' ) {\n $data['mod_geo_ip_longitude'] = $form->ServerVariableGEOIP_LONGITUDE;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter longitude variable!');\n }", "\n } elseif ($form->UseGeoIP == 'freegeoip') {\n $data['geo_service_identifier'] = 'freegeoip';\n $data['freegeoip_key'] = isset($_POST['freegeoip_key']) ? $_POST['freegeoip_key'] : '';", " if (empty($data['freegeoip_key'])) {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter API Key!');\n }", " if (empty($Errors)){\n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('freegeoip',erLhcoreClassIPDetect::getServerAddress(),$data);\n if ( $responseDetection == false || !isset($responseDetection->country_code) || !isset($responseDetection->country_name) ) {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages!');\n }\n }", " } elseif ($form->UseGeoIP == 'max_mind') {\n $data['geo_service_identifier'] = 'max_mind'; \n $data['max_mind_detection_type'] = $form->hasValidData('MaxMindDetectionType') ? $form->MaxMindDetectionType : 'city';", " $data['max_mind_city_location'] = $form->CityGeoLocation != '' ? $form->CityGeoLocation : 'var/external/geoip/GeoLite2-City.mmdb';\n ", " if ($data['max_mind_detection_type'] == 'city' && !file_exists($data['max_mind_city_location'])) {\n \t$Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','MaxMind city file does not exists!');\n } elseif (!file_exists('var/external/geoip/GeoLite2-Country.mmdb')) {\n \t$data['max_mind_detection_type'] = 'country';\n \t$Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','MaxMind country file does not exists!');\n }", " ", " if (empty($Errors)) {\n\t $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('max_mind','94.23.200.91',array('city_file' => $data['max_mind_city_location'],'detection_type' => $data['max_mind_detection_type'])); \n\t if ( $responseDetection == false || !isset($responseDetection->country_code) || !isset($responseDetection->country_name) ) {\n\t $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that MaxMind database files exists!');\n\t }\n } \n \n } elseif ($form->UseGeoIP == 'locatorhq') {\n $data['geo_service_identifier'] = 'locatorhq';", " $filledAPIData = true;", " if ( $form->hasValidData( 'locatorhqAPIKey' ) && $form->locatorhqAPIKey != '' ) {\n $data['locatorhq_api_key'] = $form->locatorhqAPIKey;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter the API key!');\n }", " if ( $form->hasValidData( 'locatorhqUsername' ) && $form->locatorhqUsername != '' ) {\n $data['locatorhqusername'] = $form->locatorhqUsername;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter the API username!');\n }", " if ( $form->hasValidData( 'locatorhqIP' ) && $form->locatorhqIP != '' ) {\n $data['locatorhqip'] = $form->locatorhqIP;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter IP!');\n }", " if ($filledAPIData == true) {\n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('locatorhq',erLhcoreClassIPDetect::getServerAddress(),array('ip' => $data['locatorhqip'], 'username' => $data['locatorhqusername'], 'api_key' => $data['locatorhq_api_key']));\n if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key and username is correct!');\n }\n }\n } elseif ($form->UseGeoIP == 'ipinfodbcom') {\n $data['geo_service_identifier'] = 'ipinfodbcom';", " $filledAPIData = true;", " if ( $form->hasValidData( 'ipinfodbAPIKey' ) && $form->ipinfodbAPIKey != '' ) {\n $data['ipinfodbcom_api_key'] = $form->ipinfodbAPIKey;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter the API key!');\n }\n \n if ($filledAPIData == true) {\n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('ipinfodbcom',erLhcoreClassIPDetect::getServerAddress(),array('api_key' => $data['ipinfodbcom_api_key']));\n if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key is correct!');\n }\n }\n } elseif ($form->UseGeoIP == 'php_geoip') {\n $data['geo_service_identifier'] = 'php_geoip';\n \n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('php_geoip','8.8.8.8');\n if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that you have installed php-GeoIP module and GeoIPCity.dat file is available!');\n } \n } elseif ($form->UseGeoIP == 'ipapi') {\n $data['geo_service_identifier'] = 'ipapi';", " if ( $form->hasValidData( 'ipapi_key' ) && $form->ipapi_key != '' ) {\n $data['ipapi_key'] = $form->ipapi_key;\n } else {\n $data['ipapi_key'] = '';\n }", " $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('ipapi','8.8.8.8');", " if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key is correct!');\n }", " } elseif ($form->UseGeoIP == 'abstractapi') {\n $data['geo_service_identifier'] = 'abstractapi';", " if ( $form->hasValidData( 'abstractapi_key' ) && $form->abstractapi_key != '' ) {\n $data['abstractapi_key'] = $form->abstractapi_key;\n } else {\n $data['abstractapi_key'] = '';\n }", " $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('abstractapi','8.8.8.8', array('abstractapi_key' => $data['abstractapi_key']));", " if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key is correct!');\n }", " }", " } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please choose a service provider!');\n }\n }", " if (count($Errors) == 0) {\n $geoData->value = serialize($data);\n $geoData->saveThis();\n $tpl->set('updated','done');\n } else {\n $tpl->set('errors',$Errors);\n }", "}", "$tpl->set('geo_data',$data);\n$tpl->set('geo_location_data',$dataLocation);", "$Result['content'] = $tpl->fetch();\n$Result['path'] = array(\narray('url' => erLhcoreClassDesign::baseurl('chat/onlineusers'), 'title' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Online users')),\narray('title' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO detection configuration')));", "\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "$response = erLhcoreClassChatEventDispatcher::getInstance()->dispatch('chat.geoconfiguration', array());", "$tpl = erLhcoreClassTemplate::getInstance( 'lhchat/geoconfiguration.tpl.php');", "$geoData = erLhcoreClassModelChatConfig::fetch('geo_data');\n$data = (array)$geoData->data;", "$geoLocationData = erLhcoreClassModelChatConfig::fetch('geo_location_data');\n$dataLocation = (array)$geoLocationData->data;", "if ( isset($_POST['store_map']) ) {\n\t$definition = array(\n\t\t\t'zoom' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'int',array('min_range' => 1)\n\t\t\t),\n\t\t\t'lat' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'float'\n\t\t\t),\n\t\t\t'lng' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'float'\n\t\t\t),\n\t\t\t'gmaps_api_key' => new ezcInputFormDefinitionElement(\n\t\t\t\t\tezcInputFormDefinitionElement::OPTIONAL, 'unsafe_raw'\n\t\t\t)\n\t);", "\t$Errors = array();", "\t$form = new ezcInputForm( INPUT_POST, $definition );\n\t$Errors = array();", "\tif (!isset($_POST['csfr_token']) || !$currentUser->validateCSFRToken($_POST['csfr_token'])) {\n\t\terLhcoreClassModule::redirect('chat/geoconfiguration');\n\t\texit;\n\t}", "\tif ( $form->hasValidData( 'zoom' )) {\n\t\t$dataLocation['zoom'] = $form->zoom;\n\t} else {\n\t\t$dataLocation['zoom'] = 3;\n\t}", "\tif ( $form->hasValidData( 'gmaps_api_key' )) {\n\t\t$dataLocation['gmaps_api_key'] = $form->gmaps_api_key;\n\t} else {\n\t\t$dataLocation['gmaps_api_key'] = '';\n\t}", "\tif ( $form->hasValidData( 'lat' )) {\n\t\t$dataLocation['lat'] = $form->lat;\n\t} else {\n\t\t$dataLocation['lat'] = '35.416';\n\t}", "\tif ( $form->hasValidData( 'lng' )) {\n\t\t$dataLocation['lng'] = $form->lng;\n\t} else {\n\t\t$dataLocation['lng'] = '19.121';\n\t}", "\t$geoLocationData->value = serialize($dataLocation);\n\t$geoLocationData->saveThis();\n\texit;\n}", "", "if ( isset($_POST['StoreGeoIPConfiguration']) ) {", " $definition = array(\n 'UseGeoIP' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'GeoDetectionEnabled' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_COUNTRY_CODE' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_COUNTRY_NAME' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_CITY' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_LATITUDE' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_REGION' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ServerVariableGEOIP_LONGITUDE' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'locatorhqAPIKey' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'ipinfodbAPIKey' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'locatorhqUsername' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'locatorhqIP' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'MaxMindDetectionType' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),", "", " 'ipapi_key' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n ),\n 'abstractapi_key' => new ezcInputFormDefinitionElement(\n ezcInputFormDefinitionElement::OPTIONAL, 'string'\n )\n );", " $Errors = array();", " $form = new ezcInputForm( INPUT_POST, $definition );\n $Errors = array();", " if ( $form->hasValidData( 'GeoDetectionEnabled' ) && $form->GeoDetectionEnabled == true ) {\n $data['geo_detection_enabled'] = 1;\n } else {\n $data['geo_detection_enabled'] = 0;\n }", " if (!isset($_POST['csfr_token']) || !$currentUser->validateCSFRToken($_POST['csfr_token'])) {\n \terLhcoreClassModule::redirect('chat/geoconfiguration');\n \texit;\n }", " if ($data['geo_detection_enabled'] == 1) {\n if ( $form->hasValidData( 'UseGeoIP' ) ) {", " if ($form->UseGeoIP == 'mod_geoip2'){", " $data['geo_service_identifier'] = 'mod_geoip2';", " if ( $form->hasValidData( 'ServerVariableGEOIP_COUNTRY_CODE' ) && $form->ServerVariableGEOIP_COUNTRY_CODE != '' && isset($_SERVER[$form->ServerVariableGEOIP_COUNTRY_CODE]) ) {\n $data['mod_geo_ip_country_code'] = $form->ServerVariableGEOIP_COUNTRY_CODE;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country code variable does not exist!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_COUNTRY_NAME' ) && $form->ServerVariableGEOIP_COUNTRY_NAME != '' && isset($_SERVER[$form->ServerVariableGEOIP_COUNTRY_NAME]) ) {\n $data['mod_geo_ip_country_name'] = $form->ServerVariableGEOIP_COUNTRY_NAME;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Country name variable does not exist!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_CITY' ) && $form->ServerVariableGEOIP_CITY != '' ) {\n $data['mod_geo_ip_city_name'] = $form->ServerVariableGEOIP_CITY;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter city variable!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_REGION' ) && $form->ServerVariableGEOIP_REGION != '' ) {\n $data['mod_geo_ip_region_name'] = $form->ServerVariableGEOIP_REGION;\n } else {\n $data['mod_geo_ip_region_name'] = '';\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_LATITUDE' ) && $form->ServerVariableGEOIP_LATITUDE != '' ) {\n $data['mod_geo_ip_latitude'] = $form->ServerVariableGEOIP_LATITUDE;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter latitude variable!');\n }", " if ( $form->hasValidData( 'ServerVariableGEOIP_LONGITUDE' ) && $form->ServerVariableGEOIP_LONGITUDE != '' ) {\n $data['mod_geo_ip_longitude'] = $form->ServerVariableGEOIP_LONGITUDE;\n } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter longitude variable!');\n }", "\n } elseif ($form->UseGeoIP == 'freegeoip') {\n $data['geo_service_identifier'] = 'freegeoip';\n $data['freegeoip_key'] = isset($_POST['freegeoip_key']) ? $_POST['freegeoip_key'] : '';", " if (empty($data['freegeoip_key'])) {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter API Key!');\n }", " if (empty($Errors)){\n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('freegeoip',erLhcoreClassIPDetect::getServerAddress(),$data);\n if ( $responseDetection == false || !isset($responseDetection->country_code) || !isset($responseDetection->country_name) ) {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages!');\n }\n }", " } elseif ($form->UseGeoIP == 'max_mind') {\n $data['geo_service_identifier'] = 'max_mind'; \n $data['max_mind_detection_type'] = $form->hasValidData('MaxMindDetectionType') ? $form->MaxMindDetectionType : 'city';", " $data['max_mind_city_location'] = 'var/external/geoip/GeoLite2-City.mmdb';\n", " if ($data['max_mind_detection_type'] == 'city' && !file_exists($data['max_mind_city_location'])) {\n \t$Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','MaxMind city file does not exists!');\n } elseif (!file_exists('var/external/geoip/GeoLite2-Country.mmdb')) {\n \t$data['max_mind_detection_type'] = 'country';\n \t$Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','MaxMind country file does not exists!');\n }", "", " if (empty($Errors)) {\n\t $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('max_mind','94.23.200.91',array('city_file' => $data['max_mind_city_location'],'detection_type' => $data['max_mind_detection_type'])); \n\t if ( $responseDetection == false || !isset($responseDetection->country_code) || !isset($responseDetection->country_name) ) {\n\t $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that MaxMind database files exists!');\n\t }\n } \n \n } elseif ($form->UseGeoIP == 'locatorhq') {\n $data['geo_service_identifier'] = 'locatorhq';", " $filledAPIData = true;", " if ( $form->hasValidData( 'locatorhqAPIKey' ) && $form->locatorhqAPIKey != '' ) {\n $data['locatorhq_api_key'] = $form->locatorhqAPIKey;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter the API key!');\n }", " if ( $form->hasValidData( 'locatorhqUsername' ) && $form->locatorhqUsername != '' ) {\n $data['locatorhqusername'] = $form->locatorhqUsername;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter the API username!');\n }", " if ( $form->hasValidData( 'locatorhqIP' ) && $form->locatorhqIP != '' ) {\n $data['locatorhqip'] = $form->locatorhqIP;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter IP!');\n }", " if ($filledAPIData == true) {\n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('locatorhq',erLhcoreClassIPDetect::getServerAddress(),array('ip' => $data['locatorhqip'], 'username' => $data['locatorhqusername'], 'api_key' => $data['locatorhq_api_key']));\n if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key and username is correct!');\n }\n }\n } elseif ($form->UseGeoIP == 'ipinfodbcom') {\n $data['geo_service_identifier'] = 'ipinfodbcom';", " $filledAPIData = true;", " if ( $form->hasValidData( 'ipinfodbAPIKey' ) && $form->ipinfodbAPIKey != '' ) {\n $data['ipinfodbcom_api_key'] = $form->ipinfodbAPIKey;\n } else {\n $filledAPIData = false;\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please enter the API key!');\n }\n \n if ($filledAPIData == true) {\n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('ipinfodbcom',erLhcoreClassIPDetect::getServerAddress(),array('api_key' => $data['ipinfodbcom_api_key']));\n if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key is correct!');\n }\n }\n } elseif ($form->UseGeoIP == 'php_geoip') {\n $data['geo_service_identifier'] = 'php_geoip';\n \n $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('php_geoip','8.8.8.8');\n if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that you have installed php-GeoIP module and GeoIPCity.dat file is available!');\n } \n } elseif ($form->UseGeoIP == 'ipapi') {\n $data['geo_service_identifier'] = 'ipapi';", " if ( $form->hasValidData( 'ipapi_key' ) && $form->ipapi_key != '' ) {\n $data['ipapi_key'] = $form->ipapi_key;\n } else {\n $data['ipapi_key'] = '';\n }", " $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('ipapi','8.8.8.8');", " if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key is correct!');\n }", " } elseif ($form->UseGeoIP == 'abstractapi') {\n $data['geo_service_identifier'] = 'abstractapi';", " if ( $form->hasValidData( 'abstractapi_key' ) && $form->abstractapi_key != '' ) {\n $data['abstractapi_key'] = $form->abstractapi_key;\n } else {\n $data['abstractapi_key'] = '';\n }", " $responseDetection = erLhcoreClassModelChatOnlineUser::getUserData('abstractapi','8.8.8.8', array('abstractapi_key' => $data['abstractapi_key']));", " if ($responseDetection == false || !isset($responseDetection->country_code)){\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Setting service provider failed, please check that your service provider allows you to make requests to remote pages and your API key is correct!');\n }", " }", " } else {\n $Errors[] = erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Please choose a service provider!');\n }\n }", " if (count($Errors) == 0) {\n $geoData->value = serialize($data);\n $geoData->saveThis();\n $tpl->set('updated','done');\n } else {\n $tpl->set('errors',$Errors);\n }", "}", "$tpl->set('geo_data',$data);\n$tpl->set('geo_location_data',$dataLocation);", "$Result['content'] = $tpl->fetch();\n$Result['path'] = array(\narray('url' => erLhcoreClassDesign::baseurl('chat/onlineusers'), 'title' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','Online users')),\narray('title' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/onlineusers','GEO detection configuration')));", "\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [133, 114, 152, 210], "buggy_code_start_loc": [131, 113, 150, 112], "filenames": ["lhc_web/design/defaulttheme/tpl/lhchat/geoconfiguration.tpl.php", "lhc_web/ezcomponents/Base/src/file.php", "lhc_web/ezcomponents/ConsoleTools/src/input/option.php", "lhc_web/modules/lhchat/geoconfiguration.php"], "fixing_code_end_loc": [133, 114, 152, 207], "fixing_code_start_loc": [131, 113, 150, 111], "message": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:livehelperchat:live_helper_chat:*:*:*:*:*:*:*:*", "matchCriteriaId": "744AB687-C4FD-47D3-BE0A-186C84B8E942", "versionEndExcluding": "3.91", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "livehelperchat is vulnerable to Generation of Error Message Containing Sensitive Information"}, {"lang": "es", "value": "livehelperchat es vulnerable a la Generaci\u00f3n de Mensajes de Error que Contienen Informaci\u00f3n Confidencial"}], "evaluatorComment": null, "id": "CVE-2021-4177", "lastModified": "2022-01-06T20:08:19.720", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:N/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "version": "3.0"}, "exploitabilityScore": 2.8, "impactScore": 1.4, "source": "security@huntr.dev", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.3, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "NONE", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 1.4, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-12-28T06:15:06.467", "references": [{"source": "security@huntr.dev", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, {"source": "security@huntr.dev", "tags": ["Exploit", "Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://huntr.dev/bounties/ac641425-1c64-4874-95e7-c7805c72074e"}], "sourceIdentifier": "security@huntr.dev", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-209"}], "source": "security@huntr.dev", "type": "Primary"}]}, "github_commit_url": "https://github.com/livehelperchat/livehelperchat/commit/b280beae2e0de37b9e998c31c5d1839852724fc1"}, "type": "CWE-209"}
34
Determine whether the {function_name} code is vulnerable or not.
[ "[package]\nname = \"base64\"\nversion = \"0.13.0\"\nauthors = [\"Alice Maz <alice@alicemaz.com>\", \"Marshall Pierce <marshall@mpierce.org>\"]\ndescription = \"encodes and decodes base64 as bytes or utf8\"\nrepository = \"https://github.com/marshallpierce/rust-base64\"\ndocumentation = \"https://docs.rs/base64\"\nreadme = \"README.md\"\nkeywords = [\"base64\", \"utf8\", \"encode\", \"decode\", \"no_std\"]\ncategories = [\"encoding\"]\nlicense = \"MIT/Apache-2.0\"\nedition = \"2018\"", "[[bench]]\nname = \"benchmarks\"\nharness = false", "[dev-dependencies]\n# 0.3.3 requires rust 1.36.0 for stable copied()\ncriterion = \"=0.3.2\"\nrand = \"0.6.1\"\nstructopt = \"0.3\"", "[features]\ndefault = [\"std\"]\nalloc = []\nstd = []", "", "\n[profile.bench]\n# Useful for better disassembly when using `perf record` and `perf annotate`\ndebug = true" ]
[ 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "[package]\nname = \"base64\"\nversion = \"0.13.0\"\nauthors = [\"Alice Maz <alice@alicemaz.com>\", \"Marshall Pierce <marshall@mpierce.org>\"]\ndescription = \"encodes and decodes base64 as bytes or utf8\"\nrepository = \"https://github.com/marshallpierce/rust-base64\"\ndocumentation = \"https://docs.rs/base64\"\nreadme = \"README.md\"\nkeywords = [\"base64\", \"utf8\", \"encode\", \"decode\", \"no_std\"]\ncategories = [\"encoding\"]\nlicense = \"MIT/Apache-2.0\"\nedition = \"2018\"", "[[bench]]\nname = \"benchmarks\"\nharness = false", "[dev-dependencies]\n# 0.3.3 requires rust 1.36.0 for stable copied()\ncriterion = \"=0.3.2\"\nrand = \"0.6.1\"\nstructopt = \"0.3\"", "[features]\ndefault = [\"std\"]\nalloc = []\nstd = []", "slow_but_safe = []", "\n[profile.bench]\n# Useful for better disassembly when using `perf record` and `perf annotate`\ndebug = true" ]
[ 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "use crate::{tables, Config, PAD_BYTE};", "#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\nuse crate::STANDARD;\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\nuse alloc::vec::Vec;\nuse core::fmt;\n#[cfg(any(feature = \"std\", test))]\nuse std::error;", "// decode logic operates on chunks of 8 input bytes without padding\nconst INPUT_CHUNK_LEN: usize = 8;\nconst DECODED_CHUNK_LEN: usize = 6;\n// we read a u64 and write a u64, but a u64 of input only yields 6 bytes of output, so the last\n// 2 bytes of any output u64 should not be counted as written to (but must be available in a\n// slice).\nconst DECODED_CHUNK_SUFFIX: usize = 2;", "// how many u64's of input to handle at a time\nconst CHUNKS_PER_FAST_LOOP_BLOCK: usize = 4;\nconst INPUT_BLOCK_LEN: usize = CHUNKS_PER_FAST_LOOP_BLOCK * INPUT_CHUNK_LEN;\n// includes the trailing 2 bytes for the final u64 write\nconst DECODED_BLOCK_LEN: usize =\n CHUNKS_PER_FAST_LOOP_BLOCK * DECODED_CHUNK_LEN + DECODED_CHUNK_SUFFIX;", "/// Errors that can occur while decoding.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum DecodeError {\n /// An invalid byte was found in the input. The offset and offending byte are provided.\n InvalidByte(usize, u8),\n /// The length of the input is invalid.\n /// A typical cause of this is stray trailing whitespace or other separator bytes.\n /// In the case where excess trailing bytes have produced an invalid length *and* the last byte\n /// is also an invalid base64 symbol (as would be the case for whitespace, etc), `InvalidByte`\n /// will be emitted instead of `InvalidLength` to make the issue easier to debug.\n InvalidLength,\n /// The last non-padding input symbol's encoded 6 bits have nonzero bits that will be discarded.\n /// This is indicative of corrupted or truncated Base64.\n /// Unlike InvalidByte, which reports symbols that aren't in the alphabet, this error is for\n /// symbols that are in the alphabet but represent nonsensical encodings.\n InvalidLastSymbol(usize, u8),\n}", "impl fmt::Display for DecodeError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match *self {\n DecodeError::InvalidByte(index, byte) => {\n write!(f, \"Invalid byte {}, offset {}.\", byte, index)\n }\n DecodeError::InvalidLength => write!(f, \"Encoded text cannot have a 6-bit remainder.\"),\n DecodeError::InvalidLastSymbol(index, byte) => {\n write!(f, \"Invalid last symbol {}, offset {}.\", byte, index)\n }\n }\n }\n}", "#[cfg(any(feature = \"std\", test))]\nimpl error::Error for DecodeError {\n fn description(&self) -> &str {\n match *self {\n DecodeError::InvalidByte(_, _) => \"invalid byte\",\n DecodeError::InvalidLength => \"invalid length\",\n DecodeError::InvalidLastSymbol(_, _) => \"invalid last symbol\",\n }\n }", " fn cause(&self) -> Option<&dyn error::Error> {\n None\n }\n}", "///Decode from string reference as octets.\n///Returns a Result containing a Vec<u8>.\n///Convenience `decode_config(input, base64::STANDARD);`.\n///\n///# Example\n///\n///```rust\n///extern crate base64;\n///\n///fn main() {\n/// let bytes = base64::decode(\"aGVsbG8gd29ybGQ=\").unwrap();\n/// println!(\"{:?}\", bytes);\n///}\n///```\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub fn decode<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, DecodeError> {\n decode_config(input, STANDARD)\n}", "///Decode from string reference as octets.\n///Returns a Result containing a Vec<u8>.\n///\n///# Example\n///\n///```rust\n///extern crate base64;\n///\n///fn main() {\n/// let bytes = base64::decode_config(\"aGVsbG8gd29ybGR+Cg==\", base64::STANDARD).unwrap();\n/// println!(\"{:?}\", bytes);\n///\n/// let bytes_url = base64::decode_config(\"aGVsbG8gaW50ZXJuZXR-Cg==\", base64::URL_SAFE).unwrap();\n/// println!(\"{:?}\", bytes_url);\n///}\n///```\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub fn decode_config<T: AsRef<[u8]>>(input: T, config: Config) -> Result<Vec<u8>, DecodeError> {\n let mut buffer = Vec::<u8>::with_capacity(input.as_ref().len() * 4 / 3);", " decode_config_buf(input, config, &mut buffer).map(|_| buffer)\n}", "///Decode from string reference as octets.\n///Writes into the supplied buffer to avoid allocation.\n///Returns a Result containing an empty tuple, aka ().\n///\n///# Example\n///\n///```rust\n///extern crate base64;\n///\n///fn main() {\n/// let mut buffer = Vec::<u8>::new();\n/// base64::decode_config_buf(\"aGVsbG8gd29ybGR+Cg==\", base64::STANDARD, &mut buffer).unwrap();\n/// println!(\"{:?}\", buffer);\n///\n/// buffer.clear();\n///\n/// base64::decode_config_buf(\"aGVsbG8gaW50ZXJuZXR-Cg==\", base64::URL_SAFE, &mut buffer)\n/// .unwrap();\n/// println!(\"{:?}\", buffer);\n///}\n///```\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub fn decode_config_buf<T: AsRef<[u8]>>(\n input: T,\n config: Config,\n buffer: &mut Vec<u8>,\n) -> Result<(), DecodeError> {\n let input_bytes = input.as_ref();", " let starting_output_len = buffer.len();", " let num_chunks = num_chunks(input_bytes);\n let decoded_len_estimate = num_chunks\n .checked_mul(DECODED_CHUNK_LEN)\n .and_then(|p| p.checked_add(starting_output_len))\n .expect(\"Overflow when calculating output buffer length\");\n buffer.resize(decoded_len_estimate, 0);", " let bytes_written;\n {\n let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];\n bytes_written = decode_helper(input_bytes, num_chunks, config, buffer_slice)?;\n }", " buffer.truncate(starting_output_len + bytes_written);", " Ok(())\n}", "/// Decode the input into the provided output slice.\n///\n/// This will not write any bytes past exactly what is decoded (no stray garbage bytes at the end).\n///\n/// If you don't know ahead of time what the decoded length should be, size your buffer with a\n/// conservative estimate for the decoded length of an input: 3 bytes of output for every 4 bytes of\n/// input, rounded up, or in other words `(input_len + 3) / 4 * 3`.\n///\n/// If the slice is not large enough, this will panic.\npub fn decode_config_slice<T: AsRef<[u8]>>(\n input: T,\n config: Config,\n output: &mut [u8],\n) -> Result<usize, DecodeError> {\n let input_bytes = input.as_ref();", " decode_helper(input_bytes, num_chunks(input_bytes), config, output)\n}", "/// Return the number of input chunks (including a possibly partial final chunk) in the input\nfn num_chunks(input: &[u8]) -> usize {\n input\n .len()\n .checked_add(INPUT_CHUNK_LEN - 1)\n .expect(\"Overflow when calculating number of chunks in input\")\n / INPUT_CHUNK_LEN\n}", "/// Helper to avoid duplicating num_chunks calculation, which is costly on short inputs.\n/// Returns the number of bytes written, or an error.\n// We're on the fragile edge of compiler heuristics here. If this is not inlined, slow. If this is\n// inlined(always), a different slow. plain ol' inline makes the benchmarks happiest at the moment,\n// but this is fragile and the best setting changes with only minor code modifications.\n#[inline]\nfn decode_helper(\n input: &[u8],\n num_chunks: usize,\n config: Config,\n output: &mut [u8],\n) -> Result<usize, DecodeError> {\n let char_set = config.char_set;\n let decode_table = char_set.decode_table();", " let remainder_len = input.len() % INPUT_CHUNK_LEN;", " // Because the fast decode loop writes in groups of 8 bytes (unrolled to\n // CHUNKS_PER_FAST_LOOP_BLOCK times 8 bytes, where possible) and outputs 8 bytes at a time (of\n // which only 6 are valid data), we need to be sure that we stop using the fast decode loop\n // soon enough that there will always be 2 more bytes of valid data written after that loop.\n let trailing_bytes_to_skip = match remainder_len {\n // if input is a multiple of the chunk size, ignore the last chunk as it may have padding,\n // and the fast decode logic cannot handle padding\n 0 => INPUT_CHUNK_LEN,\n // 1 and 5 trailing bytes are illegal: can't decode 6 bits of input into a byte\n 1 | 5 => {\n // trailing whitespace is so common that it's worth it to check the last byte to\n // possibly return a better error message\n if let Some(b) = input.last() {\n if *b != PAD_BYTE && decode_table[*b as usize] == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(input.len() - 1, *b));\n }\n }", " return Err(DecodeError::InvalidLength);\n }\n // This will decode to one output byte, which isn't enough to overwrite the 2 extra bytes\n // written by the fast decode loop. So, we have to ignore both these 2 bytes and the\n // previous chunk.\n 2 => INPUT_CHUNK_LEN + 2,\n // If this is 3 unpadded chars, then it would actually decode to 2 bytes. However, if this\n // is an erroneous 2 chars + 1 pad char that would decode to 1 byte, then it should fail\n // with an error, not panic from going past the bounds of the output slice, so we let it\n // use stage 3 + 4.\n 3 => INPUT_CHUNK_LEN + 3,\n // This can also decode to one output byte because it may be 2 input chars + 2 padding\n // chars, which would decode to 1 byte.\n 4 => INPUT_CHUNK_LEN + 4,\n // Everything else is a legal decode len (given that we don't require padding), and will\n // decode to at least 2 bytes of output.\n _ => remainder_len,\n };", " // rounded up to include partial chunks\n let mut remaining_chunks = num_chunks;", " let mut input_index = 0;\n let mut output_index = 0;", " {\n let length_of_fast_decode_chunks = input.len().saturating_sub(trailing_bytes_to_skip);", " // Fast loop, stage 1\n // manual unroll to CHUNKS_PER_FAST_LOOP_BLOCK of u64s to amortize slice bounds checks\n if let Some(max_start_index) = length_of_fast_decode_chunks.checked_sub(INPUT_BLOCK_LEN) {\n while input_index <= max_start_index {\n let input_slice = &input[input_index..(input_index + INPUT_BLOCK_LEN)];\n let output_slice = &mut output[output_index..(output_index + DECODED_BLOCK_LEN)];", " decode_chunk(\n &input_slice[0..],\n input_index,\n decode_table,\n &mut output_slice[0..],\n )?;\n decode_chunk(\n &input_slice[8..],\n input_index + 8,\n decode_table,\n &mut output_slice[6..],\n )?;\n decode_chunk(\n &input_slice[16..],\n input_index + 16,\n decode_table,\n &mut output_slice[12..],\n )?;\n decode_chunk(\n &input_slice[24..],\n input_index + 24,\n decode_table,\n &mut output_slice[18..],\n )?;", " input_index += INPUT_BLOCK_LEN;\n output_index += DECODED_BLOCK_LEN - DECODED_CHUNK_SUFFIX;\n remaining_chunks -= CHUNKS_PER_FAST_LOOP_BLOCK;\n }\n }", " // Fast loop, stage 2 (aka still pretty fast loop)\n // 8 bytes at a time for whatever we didn't do in stage 1.\n if let Some(max_start_index) = length_of_fast_decode_chunks.checked_sub(INPUT_CHUNK_LEN) {\n while input_index < max_start_index {\n decode_chunk(\n &input[input_index..(input_index + INPUT_CHUNK_LEN)],\n input_index,\n decode_table,\n &mut output\n [output_index..(output_index + DECODED_CHUNK_LEN + DECODED_CHUNK_SUFFIX)],\n )?;", " output_index += DECODED_CHUNK_LEN;\n input_index += INPUT_CHUNK_LEN;\n remaining_chunks -= 1;\n }\n }\n }", " // Stage 3\n // If input length was such that a chunk had to be deferred until after the fast loop\n // because decoding it would have produced 2 trailing bytes that wouldn't then be\n // overwritten, we decode that chunk here. This way is slower but doesn't write the 2\n // trailing bytes.\n // However, we still need to avoid the last chunk (partial or complete) because it could\n // have padding, so we always do 1 fewer to avoid the last chunk.\n for _ in 1..remaining_chunks {\n decode_chunk_precise(\n &input[input_index..],\n input_index,\n decode_table,\n &mut output[output_index..(output_index + DECODED_CHUNK_LEN)],\n )?;", " input_index += INPUT_CHUNK_LEN;\n output_index += DECODED_CHUNK_LEN;\n }", " // always have one more (possibly partial) block of 8 input\n debug_assert!(input.len() - input_index > 1 || input.is_empty());\n debug_assert!(input.len() - input_index <= 8);", " // Stage 4\n // Finally, decode any leftovers that aren't a complete input block of 8 bytes.\n // Use a u64 as a stack-resident 8 byte buffer.\n let mut leftover_bits: u64 = 0;\n let mut morsels_in_leftover = 0;\n let mut padding_bytes = 0;\n let mut first_padding_index: usize = 0;\n let mut last_symbol = 0_u8;\n let start_of_leftovers = input_index;\n for (i, b) in input[start_of_leftovers..].iter().enumerate() {\n // '=' padding\n if *b == PAD_BYTE {\n // There can be bad padding in a few ways:\n // 1 - Padding with non-padding characters after it\n // 2 - Padding after zero or one non-padding characters before it\n // in the current quad.\n // 3 - More than two characters of padding. If 3 or 4 padding chars\n // are in the same quad, that implies it will be caught by #2.\n // If it spreads from one quad to another, it will be caught by\n // #2 in the second quad.", " if i % 4 < 2 {\n // Check for case #2.\n let bad_padding_index = start_of_leftovers\n + if padding_bytes > 0 {\n // If we've already seen padding, report the first padding index.\n // This is to be consistent with the faster logic above: it will report an\n // error on the first padding character (since it doesn't expect to see\n // anything but actual encoded data).\n first_padding_index\n } else {\n // haven't seen padding before, just use where we are now\n i\n };\n return Err(DecodeError::InvalidByte(bad_padding_index, *b));\n }", " if padding_bytes == 0 {\n first_padding_index = i;\n }", " padding_bytes += 1;\n continue;\n }", " // Check for case #1.\n // To make '=' handling consistent with the main loop, don't allow\n // non-suffix '=' in trailing chunk either. Report error as first\n // erroneous padding.\n if padding_bytes > 0 {\n return Err(DecodeError::InvalidByte(\n start_of_leftovers + first_padding_index,\n PAD_BYTE,\n ));\n }\n last_symbol = *b;", " // can use up to 8 * 6 = 48 bits of the u64, if last chunk has no padding.\n // To minimize shifts, pack the leftovers from left to right.\n let shift = 64 - (morsels_in_leftover + 1) * 6;\n // tables are all 256 elements, lookup with a u8 index always succeeds\n let morsel = decode_table[*b as usize];\n if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(start_of_leftovers + i, *b));\n }", " leftover_bits |= (morsel as u64) << shift;\n morsels_in_leftover += 1;\n }", " let leftover_bits_ready_to_append = match morsels_in_leftover {\n 0 => 0,\n 2 => 8,\n 3 => 16,\n 4 => 24,\n 6 => 32,\n 7 => 40,\n 8 => 48,\n _ => unreachable!(\n \"Impossible: must only have 0 to 8 input bytes in last chunk, with no invalid lengths\"\n ),\n };", " // if there are bits set outside the bits we care about, last symbol encodes trailing bits that\n // will not be included in the output\n let mask = !0 >> leftover_bits_ready_to_append;\n if !config.decode_allow_trailing_bits && (leftover_bits & mask) != 0 {\n // last morsel is at `morsels_in_leftover` - 1\n return Err(DecodeError::InvalidLastSymbol(\n start_of_leftovers + morsels_in_leftover - 1,\n last_symbol,\n ));\n }", " let mut leftover_bits_appended_to_buf = 0;\n while leftover_bits_appended_to_buf < leftover_bits_ready_to_append {\n // `as` simply truncates the higher bits, which is what we want here\n let selected_bits = (leftover_bits >> (56 - leftover_bits_appended_to_buf)) as u8;\n output[output_index] = selected_bits;\n output_index += 1;", " leftover_bits_appended_to_buf += 8;\n }", " Ok(output_index)\n}", "#[inline]\nfn write_u64(output: &mut [u8], value: u64) {\n output[..8].copy_from_slice(&value.to_be_bytes());\n}\n", "", "/// Decode 8 bytes of input into 6 bytes of output. 8 bytes of output will be written, but only the\n/// first 6 of those contain meaningful data.\n///\n/// `input` is the bytes to decode, of which the first 8 bytes will be processed.\n/// `index_at_start_of_input` is the offset in the overall input (used for reporting errors\n/// accurately)\n/// `decode_table` is the lookup table for the particular base64 alphabet.\n/// `output` will have its first 8 bytes overwritten, of which only the first 6 are valid decoded\n/// data.\n// yes, really inline (worth 30-50% speedup)\n#[inline(always)]\nfn decode_chunk(\n input: &[u8],\n index_at_start_of_input: usize,\n decode_table: &[u8; 256],\n output: &mut [u8],\n) -> Result<(), DecodeError> {\n let mut accum: u64;\n", "", " let morsel = decode_table[input[0] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(index_at_start_of_input, input[0]));\n }\n accum = (morsel as u64) << 58;\n", "", " let morsel = decode_table[input[1] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 1,\n input[1],\n ));\n }\n accum |= (morsel as u64) << 52;\n", "", " let morsel = decode_table[input[2] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 2,\n input[2],\n ));\n }\n accum |= (morsel as u64) << 46;\n", "", " let morsel = decode_table[input[3] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 3,\n input[3],\n ));\n }\n accum |= (morsel as u64) << 40;\n", "", " let morsel = decode_table[input[4] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 4,\n input[4],\n ));\n }\n accum |= (morsel as u64) << 34;\n", "", " let morsel = decode_table[input[5] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 5,\n input[5],\n ));\n }\n accum |= (morsel as u64) << 28;\n", "", " let morsel = decode_table[input[6] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 6,\n input[6],\n ));\n }\n accum |= (morsel as u64) << 22;\n", "", " let morsel = decode_table[input[7] as usize];", "", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 7,\n input[7],\n ));\n }\n accum |= (morsel as u64) << 16;", " write_u64(output, accum);", " Ok(())\n}", "/// Decode an 8-byte chunk, but only write the 6 bytes actually decoded instead of including 2\n/// trailing garbage bytes.\n#[inline]\nfn decode_chunk_precise(\n input: &[u8],\n index_at_start_of_input: usize,\n decode_table: &[u8; 256],\n output: &mut [u8],\n) -> Result<(), DecodeError> {\n let mut tmp_buf = [0_u8; 8];", " decode_chunk(\n input,\n index_at_start_of_input,\n decode_table,\n &mut tmp_buf[..],\n )?;", " output[0..6].copy_from_slice(&tmp_buf[0..6]);", " Ok(())\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n use crate::{\n encode::encode_config_buf,\n encode::encode_config_slice,\n tests::{assert_encode_sanity, random_config},\n };", " use rand::{\n distributions::{Distribution, Uniform},\n FromEntropy, Rng,\n };", " #[test]\n fn decode_chunk_precise_writes_only_6_bytes() {\n let input = b\"Zm9vYmFy\"; // \"foobar\"\n let mut output = [0_u8, 1, 2, 3, 4, 5, 6, 7];\n decode_chunk_precise(&input[..], 0, tables::STANDARD_DECODE, &mut output).unwrap();\n assert_eq!(&vec![b'f', b'o', b'o', b'b', b'a', b'r', 6, 7], &output);\n }", " #[test]\n fn decode_chunk_writes_8_bytes() {\n let input = b\"Zm9vYmFy\"; // \"foobar\"\n let mut output = [0_u8, 1, 2, 3, 4, 5, 6, 7];\n decode_chunk(&input[..], 0, tables::STANDARD_DECODE, &mut output).unwrap();\n assert_eq!(&vec![b'f', b'o', b'o', b'b', b'a', b'r', 0, 0], &output);\n }", " #[test]\n fn decode_into_nonempty_vec_doesnt_clobber_existing_prefix() {\n let mut orig_data = Vec::new();\n let mut encoded_data = String::new();\n let mut decoded_with_prefix = Vec::new();\n let mut decoded_without_prefix = Vec::new();\n let mut prefix = Vec::new();", " let prefix_len_range = Uniform::new(0, 1000);\n let input_len_range = Uniform::new(0, 1000);", " let mut rng = rand::rngs::SmallRng::from_entropy();", " for _ in 0..10_000 {\n orig_data.clear();\n encoded_data.clear();\n decoded_with_prefix.clear();\n decoded_without_prefix.clear();\n prefix.clear();", " let input_len = input_len_range.sample(&mut rng);", " for _ in 0..input_len {\n orig_data.push(rng.gen());\n }", " let config = random_config(&mut rng);\n encode_config_buf(&orig_data, config, &mut encoded_data);\n assert_encode_sanity(&encoded_data, config, input_len);", " let prefix_len = prefix_len_range.sample(&mut rng);", " // fill the buf with a prefix\n for _ in 0..prefix_len {\n prefix.push(rng.gen());\n }", " decoded_with_prefix.resize(prefix_len, 0);\n decoded_with_prefix.copy_from_slice(&prefix);", " // decode into the non-empty buf\n decode_config_buf(&encoded_data, config, &mut decoded_with_prefix).unwrap();\n // also decode into the empty buf\n decode_config_buf(&encoded_data, config, &mut decoded_without_prefix).unwrap();", " assert_eq!(\n prefix_len + decoded_without_prefix.len(),\n decoded_with_prefix.len()\n );\n assert_eq!(orig_data, decoded_without_prefix);", " // append plain decode onto prefix\n prefix.append(&mut decoded_without_prefix);", " assert_eq!(prefix, decoded_with_prefix);\n }\n }", " #[test]\n fn decode_into_slice_doesnt_clobber_existing_prefix_or_suffix() {\n let mut orig_data = Vec::new();\n let mut encoded_data = String::new();\n let mut decode_buf = Vec::new();\n let mut decode_buf_copy: Vec<u8> = Vec::new();", " let input_len_range = Uniform::new(0, 1000);", " let mut rng = rand::rngs::SmallRng::from_entropy();", " for _ in 0..10_000 {\n orig_data.clear();\n encoded_data.clear();\n decode_buf.clear();\n decode_buf_copy.clear();", " let input_len = input_len_range.sample(&mut rng);", " for _ in 0..input_len {\n orig_data.push(rng.gen());\n }", " let config = random_config(&mut rng);\n encode_config_buf(&orig_data, config, &mut encoded_data);\n assert_encode_sanity(&encoded_data, config, input_len);", " // fill the buffer with random garbage, long enough to have some room before and after\n for _ in 0..5000 {\n decode_buf.push(rng.gen());\n }", " // keep a copy for later comparison\n decode_buf_copy.extend(decode_buf.iter());", " let offset = 1000;", " // decode into the non-empty buf\n let decode_bytes_written =\n decode_config_slice(&encoded_data, config, &mut decode_buf[offset..]).unwrap();", " assert_eq!(orig_data.len(), decode_bytes_written);\n assert_eq!(\n orig_data,\n &decode_buf[offset..(offset + decode_bytes_written)]\n );\n assert_eq!(&decode_buf_copy[0..offset], &decode_buf[0..offset]);\n assert_eq!(\n &decode_buf_copy[offset + decode_bytes_written..],\n &decode_buf[offset + decode_bytes_written..]\n );\n }\n }", " #[test]\n fn decode_into_slice_fits_in_precisely_sized_slice() {\n let mut orig_data = Vec::new();\n let mut encoded_data = String::new();\n let mut decode_buf = Vec::new();", " let input_len_range = Uniform::new(0, 1000);", " let mut rng = rand::rngs::SmallRng::from_entropy();", " for _ in 0..10_000 {\n orig_data.clear();\n encoded_data.clear();\n decode_buf.clear();", " let input_len = input_len_range.sample(&mut rng);", " for _ in 0..input_len {\n orig_data.push(rng.gen());\n }", " let config = random_config(&mut rng);\n encode_config_buf(&orig_data, config, &mut encoded_data);\n assert_encode_sanity(&encoded_data, config, input_len);", " decode_buf.resize(input_len, 0);", " // decode into the non-empty buf\n let decode_bytes_written =\n decode_config_slice(&encoded_data, config, &mut decode_buf[..]).unwrap();", " assert_eq!(orig_data.len(), decode_bytes_written);\n assert_eq!(orig_data, decode_buf);\n }\n }", " #[test]\n fn detect_invalid_last_symbol_two_bytes() {\n let decode =\n |input, forgiving| decode_config(input, STANDARD.decode_allow_trailing_bits(forgiving));", " // example from https://github.com/marshallpierce/rust-base64/issues/75\n assert!(decode(\"iYU=\", false).is_ok());\n // trailing 01\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, b'V')),\n decode(\"iYV=\", false)\n );\n assert_eq!(Ok(vec![137, 133]), decode(\"iYV=\", true));\n // trailing 10\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, b'W')),\n decode(\"iYW=\", false)\n );\n assert_eq!(Ok(vec![137, 133]), decode(\"iYV=\", true));\n // trailing 11\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, b'X')),\n decode(\"iYX=\", false)\n );\n assert_eq!(Ok(vec![137, 133]), decode(\"iYV=\", true));", " // also works when there are 2 quads in the last block\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(6, b'X')),\n decode(\"AAAAiYX=\", false)\n );\n assert_eq!(Ok(vec![0, 0, 0, 137, 133]), decode(\"AAAAiYX=\", true));\n }", " #[test]\n fn detect_invalid_last_symbol_one_byte() {\n // 0xFF -> \"/w==\", so all letters > w, 0-9, and '+', '/' should get InvalidLastSymbol", " assert!(decode(\"/w==\").is_ok());\n // trailing 01\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'x')), decode(\"/x==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'z')), decode(\"/z==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'0')), decode(\"/0==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'9')), decode(\"/9==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'+')), decode(\"/+==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'/')), decode(\"//==\"));", " // also works when there are 2 quads in the last block\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(5, b'x')),\n decode(\"AAAA/x==\")\n );\n }", " #[test]\n fn detect_invalid_last_symbol_every_possible_three_symbols() {\n let mut base64_to_bytes = ::std::collections::HashMap::new();", " let mut bytes = [0_u8; 2];\n for b1 in 0_u16..256 {\n bytes[0] = b1 as u8;\n for b2 in 0_u16..256 {\n bytes[1] = b2 as u8;\n let mut b64 = vec![0_u8; 4];\n assert_eq!(4, encode_config_slice(&bytes, STANDARD, &mut b64[..]));\n let mut v = ::std::vec::Vec::with_capacity(2);\n v.extend_from_slice(&bytes[..]);", " assert!(base64_to_bytes.insert(b64, v).is_none());\n }\n }", " // every possible combination of symbols must either decode to 2 bytes or get InvalidLastSymbol", " let mut symbols = [0_u8; 4];\n for &s1 in STANDARD.char_set.encode_table().iter() {\n symbols[0] = s1;\n for &s2 in STANDARD.char_set.encode_table().iter() {\n symbols[1] = s2;\n for &s3 in STANDARD.char_set.encode_table().iter() {\n symbols[2] = s3;\n symbols[3] = PAD_BYTE;", " match base64_to_bytes.get(&symbols[..]) {\n Some(bytes) => {\n assert_eq!(Ok(bytes.to_vec()), decode_config(&symbols, STANDARD))\n }\n None => assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, s3)),\n decode_config(&symbols[..], STANDARD)\n ),\n }\n }\n }\n }\n }", " #[test]\n fn detect_invalid_last_symbol_every_possible_two_symbols() {\n let mut base64_to_bytes = ::std::collections::HashMap::new();", " for b in 0_u16..256 {\n let mut b64 = vec![0_u8; 4];\n assert_eq!(4, encode_config_slice(&[b as u8], STANDARD, &mut b64[..]));\n let mut v = ::std::vec::Vec::with_capacity(1);\n v.push(b as u8);", " assert!(base64_to_bytes.insert(b64, v).is_none());\n }", " // every possible combination of symbols must either decode to 1 byte or get InvalidLastSymbol", " let mut symbols = [0_u8; 4];\n for &s1 in STANDARD.char_set.encode_table().iter() {\n symbols[0] = s1;\n for &s2 in STANDARD.char_set.encode_table().iter() {\n symbols[1] = s2;\n symbols[2] = PAD_BYTE;\n symbols[3] = PAD_BYTE;", " match base64_to_bytes.get(&symbols[..]) {\n Some(bytes) => {\n assert_eq!(Ok(bytes.to_vec()), decode_config(&symbols, STANDARD))\n }\n None => assert_eq!(\n Err(DecodeError::InvalidLastSymbol(1, s2)),\n decode_config(&symbols[..], STANDARD)\n ),\n }\n }\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "use crate::{tables, Config, PAD_BYTE};", "#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\nuse crate::STANDARD;\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\nuse alloc::vec::Vec;\nuse core::fmt;\n#[cfg(any(feature = \"std\", test))]\nuse std::error;", "// decode logic operates on chunks of 8 input bytes without padding\nconst INPUT_CHUNK_LEN: usize = 8;\nconst DECODED_CHUNK_LEN: usize = 6;\n// we read a u64 and write a u64, but a u64 of input only yields 6 bytes of output, so the last\n// 2 bytes of any output u64 should not be counted as written to (but must be available in a\n// slice).\nconst DECODED_CHUNK_SUFFIX: usize = 2;", "// how many u64's of input to handle at a time\nconst CHUNKS_PER_FAST_LOOP_BLOCK: usize = 4;\nconst INPUT_BLOCK_LEN: usize = CHUNKS_PER_FAST_LOOP_BLOCK * INPUT_CHUNK_LEN;\n// includes the trailing 2 bytes for the final u64 write\nconst DECODED_BLOCK_LEN: usize =\n CHUNKS_PER_FAST_LOOP_BLOCK * DECODED_CHUNK_LEN + DECODED_CHUNK_SUFFIX;", "/// Errors that can occur while decoding.\n#[derive(Clone, Debug, PartialEq, Eq)]\npub enum DecodeError {\n /// An invalid byte was found in the input. The offset and offending byte are provided.\n InvalidByte(usize, u8),\n /// The length of the input is invalid.\n /// A typical cause of this is stray trailing whitespace or other separator bytes.\n /// In the case where excess trailing bytes have produced an invalid length *and* the last byte\n /// is also an invalid base64 symbol (as would be the case for whitespace, etc), `InvalidByte`\n /// will be emitted instead of `InvalidLength` to make the issue easier to debug.\n InvalidLength,\n /// The last non-padding input symbol's encoded 6 bits have nonzero bits that will be discarded.\n /// This is indicative of corrupted or truncated Base64.\n /// Unlike InvalidByte, which reports symbols that aren't in the alphabet, this error is for\n /// symbols that are in the alphabet but represent nonsensical encodings.\n InvalidLastSymbol(usize, u8),\n}", "impl fmt::Display for DecodeError {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n match *self {\n DecodeError::InvalidByte(index, byte) => {\n write!(f, \"Invalid byte {}, offset {}.\", byte, index)\n }\n DecodeError::InvalidLength => write!(f, \"Encoded text cannot have a 6-bit remainder.\"),\n DecodeError::InvalidLastSymbol(index, byte) => {\n write!(f, \"Invalid last symbol {}, offset {}.\", byte, index)\n }\n }\n }\n}", "#[cfg(any(feature = \"std\", test))]\nimpl error::Error for DecodeError {\n fn description(&self) -> &str {\n match *self {\n DecodeError::InvalidByte(_, _) => \"invalid byte\",\n DecodeError::InvalidLength => \"invalid length\",\n DecodeError::InvalidLastSymbol(_, _) => \"invalid last symbol\",\n }\n }", " fn cause(&self) -> Option<&dyn error::Error> {\n None\n }\n}", "///Decode from string reference as octets.\n///Returns a Result containing a Vec<u8>.\n///Convenience `decode_config(input, base64::STANDARD);`.\n///\n///# Example\n///\n///```rust\n///extern crate base64;\n///\n///fn main() {\n/// let bytes = base64::decode(\"aGVsbG8gd29ybGQ=\").unwrap();\n/// println!(\"{:?}\", bytes);\n///}\n///```\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub fn decode<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, DecodeError> {\n decode_config(input, STANDARD)\n}", "///Decode from string reference as octets.\n///Returns a Result containing a Vec<u8>.\n///\n///# Example\n///\n///```rust\n///extern crate base64;\n///\n///fn main() {\n/// let bytes = base64::decode_config(\"aGVsbG8gd29ybGR+Cg==\", base64::STANDARD).unwrap();\n/// println!(\"{:?}\", bytes);\n///\n/// let bytes_url = base64::decode_config(\"aGVsbG8gaW50ZXJuZXR-Cg==\", base64::URL_SAFE).unwrap();\n/// println!(\"{:?}\", bytes_url);\n///}\n///```\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub fn decode_config<T: AsRef<[u8]>>(input: T, config: Config) -> Result<Vec<u8>, DecodeError> {\n let mut buffer = Vec::<u8>::with_capacity(input.as_ref().len() * 4 / 3);", " decode_config_buf(input, config, &mut buffer).map(|_| buffer)\n}", "///Decode from string reference as octets.\n///Writes into the supplied buffer to avoid allocation.\n///Returns a Result containing an empty tuple, aka ().\n///\n///# Example\n///\n///```rust\n///extern crate base64;\n///\n///fn main() {\n/// let mut buffer = Vec::<u8>::new();\n/// base64::decode_config_buf(\"aGVsbG8gd29ybGR+Cg==\", base64::STANDARD, &mut buffer).unwrap();\n/// println!(\"{:?}\", buffer);\n///\n/// buffer.clear();\n///\n/// base64::decode_config_buf(\"aGVsbG8gaW50ZXJuZXR-Cg==\", base64::URL_SAFE, &mut buffer)\n/// .unwrap();\n/// println!(\"{:?}\", buffer);\n///}\n///```\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub fn decode_config_buf<T: AsRef<[u8]>>(\n input: T,\n config: Config,\n buffer: &mut Vec<u8>,\n) -> Result<(), DecodeError> {\n let input_bytes = input.as_ref();", " let starting_output_len = buffer.len();", " let num_chunks = num_chunks(input_bytes);\n let decoded_len_estimate = num_chunks\n .checked_mul(DECODED_CHUNK_LEN)\n .and_then(|p| p.checked_add(starting_output_len))\n .expect(\"Overflow when calculating output buffer length\");\n buffer.resize(decoded_len_estimate, 0);", " let bytes_written;\n {\n let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];\n bytes_written = decode_helper(input_bytes, num_chunks, config, buffer_slice)?;\n }", " buffer.truncate(starting_output_len + bytes_written);", " Ok(())\n}", "/// Decode the input into the provided output slice.\n///\n/// This will not write any bytes past exactly what is decoded (no stray garbage bytes at the end).\n///\n/// If you don't know ahead of time what the decoded length should be, size your buffer with a\n/// conservative estimate for the decoded length of an input: 3 bytes of output for every 4 bytes of\n/// input, rounded up, or in other words `(input_len + 3) / 4 * 3`.\n///\n/// If the slice is not large enough, this will panic.\npub fn decode_config_slice<T: AsRef<[u8]>>(\n input: T,\n config: Config,\n output: &mut [u8],\n) -> Result<usize, DecodeError> {\n let input_bytes = input.as_ref();", " decode_helper(input_bytes, num_chunks(input_bytes), config, output)\n}", "/// Return the number of input chunks (including a possibly partial final chunk) in the input\nfn num_chunks(input: &[u8]) -> usize {\n input\n .len()\n .checked_add(INPUT_CHUNK_LEN - 1)\n .expect(\"Overflow when calculating number of chunks in input\")\n / INPUT_CHUNK_LEN\n}", "/// Helper to avoid duplicating num_chunks calculation, which is costly on short inputs.\n/// Returns the number of bytes written, or an error.\n// We're on the fragile edge of compiler heuristics here. If this is not inlined, slow. If this is\n// inlined(always), a different slow. plain ol' inline makes the benchmarks happiest at the moment,\n// but this is fragile and the best setting changes with only minor code modifications.\n#[inline]\nfn decode_helper(\n input: &[u8],\n num_chunks: usize,\n config: Config,\n output: &mut [u8],\n) -> Result<usize, DecodeError> {\n let char_set = config.char_set;\n let decode_table = char_set.decode_table();", " let remainder_len = input.len() % INPUT_CHUNK_LEN;", " // Because the fast decode loop writes in groups of 8 bytes (unrolled to\n // CHUNKS_PER_FAST_LOOP_BLOCK times 8 bytes, where possible) and outputs 8 bytes at a time (of\n // which only 6 are valid data), we need to be sure that we stop using the fast decode loop\n // soon enough that there will always be 2 more bytes of valid data written after that loop.\n let trailing_bytes_to_skip = match remainder_len {\n // if input is a multiple of the chunk size, ignore the last chunk as it may have padding,\n // and the fast decode logic cannot handle padding\n 0 => INPUT_CHUNK_LEN,\n // 1 and 5 trailing bytes are illegal: can't decode 6 bits of input into a byte\n 1 | 5 => {\n // trailing whitespace is so common that it's worth it to check the last byte to\n // possibly return a better error message\n if let Some(b) = input.last() {\n if *b != PAD_BYTE && decode_table[*b as usize] == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(input.len() - 1, *b));\n }\n }", " return Err(DecodeError::InvalidLength);\n }\n // This will decode to one output byte, which isn't enough to overwrite the 2 extra bytes\n // written by the fast decode loop. So, we have to ignore both these 2 bytes and the\n // previous chunk.\n 2 => INPUT_CHUNK_LEN + 2,\n // If this is 3 unpadded chars, then it would actually decode to 2 bytes. However, if this\n // is an erroneous 2 chars + 1 pad char that would decode to 1 byte, then it should fail\n // with an error, not panic from going past the bounds of the output slice, so we let it\n // use stage 3 + 4.\n 3 => INPUT_CHUNK_LEN + 3,\n // This can also decode to one output byte because it may be 2 input chars + 2 padding\n // chars, which would decode to 1 byte.\n 4 => INPUT_CHUNK_LEN + 4,\n // Everything else is a legal decode len (given that we don't require padding), and will\n // decode to at least 2 bytes of output.\n _ => remainder_len,\n };", " // rounded up to include partial chunks\n let mut remaining_chunks = num_chunks;", " let mut input_index = 0;\n let mut output_index = 0;", " {\n let length_of_fast_decode_chunks = input.len().saturating_sub(trailing_bytes_to_skip);", " // Fast loop, stage 1\n // manual unroll to CHUNKS_PER_FAST_LOOP_BLOCK of u64s to amortize slice bounds checks\n if let Some(max_start_index) = length_of_fast_decode_chunks.checked_sub(INPUT_BLOCK_LEN) {\n while input_index <= max_start_index {\n let input_slice = &input[input_index..(input_index + INPUT_BLOCK_LEN)];\n let output_slice = &mut output[output_index..(output_index + DECODED_BLOCK_LEN)];", " decode_chunk(\n &input_slice[0..],\n input_index,\n decode_table,\n &mut output_slice[0..],\n )?;\n decode_chunk(\n &input_slice[8..],\n input_index + 8,\n decode_table,\n &mut output_slice[6..],\n )?;\n decode_chunk(\n &input_slice[16..],\n input_index + 16,\n decode_table,\n &mut output_slice[12..],\n )?;\n decode_chunk(\n &input_slice[24..],\n input_index + 24,\n decode_table,\n &mut output_slice[18..],\n )?;", " input_index += INPUT_BLOCK_LEN;\n output_index += DECODED_BLOCK_LEN - DECODED_CHUNK_SUFFIX;\n remaining_chunks -= CHUNKS_PER_FAST_LOOP_BLOCK;\n }\n }", " // Fast loop, stage 2 (aka still pretty fast loop)\n // 8 bytes at a time for whatever we didn't do in stage 1.\n if let Some(max_start_index) = length_of_fast_decode_chunks.checked_sub(INPUT_CHUNK_LEN) {\n while input_index < max_start_index {\n decode_chunk(\n &input[input_index..(input_index + INPUT_CHUNK_LEN)],\n input_index,\n decode_table,\n &mut output\n [output_index..(output_index + DECODED_CHUNK_LEN + DECODED_CHUNK_SUFFIX)],\n )?;", " output_index += DECODED_CHUNK_LEN;\n input_index += INPUT_CHUNK_LEN;\n remaining_chunks -= 1;\n }\n }\n }", " // Stage 3\n // If input length was such that a chunk had to be deferred until after the fast loop\n // because decoding it would have produced 2 trailing bytes that wouldn't then be\n // overwritten, we decode that chunk here. This way is slower but doesn't write the 2\n // trailing bytes.\n // However, we still need to avoid the last chunk (partial or complete) because it could\n // have padding, so we always do 1 fewer to avoid the last chunk.\n for _ in 1..remaining_chunks {\n decode_chunk_precise(\n &input[input_index..],\n input_index,\n decode_table,\n &mut output[output_index..(output_index + DECODED_CHUNK_LEN)],\n )?;", " input_index += INPUT_CHUNK_LEN;\n output_index += DECODED_CHUNK_LEN;\n }", " // always have one more (possibly partial) block of 8 input\n debug_assert!(input.len() - input_index > 1 || input.is_empty());\n debug_assert!(input.len() - input_index <= 8);", " // Stage 4\n // Finally, decode any leftovers that aren't a complete input block of 8 bytes.\n // Use a u64 as a stack-resident 8 byte buffer.\n let mut leftover_bits: u64 = 0;\n let mut morsels_in_leftover = 0;\n let mut padding_bytes = 0;\n let mut first_padding_index: usize = 0;\n let mut last_symbol = 0_u8;\n let start_of_leftovers = input_index;\n for (i, b) in input[start_of_leftovers..].iter().enumerate() {\n // '=' padding\n if *b == PAD_BYTE {\n // There can be bad padding in a few ways:\n // 1 - Padding with non-padding characters after it\n // 2 - Padding after zero or one non-padding characters before it\n // in the current quad.\n // 3 - More than two characters of padding. If 3 or 4 padding chars\n // are in the same quad, that implies it will be caught by #2.\n // If it spreads from one quad to another, it will be caught by\n // #2 in the second quad.", " if i % 4 < 2 {\n // Check for case #2.\n let bad_padding_index = start_of_leftovers\n + if padding_bytes > 0 {\n // If we've already seen padding, report the first padding index.\n // This is to be consistent with the faster logic above: it will report an\n // error on the first padding character (since it doesn't expect to see\n // anything but actual encoded data).\n first_padding_index\n } else {\n // haven't seen padding before, just use where we are now\n i\n };\n return Err(DecodeError::InvalidByte(bad_padding_index, *b));\n }", " if padding_bytes == 0 {\n first_padding_index = i;\n }", " padding_bytes += 1;\n continue;\n }", " // Check for case #1.\n // To make '=' handling consistent with the main loop, don't allow\n // non-suffix '=' in trailing chunk either. Report error as first\n // erroneous padding.\n if padding_bytes > 0 {\n return Err(DecodeError::InvalidByte(\n start_of_leftovers + first_padding_index,\n PAD_BYTE,\n ));\n }\n last_symbol = *b;", " // can use up to 8 * 6 = 48 bits of the u64, if last chunk has no padding.\n // To minimize shifts, pack the leftovers from left to right.\n let shift = 64 - (morsels_in_leftover + 1) * 6;\n // tables are all 256 elements, lookup with a u8 index always succeeds\n let morsel = decode_table[*b as usize];\n if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(start_of_leftovers + i, *b));\n }", " leftover_bits |= (morsel as u64) << shift;\n morsels_in_leftover += 1;\n }", " let leftover_bits_ready_to_append = match morsels_in_leftover {\n 0 => 0,\n 2 => 8,\n 3 => 16,\n 4 => 24,\n 6 => 32,\n 7 => 40,\n 8 => 48,\n _ => unreachable!(\n \"Impossible: must only have 0 to 8 input bytes in last chunk, with no invalid lengths\"\n ),\n };", " // if there are bits set outside the bits we care about, last symbol encodes trailing bits that\n // will not be included in the output\n let mask = !0 >> leftover_bits_ready_to_append;\n if !config.decode_allow_trailing_bits && (leftover_bits & mask) != 0 {\n // last morsel is at `morsels_in_leftover` - 1\n return Err(DecodeError::InvalidLastSymbol(\n start_of_leftovers + morsels_in_leftover - 1,\n last_symbol,\n ));\n }", " let mut leftover_bits_appended_to_buf = 0;\n while leftover_bits_appended_to_buf < leftover_bits_ready_to_append {\n // `as` simply truncates the higher bits, which is what we want here\n let selected_bits = (leftover_bits >> (56 - leftover_bits_appended_to_buf)) as u8;\n output[output_index] = selected_bits;\n output_index += 1;", " leftover_bits_appended_to_buf += 8;\n }", " Ok(output_index)\n}", "#[inline]\nfn write_u64(output: &mut [u8], value: u64) {\n output[..8].copy_from_slice(&value.to_be_bytes());\n}\n", "#[cfg(feature = \"slow_but_safe\")]\nfn decode_aligned(b64ch: u8, decode_table: &[u8; 256]) -> u8 {\n let mut result: u8 = 0x00;\n let mut mask: u8;\n let idx: [u8;2] = [ b64ch % 64, b64ch % 64 + 64];\n for i in 0..2 {\n mask = 0xFF ^ (((idx[i] == b64ch) as i8 - 1) as u8);\n result = result | (decode_table[idx[i] as usize] & mask);\n }\n result\n}\n", "/// Decode 8 bytes of input into 6 bytes of output. 8 bytes of output will be written, but only the\n/// first 6 of those contain meaningful data.\n///\n/// `input` is the bytes to decode, of which the first 8 bytes will be processed.\n/// `index_at_start_of_input` is the offset in the overall input (used for reporting errors\n/// accurately)\n/// `decode_table` is the lookup table for the particular base64 alphabet.\n/// `output` will have its first 8 bytes overwritten, of which only the first 6 are valid decoded\n/// data.\n// yes, really inline (worth 30-50% speedup)\n#[inline(always)]\nfn decode_chunk(\n input: &[u8],\n index_at_start_of_input: usize,\n decode_table: &[u8; 256],\n output: &mut [u8],\n) -> Result<(), DecodeError> {\n let mut accum: u64;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[0] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[0], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(index_at_start_of_input, input[0]));\n }\n accum = (morsel as u64) << 58;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[1] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[1], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 1,\n input[1],\n ));\n }\n accum |= (morsel as u64) << 52;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[2] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[2], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 2,\n input[2],\n ));\n }\n accum |= (morsel as u64) << 46;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[3] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[3], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 3,\n input[3],\n ));\n }\n accum |= (morsel as u64) << 40;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[4] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[4], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 4,\n input[4],\n ));\n }\n accum |= (morsel as u64) << 34;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[5] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[5], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 5,\n input[5],\n ));\n }\n accum |= (morsel as u64) << 28;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[6] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[6], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 6,\n input[6],\n ));\n }\n accum |= (morsel as u64) << 22;\n", " #[cfg(not(feature = \"slow_but_safe\"))]", " let morsel = decode_table[input[7] as usize];", " #[cfg(feature = \"slow_but_safe\")]\n let morsel = decode_aligned(input[7], decode_table);", " if morsel == tables::INVALID_VALUE {\n return Err(DecodeError::InvalidByte(\n index_at_start_of_input + 7,\n input[7],\n ));\n }\n accum |= (morsel as u64) << 16;", " write_u64(output, accum);", " Ok(())\n}", "/// Decode an 8-byte chunk, but only write the 6 bytes actually decoded instead of including 2\n/// trailing garbage bytes.\n#[inline]\nfn decode_chunk_precise(\n input: &[u8],\n index_at_start_of_input: usize,\n decode_table: &[u8; 256],\n output: &mut [u8],\n) -> Result<(), DecodeError> {\n let mut tmp_buf = [0_u8; 8];", " decode_chunk(\n input,\n index_at_start_of_input,\n decode_table,\n &mut tmp_buf[..],\n )?;", " output[0..6].copy_from_slice(&tmp_buf[0..6]);", " Ok(())\n}", "#[cfg(test)]\nmod tests {\n use super::*;\n use crate::{\n encode::encode_config_buf,\n encode::encode_config_slice,\n tests::{assert_encode_sanity, random_config},\n };", " use rand::{\n distributions::{Distribution, Uniform},\n FromEntropy, Rng,\n };", " #[test]\n fn decode_chunk_precise_writes_only_6_bytes() {\n let input = b\"Zm9vYmFy\"; // \"foobar\"\n let mut output = [0_u8, 1, 2, 3, 4, 5, 6, 7];\n decode_chunk_precise(&input[..], 0, tables::STANDARD_DECODE, &mut output).unwrap();\n assert_eq!(&vec![b'f', b'o', b'o', b'b', b'a', b'r', 6, 7], &output);\n }", " #[test]\n fn decode_chunk_writes_8_bytes() {\n let input = b\"Zm9vYmFy\"; // \"foobar\"\n let mut output = [0_u8, 1, 2, 3, 4, 5, 6, 7];\n decode_chunk(&input[..], 0, tables::STANDARD_DECODE, &mut output).unwrap();\n assert_eq!(&vec![b'f', b'o', b'o', b'b', b'a', b'r', 0, 0], &output);\n }", " #[test]\n fn decode_into_nonempty_vec_doesnt_clobber_existing_prefix() {\n let mut orig_data = Vec::new();\n let mut encoded_data = String::new();\n let mut decoded_with_prefix = Vec::new();\n let mut decoded_without_prefix = Vec::new();\n let mut prefix = Vec::new();", " let prefix_len_range = Uniform::new(0, 1000);\n let input_len_range = Uniform::new(0, 1000);", " let mut rng = rand::rngs::SmallRng::from_entropy();", " for _ in 0..10_000 {\n orig_data.clear();\n encoded_data.clear();\n decoded_with_prefix.clear();\n decoded_without_prefix.clear();\n prefix.clear();", " let input_len = input_len_range.sample(&mut rng);", " for _ in 0..input_len {\n orig_data.push(rng.gen());\n }", " let config = random_config(&mut rng);\n encode_config_buf(&orig_data, config, &mut encoded_data);\n assert_encode_sanity(&encoded_data, config, input_len);", " let prefix_len = prefix_len_range.sample(&mut rng);", " // fill the buf with a prefix\n for _ in 0..prefix_len {\n prefix.push(rng.gen());\n }", " decoded_with_prefix.resize(prefix_len, 0);\n decoded_with_prefix.copy_from_slice(&prefix);", " // decode into the non-empty buf\n decode_config_buf(&encoded_data, config, &mut decoded_with_prefix).unwrap();\n // also decode into the empty buf\n decode_config_buf(&encoded_data, config, &mut decoded_without_prefix).unwrap();", " assert_eq!(\n prefix_len + decoded_without_prefix.len(),\n decoded_with_prefix.len()\n );\n assert_eq!(orig_data, decoded_without_prefix);", " // append plain decode onto prefix\n prefix.append(&mut decoded_without_prefix);", " assert_eq!(prefix, decoded_with_prefix);\n }\n }", " #[test]\n fn decode_into_slice_doesnt_clobber_existing_prefix_or_suffix() {\n let mut orig_data = Vec::new();\n let mut encoded_data = String::new();\n let mut decode_buf = Vec::new();\n let mut decode_buf_copy: Vec<u8> = Vec::new();", " let input_len_range = Uniform::new(0, 1000);", " let mut rng = rand::rngs::SmallRng::from_entropy();", " for _ in 0..10_000 {\n orig_data.clear();\n encoded_data.clear();\n decode_buf.clear();\n decode_buf_copy.clear();", " let input_len = input_len_range.sample(&mut rng);", " for _ in 0..input_len {\n orig_data.push(rng.gen());\n }", " let config = random_config(&mut rng);\n encode_config_buf(&orig_data, config, &mut encoded_data);\n assert_encode_sanity(&encoded_data, config, input_len);", " // fill the buffer with random garbage, long enough to have some room before and after\n for _ in 0..5000 {\n decode_buf.push(rng.gen());\n }", " // keep a copy for later comparison\n decode_buf_copy.extend(decode_buf.iter());", " let offset = 1000;", " // decode into the non-empty buf\n let decode_bytes_written =\n decode_config_slice(&encoded_data, config, &mut decode_buf[offset..]).unwrap();", " assert_eq!(orig_data.len(), decode_bytes_written);\n assert_eq!(\n orig_data,\n &decode_buf[offset..(offset + decode_bytes_written)]\n );\n assert_eq!(&decode_buf_copy[0..offset], &decode_buf[0..offset]);\n assert_eq!(\n &decode_buf_copy[offset + decode_bytes_written..],\n &decode_buf[offset + decode_bytes_written..]\n );\n }\n }", " #[test]\n fn decode_into_slice_fits_in_precisely_sized_slice() {\n let mut orig_data = Vec::new();\n let mut encoded_data = String::new();\n let mut decode_buf = Vec::new();", " let input_len_range = Uniform::new(0, 1000);", " let mut rng = rand::rngs::SmallRng::from_entropy();", " for _ in 0..10_000 {\n orig_data.clear();\n encoded_data.clear();\n decode_buf.clear();", " let input_len = input_len_range.sample(&mut rng);", " for _ in 0..input_len {\n orig_data.push(rng.gen());\n }", " let config = random_config(&mut rng);\n encode_config_buf(&orig_data, config, &mut encoded_data);\n assert_encode_sanity(&encoded_data, config, input_len);", " decode_buf.resize(input_len, 0);", " // decode into the non-empty buf\n let decode_bytes_written =\n decode_config_slice(&encoded_data, config, &mut decode_buf[..]).unwrap();", " assert_eq!(orig_data.len(), decode_bytes_written);\n assert_eq!(orig_data, decode_buf);\n }\n }", " #[test]\n fn detect_invalid_last_symbol_two_bytes() {\n let decode =\n |input, forgiving| decode_config(input, STANDARD.decode_allow_trailing_bits(forgiving));", " // example from https://github.com/marshallpierce/rust-base64/issues/75\n assert!(decode(\"iYU=\", false).is_ok());\n // trailing 01\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, b'V')),\n decode(\"iYV=\", false)\n );\n assert_eq!(Ok(vec![137, 133]), decode(\"iYV=\", true));\n // trailing 10\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, b'W')),\n decode(\"iYW=\", false)\n );\n assert_eq!(Ok(vec![137, 133]), decode(\"iYV=\", true));\n // trailing 11\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, b'X')),\n decode(\"iYX=\", false)\n );\n assert_eq!(Ok(vec![137, 133]), decode(\"iYV=\", true));", " // also works when there are 2 quads in the last block\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(6, b'X')),\n decode(\"AAAAiYX=\", false)\n );\n assert_eq!(Ok(vec![0, 0, 0, 137, 133]), decode(\"AAAAiYX=\", true));\n }", " #[test]\n fn detect_invalid_last_symbol_one_byte() {\n // 0xFF -> \"/w==\", so all letters > w, 0-9, and '+', '/' should get InvalidLastSymbol", " assert!(decode(\"/w==\").is_ok());\n // trailing 01\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'x')), decode(\"/x==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'z')), decode(\"/z==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'0')), decode(\"/0==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'9')), decode(\"/9==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'+')), decode(\"/+==\"));\n assert_eq!(Err(DecodeError::InvalidLastSymbol(1, b'/')), decode(\"//==\"));", " // also works when there are 2 quads in the last block\n assert_eq!(\n Err(DecodeError::InvalidLastSymbol(5, b'x')),\n decode(\"AAAA/x==\")\n );\n }", " #[test]\n fn detect_invalid_last_symbol_every_possible_three_symbols() {\n let mut base64_to_bytes = ::std::collections::HashMap::new();", " let mut bytes = [0_u8; 2];\n for b1 in 0_u16..256 {\n bytes[0] = b1 as u8;\n for b2 in 0_u16..256 {\n bytes[1] = b2 as u8;\n let mut b64 = vec![0_u8; 4];\n assert_eq!(4, encode_config_slice(&bytes, STANDARD, &mut b64[..]));\n let mut v = ::std::vec::Vec::with_capacity(2);\n v.extend_from_slice(&bytes[..]);", " assert!(base64_to_bytes.insert(b64, v).is_none());\n }\n }", " // every possible combination of symbols must either decode to 2 bytes or get InvalidLastSymbol", " let mut symbols = [0_u8; 4];\n for &s1 in STANDARD.char_set.encode_table().iter() {\n symbols[0] = s1;\n for &s2 in STANDARD.char_set.encode_table().iter() {\n symbols[1] = s2;\n for &s3 in STANDARD.char_set.encode_table().iter() {\n symbols[2] = s3;\n symbols[3] = PAD_BYTE;", " match base64_to_bytes.get(&symbols[..]) {\n Some(bytes) => {\n assert_eq!(Ok(bytes.to_vec()), decode_config(&symbols, STANDARD))\n }\n None => assert_eq!(\n Err(DecodeError::InvalidLastSymbol(2, s3)),\n decode_config(&symbols[..], STANDARD)\n ),\n }\n }\n }\n }\n }", " #[test]\n fn detect_invalid_last_symbol_every_possible_two_symbols() {\n let mut base64_to_bytes = ::std::collections::HashMap::new();", " for b in 0_u16..256 {\n let mut b64 = vec![0_u8; 4];\n assert_eq!(4, encode_config_slice(&[b as u8], STANDARD, &mut b64[..]));\n let mut v = ::std::vec::Vec::with_capacity(1);\n v.push(b as u8);", " assert!(base64_to_bytes.insert(b64, v).is_none());\n }", " // every possible combination of symbols must either decode to 1 byte or get InvalidLastSymbol", " let mut symbols = [0_u8; 4];\n for &s1 in STANDARD.char_set.encode_table().iter() {\n symbols[0] = s1;\n for &s2 in STANDARD.char_set.encode_table().iter() {\n symbols[1] = s2;\n symbols[2] = PAD_BYTE;\n symbols[3] = PAD_BYTE;", " match base64_to_bytes.get(&symbols[..]) {\n Some(bytes) => {\n assert_eq!(Ok(bytes.to_vec()), decode_config(&symbols, STANDARD))\n }\n None => assert_eq!(\n Err(DecodeError::InvalidLastSymbol(1, s2)),\n decode_config(&symbols[..], STANDARD)\n ),\n }\n }\n }\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "//! # Configs\n//!\n//! There isn't just one type of Base64; that would be too simple. You need to choose a character\n//! set (standard, URL-safe, etc) and padding suffix (yes/no).\n//! The `Config` struct encapsulates this info. There are some common configs included: `STANDARD`,\n//! `URL_SAFE`, etc. You can also make your own `Config` if needed.\n//!\n//! The functions that don't have `config` in the name (e.g. `encode()` and `decode()`) use the\n//! `STANDARD` config .\n//!\n//! The functions that write to a slice (the ones that end in `_slice`) are generally the fastest\n//! because they don't need to resize anything. If it fits in your workflow and you care about\n//! performance, keep using the same buffer (growing as need be) and use the `_slice` methods for\n//! the best performance.\n//!\n//! # Encoding\n//!\n//! Several different encoding functions are available to you depending on your desire for\n//! convenience vs performance.\n//!\n//! | Function | Output | Allocates |\n//! | ----------------------- | ---------------------------- | ------------------------------ |\n//! | `encode` | Returns a new `String` | Always |\n//! | `encode_config` | Returns a new `String` | Always |\n//! | `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |\n//! | `encode_config_slice` | Writes to provided `&[u8]` | Never |\n//!\n//! All of the encoding functions that take a `Config` will pad as per the config.\n//!\n//! # Decoding\n//!\n//! Just as for encoding, there are different decoding functions available.\n//!\n//! | Function | Output | Allocates |\n//! | ----------------------- | ----------------------------- | ------------------------------ |\n//! | `decode` | Returns a new `Vec<u8>` | Always |\n//! | `decode_config` | Returns a new `Vec<u8>` | Always |\n//! | `decode_config_buf` | Appends to provided `Vec<u8>` | Only if `Vec` needs to grow |\n//! | `decode_config_slice` | Writes to provided `&[u8]` | Never |\n//!\n//! Unlike encoding, where all possible input is valid, decoding can fail (see `DecodeError`).\n//!\n//! Input can be invalid because it has invalid characters or invalid padding. (No padding at all is\n//! valid, but excess padding is not.) Whitespace in the input is invalid.\n//!\n//! # `Read` and `Write`\n//!\n//! To map a `Read` of b64 bytes to the decoded bytes, wrap a reader (file, network socket, etc)\n//! with `base64::read::DecoderReader`. To write raw bytes and have them b64 encoded on the fly,\n//! wrap a writer with `base64::write::EncoderWriter`. There is some performance overhead (15% or\n//! so) because of the necessary buffer shuffling -- still fast enough that almost nobody cares.\n//! Also, these implementations do not heap allocate.\n//!\n//! # Panics\n//!\n//! If length calculations result in overflowing `usize`, a panic will result.\n//!\n//! The `_slice` flavors of encode or decode will panic if the provided output slice is too small,", "#![cfg_attr(feature = \"cargo-clippy\", allow(clippy::cast_lossless))]\n#![deny(\n missing_docs,\n trivial_casts,\n trivial_numeric_casts,\n unused_extern_crates,\n unused_import_braces,\n unused_results,\n variant_size_differences,\n warnings\n)]\n#![forbid(unsafe_code)]\n#![cfg_attr(not(any(feature = \"std\", test)), no_std)]", "#[cfg(all(feature = \"alloc\", not(any(feature = \"std\", test))))]\nextern crate alloc;\n#[cfg(any(feature = \"std\", test))]\nextern crate std as alloc;", "mod chunked_encoder;\npub mod display;\n#[cfg(any(feature = \"std\", test))]\npub mod read;\nmod tables;\n#[cfg(any(feature = \"std\", test))]\npub mod write;", "mod encode;\npub use crate::encode::encode_config_slice;\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub use crate::encode::{encode, encode_config, encode_config_buf};", "mod decode;\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub use crate::decode::{decode, decode_config, decode_config_buf};\npub use crate::decode::{decode_config_slice, DecodeError};", "#[cfg(test)]\nmod tests;", "/// Available encoding character sets\n#[derive(Clone, Copy, Debug)]\npub enum CharacterSet {\n /// The standard character set (uses `+` and `/`).\n ///\n /// See [RFC 3548](https://tools.ietf.org/html/rfc3548#section-3).\n Standard,\n /// The URL safe character set (uses `-` and `_`).\n ///\n /// See [RFC 3548](https://tools.ietf.org/html/rfc3548#section-4).\n UrlSafe,\n /// The `crypt(3)` character set (uses `./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`).\n ///\n /// Not standardized, but folk wisdom on the net asserts that this alphabet is what crypt uses.\n Crypt,\n /// The bcrypt character set (uses `./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`).\n Bcrypt,\n /// The character set used in IMAP-modified UTF-7 (uses `+` and `,`).\n ///\n /// See [RFC 3501](https://tools.ietf.org/html/rfc3501#section-5.1.3)\n ImapMutf7,\n /// The character set used in BinHex 4.0 files.\n ///\n /// See [BinHex 4.0 Definition](http://files.stairways.com/other/binhex-40-specs-info.txt)\n BinHex,\n}", "impl CharacterSet {\n fn encode_table(self) -> &'static [u8; 64] {\n match self {\n CharacterSet::Standard => tables::STANDARD_ENCODE,\n CharacterSet::UrlSafe => tables::URL_SAFE_ENCODE,\n CharacterSet::Crypt => tables::CRYPT_ENCODE,\n CharacterSet::Bcrypt => tables::BCRYPT_ENCODE,\n CharacterSet::ImapMutf7 => tables::IMAP_MUTF7_ENCODE,\n CharacterSet::BinHex => tables::BINHEX_ENCODE,\n }\n }", " fn decode_table(self) -> &'static [u8; 256] {\n match self {", " CharacterSet::Standard => tables::STANDARD_DECODE,\n CharacterSet::UrlSafe => tables::URL_SAFE_DECODE,\n CharacterSet::Crypt => tables::CRYPT_DECODE,\n CharacterSet::Bcrypt => tables::BCRYPT_DECODE,\n CharacterSet::ImapMutf7 => tables::IMAP_MUTF7_DECODE,\n CharacterSet::BinHex => tables::BINHEX_DECODE,", " }\n }\n}", "/// Contains configuration parameters for base64 encoding\n#[derive(Clone, Copy, Debug)]\npub struct Config {\n /// Character set to use\n char_set: CharacterSet,\n /// True to pad output with `=` characters\n pad: bool,\n /// True to ignore excess nonzero bits in the last few symbols, otherwise an error is returned.\n decode_allow_trailing_bits: bool,\n}", "impl Config {\n /// Create a new `Config`.\n pub const fn new(char_set: CharacterSet, pad: bool) -> Config {\n Config {\n char_set,\n pad,\n decode_allow_trailing_bits: false,\n }\n }", " /// Sets whether to pad output with `=` characters.\n pub const fn pad(self, pad: bool) -> Config {\n Config { pad, ..self }\n }", " /// Sets whether to emit errors for nonzero trailing bits.\n ///\n /// This is useful when implementing\n /// [forgiving-base64 decode](https://infra.spec.whatwg.org/#forgiving-base64-decode).\n pub const fn decode_allow_trailing_bits(self, allow: bool) -> Config {\n Config {\n decode_allow_trailing_bits: allow,\n ..self\n }\n }\n}", "/// Standard character set with padding.\npub const STANDARD: Config = Config {\n char_set: CharacterSet::Standard,\n pad: true,\n decode_allow_trailing_bits: false,\n};", "/// Standard character set without padding.\npub const STANDARD_NO_PAD: Config = Config {\n char_set: CharacterSet::Standard,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// URL-safe character set with padding\npub const URL_SAFE: Config = Config {\n char_set: CharacterSet::UrlSafe,\n pad: true,\n decode_allow_trailing_bits: false,\n};", "/// URL-safe character set without padding\npub const URL_SAFE_NO_PAD: Config = Config {\n char_set: CharacterSet::UrlSafe,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// As per `crypt(3)` requirements\npub const CRYPT: Config = Config {\n char_set: CharacterSet::Crypt,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// Bcrypt character set\npub const BCRYPT: Config = Config {\n char_set: CharacterSet::Bcrypt,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// IMAP modified UTF-7 requirements\npub const IMAP_MUTF7: Config = Config {\n char_set: CharacterSet::ImapMutf7,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// BinHex character set\npub const BINHEX: Config = Config {\n char_set: CharacterSet::BinHex,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "const PAD_BYTE: u8 = b'=';" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "//! # Configs\n//!\n//! There isn't just one type of Base64; that would be too simple. You need to choose a character\n//! set (standard, URL-safe, etc) and padding suffix (yes/no).\n//! The `Config` struct encapsulates this info. There are some common configs included: `STANDARD`,\n//! `URL_SAFE`, etc. You can also make your own `Config` if needed.\n//!\n//! The functions that don't have `config` in the name (e.g. `encode()` and `decode()`) use the\n//! `STANDARD` config .\n//!\n//! The functions that write to a slice (the ones that end in `_slice`) are generally the fastest\n//! because they don't need to resize anything. If it fits in your workflow and you care about\n//! performance, keep using the same buffer (growing as need be) and use the `_slice` methods for\n//! the best performance.\n//!\n//! # Encoding\n//!\n//! Several different encoding functions are available to you depending on your desire for\n//! convenience vs performance.\n//!\n//! | Function | Output | Allocates |\n//! | ----------------------- | ---------------------------- | ------------------------------ |\n//! | `encode` | Returns a new `String` | Always |\n//! | `encode_config` | Returns a new `String` | Always |\n//! | `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |\n//! | `encode_config_slice` | Writes to provided `&[u8]` | Never |\n//!\n//! All of the encoding functions that take a `Config` will pad as per the config.\n//!\n//! # Decoding\n//!\n//! Just as for encoding, there are different decoding functions available.\n//!\n//! | Function | Output | Allocates |\n//! | ----------------------- | ----------------------------- | ------------------------------ |\n//! | `decode` | Returns a new `Vec<u8>` | Always |\n//! | `decode_config` | Returns a new `Vec<u8>` | Always |\n//! | `decode_config_buf` | Appends to provided `Vec<u8>` | Only if `Vec` needs to grow |\n//! | `decode_config_slice` | Writes to provided `&[u8]` | Never |\n//!\n//! Unlike encoding, where all possible input is valid, decoding can fail (see `DecodeError`).\n//!\n//! Input can be invalid because it has invalid characters or invalid padding. (No padding at all is\n//! valid, but excess padding is not.) Whitespace in the input is invalid.\n//!\n//! # `Read` and `Write`\n//!\n//! To map a `Read` of b64 bytes to the decoded bytes, wrap a reader (file, network socket, etc)\n//! with `base64::read::DecoderReader`. To write raw bytes and have them b64 encoded on the fly,\n//! wrap a writer with `base64::write::EncoderWriter`. There is some performance overhead (15% or\n//! so) because of the necessary buffer shuffling -- still fast enough that almost nobody cares.\n//! Also, these implementations do not heap allocate.\n//!\n//! # Panics\n//!\n//! If length calculations result in overflowing `usize`, a panic will result.\n//!\n//! The `_slice` flavors of encode or decode will panic if the provided output slice is too small,", "#![cfg_attr(feature = \"cargo-clippy\", allow(clippy::cast_lossless))]\n#![deny(\n missing_docs,\n trivial_casts,\n trivial_numeric_casts,\n unused_extern_crates,\n unused_import_braces,\n unused_results,\n variant_size_differences,\n warnings\n)]\n#![forbid(unsafe_code)]\n#![cfg_attr(not(any(feature = \"std\", test)), no_std)]", "#[cfg(all(feature = \"alloc\", not(any(feature = \"std\", test))))]\nextern crate alloc;\n#[cfg(any(feature = \"std\", test))]\nextern crate std as alloc;", "mod chunked_encoder;\npub mod display;\n#[cfg(any(feature = \"std\", test))]\npub mod read;\nmod tables;\n#[cfg(any(feature = \"std\", test))]\npub mod write;", "mod encode;\npub use crate::encode::encode_config_slice;\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub use crate::encode::{encode, encode_config, encode_config_buf};", "mod decode;\n#[cfg(any(feature = \"alloc\", feature = \"std\", test))]\npub use crate::decode::{decode, decode_config, decode_config_buf};\npub use crate::decode::{decode_config_slice, DecodeError};", "#[cfg(test)]\nmod tests;", "/// Available encoding character sets\n#[derive(Clone, Copy, Debug)]\npub enum CharacterSet {\n /// The standard character set (uses `+` and `/`).\n ///\n /// See [RFC 3548](https://tools.ietf.org/html/rfc3548#section-3).\n Standard,\n /// The URL safe character set (uses `-` and `_`).\n ///\n /// See [RFC 3548](https://tools.ietf.org/html/rfc3548#section-4).\n UrlSafe,\n /// The `crypt(3)` character set (uses `./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`).\n ///\n /// Not standardized, but folk wisdom on the net asserts that this alphabet is what crypt uses.\n Crypt,\n /// The bcrypt character set (uses `./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`).\n Bcrypt,\n /// The character set used in IMAP-modified UTF-7 (uses `+` and `,`).\n ///\n /// See [RFC 3501](https://tools.ietf.org/html/rfc3501#section-5.1.3)\n ImapMutf7,\n /// The character set used in BinHex 4.0 files.\n ///\n /// See [BinHex 4.0 Definition](http://files.stairways.com/other/binhex-40-specs-info.txt)\n BinHex,\n}", "impl CharacterSet {\n fn encode_table(self) -> &'static [u8; 64] {\n match self {\n CharacterSet::Standard => tables::STANDARD_ENCODE,\n CharacterSet::UrlSafe => tables::URL_SAFE_ENCODE,\n CharacterSet::Crypt => tables::CRYPT_ENCODE,\n CharacterSet::Bcrypt => tables::BCRYPT_ENCODE,\n CharacterSet::ImapMutf7 => tables::IMAP_MUTF7_ENCODE,\n CharacterSet::BinHex => tables::BINHEX_ENCODE,\n }\n }", " fn decode_table(self) -> &'static [u8; 256] {\n match self {", " CharacterSet::Standard => &tables::STANDARD_DECODE_HOLDER.data,\n CharacterSet::UrlSafe => &tables::URL_SAFE_DECODE_HOLDER.data,\n CharacterSet::Crypt => &tables::CRYPT_DECODE_HOLDER.data,\n CharacterSet::Bcrypt => &tables::BCRYPT_DECODE_HOLDER.data,\n CharacterSet::ImapMutf7 => &tables::IMAP_MUTF7_DECODE_HOLDER.data,\n CharacterSet::BinHex => &tables::BINHEX_DECODE_HOLDER.data,", " }\n }\n}", "/// Contains configuration parameters for base64 encoding\n#[derive(Clone, Copy, Debug)]\npub struct Config {\n /// Character set to use\n char_set: CharacterSet,\n /// True to pad output with `=` characters\n pad: bool,\n /// True to ignore excess nonzero bits in the last few symbols, otherwise an error is returned.\n decode_allow_trailing_bits: bool,\n}", "impl Config {\n /// Create a new `Config`.\n pub const fn new(char_set: CharacterSet, pad: bool) -> Config {\n Config {\n char_set,\n pad,\n decode_allow_trailing_bits: false,\n }\n }", " /// Sets whether to pad output with `=` characters.\n pub const fn pad(self, pad: bool) -> Config {\n Config { pad, ..self }\n }", " /// Sets whether to emit errors for nonzero trailing bits.\n ///\n /// This is useful when implementing\n /// [forgiving-base64 decode](https://infra.spec.whatwg.org/#forgiving-base64-decode).\n pub const fn decode_allow_trailing_bits(self, allow: bool) -> Config {\n Config {\n decode_allow_trailing_bits: allow,\n ..self\n }\n }\n}", "/// Standard character set with padding.\npub const STANDARD: Config = Config {\n char_set: CharacterSet::Standard,\n pad: true,\n decode_allow_trailing_bits: false,\n};", "/// Standard character set without padding.\npub const STANDARD_NO_PAD: Config = Config {\n char_set: CharacterSet::Standard,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// URL-safe character set with padding\npub const URL_SAFE: Config = Config {\n char_set: CharacterSet::UrlSafe,\n pad: true,\n decode_allow_trailing_bits: false,\n};", "/// URL-safe character set without padding\npub const URL_SAFE_NO_PAD: Config = Config {\n char_set: CharacterSet::UrlSafe,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// As per `crypt(3)` requirements\npub const CRYPT: Config = Config {\n char_set: CharacterSet::Crypt,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// Bcrypt character set\npub const BCRYPT: Config = Config {\n char_set: CharacterSet::Bcrypt,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// IMAP modified UTF-7 requirements\npub const IMAP_MUTF7: Config = Config {\n char_set: CharacterSet::ImapMutf7,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "/// BinHex character set\npub const BINHEX: Config = Config {\n char_set: CharacterSet::BinHex,\n pad: false,\n decode_allow_trailing_bits: false,\n};", "const PAD_BYTE: u8 = b'=';" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "", "pub const INVALID_VALUE: u8 = 255;\n#[rustfmt::skip]\npub const STANDARD_ENCODE: &[u8; 64] = &[\n 65, // input 0 (0x0) => 'A' (0x41)\n 66, // input 1 (0x1) => 'B' (0x42)\n 67, // input 2 (0x2) => 'C' (0x43)\n 68, // input 3 (0x3) => 'D' (0x44)\n 69, // input 4 (0x4) => 'E' (0x45)\n 70, // input 5 (0x5) => 'F' (0x46)\n 71, // input 6 (0x6) => 'G' (0x47)\n 72, // input 7 (0x7) => 'H' (0x48)\n 73, // input 8 (0x8) => 'I' (0x49)\n 74, // input 9 (0x9) => 'J' (0x4A)\n 75, // input 10 (0xA) => 'K' (0x4B)\n 76, // input 11 (0xB) => 'L' (0x4C)\n 77, // input 12 (0xC) => 'M' (0x4D)\n 78, // input 13 (0xD) => 'N' (0x4E)\n 79, // input 14 (0xE) => 'O' (0x4F)\n 80, // input 15 (0xF) => 'P' (0x50)\n 81, // input 16 (0x10) => 'Q' (0x51)\n 82, // input 17 (0x11) => 'R' (0x52)\n 83, // input 18 (0x12) => 'S' (0x53)\n 84, // input 19 (0x13) => 'T' (0x54)\n 85, // input 20 (0x14) => 'U' (0x55)\n 86, // input 21 (0x15) => 'V' (0x56)\n 87, // input 22 (0x16) => 'W' (0x57)\n 88, // input 23 (0x17) => 'X' (0x58)\n 89, // input 24 (0x18) => 'Y' (0x59)\n 90, // input 25 (0x19) => 'Z' (0x5A)\n 97, // input 26 (0x1A) => 'a' (0x61)\n 98, // input 27 (0x1B) => 'b' (0x62)\n 99, // input 28 (0x1C) => 'c' (0x63)\n 100, // input 29 (0x1D) => 'd' (0x64)\n 101, // input 30 (0x1E) => 'e' (0x65)\n 102, // input 31 (0x1F) => 'f' (0x66)\n 103, // input 32 (0x20) => 'g' (0x67)\n 104, // input 33 (0x21) => 'h' (0x68)\n 105, // input 34 (0x22) => 'i' (0x69)\n 106, // input 35 (0x23) => 'j' (0x6A)\n 107, // input 36 (0x24) => 'k' (0x6B)\n 108, // input 37 (0x25) => 'l' (0x6C)\n 109, // input 38 (0x26) => 'm' (0x6D)\n 110, // input 39 (0x27) => 'n' (0x6E)\n 111, // input 40 (0x28) => 'o' (0x6F)\n 112, // input 41 (0x29) => 'p' (0x70)\n 113, // input 42 (0x2A) => 'q' (0x71)\n 114, // input 43 (0x2B) => 'r' (0x72)\n 115, // input 44 (0x2C) => 's' (0x73)\n 116, // input 45 (0x2D) => 't' (0x74)\n 117, // input 46 (0x2E) => 'u' (0x75)\n 118, // input 47 (0x2F) => 'v' (0x76)\n 119, // input 48 (0x30) => 'w' (0x77)\n 120, // input 49 (0x31) => 'x' (0x78)\n 121, // input 50 (0x32) => 'y' (0x79)\n 122, // input 51 (0x33) => 'z' (0x7A)\n 48, // input 52 (0x34) => '0' (0x30)\n 49, // input 53 (0x35) => '1' (0x31)\n 50, // input 54 (0x36) => '2' (0x32)\n 51, // input 55 (0x37) => '3' (0x33)\n 52, // input 56 (0x38) => '4' (0x34)\n 53, // input 57 (0x39) => '5' (0x35)\n 54, // input 58 (0x3A) => '6' (0x36)\n 55, // input 59 (0x3B) => '7' (0x37)\n 56, // input 60 (0x3C) => '8' (0x38)\n 57, // input 61 (0x3D) => '9' (0x39)\n 43, // input 62 (0x3E) => '+' (0x2B)\n 47, // input 63 (0x3F) => '/' (0x2F)\n];\n#[rustfmt::skip]\npub const STANDARD_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n 62, // input 43 (0x2B char '+') => 62 (0x3E)\n INVALID_VALUE, // input 44 (0x2C)\n INVALID_VALUE, // input 45 (0x2D)\n INVALID_VALUE, // input 46 (0x2E)\n 63, // input 47 (0x2F char '/') => 63 (0x3F)\n 52, // input 48 (0x30 char '0') => 52 (0x34)\n 53, // input 49 (0x31 char '1') => 53 (0x35)\n 54, // input 50 (0x32 char '2') => 54 (0x36)\n 55, // input 51 (0x33 char '3') => 55 (0x37)\n 56, // input 52 (0x34 char '4') => 56 (0x38)\n 57, // input 53 (0x35 char '5') => 57 (0x39)\n 58, // input 54 (0x36 char '6') => 58 (0x3A)\n 59, // input 55 (0x37 char '7') => 59 (0x3B)\n 60, // input 56 (0x38 char '8') => 60 (0x3C)\n 61, // input 57 (0x39 char '9') => 61 (0x3D)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 0, // input 65 (0x41 char 'A') => 0 (0x0)\n 1, // input 66 (0x42 char 'B') => 1 (0x1)\n 2, // input 67 (0x43 char 'C') => 2 (0x2)\n 3, // input 68 (0x44 char 'D') => 3 (0x3)\n 4, // input 69 (0x45 char 'E') => 4 (0x4)\n 5, // input 70 (0x46 char 'F') => 5 (0x5)\n 6, // input 71 (0x47 char 'G') => 6 (0x6)\n 7, // input 72 (0x48 char 'H') => 7 (0x7)\n 8, // input 73 (0x49 char 'I') => 8 (0x8)\n 9, // input 74 (0x4A char 'J') => 9 (0x9)\n 10, // input 75 (0x4B char 'K') => 10 (0xA)\n 11, // input 76 (0x4C char 'L') => 11 (0xB)\n 12, // input 77 (0x4D char 'M') => 12 (0xC)\n 13, // input 78 (0x4E char 'N') => 13 (0xD)\n 14, // input 79 (0x4F char 'O') => 14 (0xE)\n 15, // input 80 (0x50 char 'P') => 15 (0xF)\n 16, // input 81 (0x51 char 'Q') => 16 (0x10)\n 17, // input 82 (0x52 char 'R') => 17 (0x11)\n 18, // input 83 (0x53 char 'S') => 18 (0x12)\n 19, // input 84 (0x54 char 'T') => 19 (0x13)\n 20, // input 85 (0x55 char 'U') => 20 (0x14)\n 21, // input 86 (0x56 char 'V') => 21 (0x15)\n 22, // input 87 (0x57 char 'W') => 22 (0x16)\n 23, // input 88 (0x58 char 'X') => 23 (0x17)\n 24, // input 89 (0x59 char 'Y') => 24 (0x18)\n 25, // input 90 (0x5A char 'Z') => 25 (0x19)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 26, // input 97 (0x61 char 'a') => 26 (0x1A)\n 27, // input 98 (0x62 char 'b') => 27 (0x1B)\n 28, // input 99 (0x63 char 'c') => 28 (0x1C)\n 29, // input 100 (0x64 char 'd') => 29 (0x1D)\n 30, // input 101 (0x65 char 'e') => 30 (0x1E)\n 31, // input 102 (0x66 char 'f') => 31 (0x1F)\n 32, // input 103 (0x67 char 'g') => 32 (0x20)\n 33, // input 104 (0x68 char 'h') => 33 (0x21)\n 34, // input 105 (0x69 char 'i') => 34 (0x22)\n 35, // input 106 (0x6A char 'j') => 35 (0x23)\n 36, // input 107 (0x6B char 'k') => 36 (0x24)\n 37, // input 108 (0x6C char 'l') => 37 (0x25)\n 38, // input 109 (0x6D char 'm') => 38 (0x26)\n 39, // input 110 (0x6E char 'n') => 39 (0x27)\n 40, // input 111 (0x6F char 'o') => 40 (0x28)\n 41, // input 112 (0x70 char 'p') => 41 (0x29)\n 42, // input 113 (0x71 char 'q') => 42 (0x2A)\n 43, // input 114 (0x72 char 'r') => 43 (0x2B)\n 44, // input 115 (0x73 char 's') => 44 (0x2C)\n 45, // input 116 (0x74 char 't') => 45 (0x2D)\n 46, // input 117 (0x75 char 'u') => 46 (0x2E)\n 47, // input 118 (0x76 char 'v') => 47 (0x2F)\n 48, // input 119 (0x77 char 'w') => 48 (0x30)\n 49, // input 120 (0x78 char 'x') => 49 (0x31)\n 50, // input 121 (0x79 char 'y') => 50 (0x32)\n 51, // input 122 (0x7A char 'z') => 51 (0x33)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const URL_SAFE_ENCODE: &[u8; 64] = &[\n 65, // input 0 (0x0) => 'A' (0x41)\n 66, // input 1 (0x1) => 'B' (0x42)\n 67, // input 2 (0x2) => 'C' (0x43)\n 68, // input 3 (0x3) => 'D' (0x44)\n 69, // input 4 (0x4) => 'E' (0x45)\n 70, // input 5 (0x5) => 'F' (0x46)\n 71, // input 6 (0x6) => 'G' (0x47)\n 72, // input 7 (0x7) => 'H' (0x48)\n 73, // input 8 (0x8) => 'I' (0x49)\n 74, // input 9 (0x9) => 'J' (0x4A)\n 75, // input 10 (0xA) => 'K' (0x4B)\n 76, // input 11 (0xB) => 'L' (0x4C)\n 77, // input 12 (0xC) => 'M' (0x4D)\n 78, // input 13 (0xD) => 'N' (0x4E)\n 79, // input 14 (0xE) => 'O' (0x4F)\n 80, // input 15 (0xF) => 'P' (0x50)\n 81, // input 16 (0x10) => 'Q' (0x51)\n 82, // input 17 (0x11) => 'R' (0x52)\n 83, // input 18 (0x12) => 'S' (0x53)\n 84, // input 19 (0x13) => 'T' (0x54)\n 85, // input 20 (0x14) => 'U' (0x55)\n 86, // input 21 (0x15) => 'V' (0x56)\n 87, // input 22 (0x16) => 'W' (0x57)\n 88, // input 23 (0x17) => 'X' (0x58)\n 89, // input 24 (0x18) => 'Y' (0x59)\n 90, // input 25 (0x19) => 'Z' (0x5A)\n 97, // input 26 (0x1A) => 'a' (0x61)\n 98, // input 27 (0x1B) => 'b' (0x62)\n 99, // input 28 (0x1C) => 'c' (0x63)\n 100, // input 29 (0x1D) => 'd' (0x64)\n 101, // input 30 (0x1E) => 'e' (0x65)\n 102, // input 31 (0x1F) => 'f' (0x66)\n 103, // input 32 (0x20) => 'g' (0x67)\n 104, // input 33 (0x21) => 'h' (0x68)\n 105, // input 34 (0x22) => 'i' (0x69)\n 106, // input 35 (0x23) => 'j' (0x6A)\n 107, // input 36 (0x24) => 'k' (0x6B)\n 108, // input 37 (0x25) => 'l' (0x6C)\n 109, // input 38 (0x26) => 'm' (0x6D)\n 110, // input 39 (0x27) => 'n' (0x6E)\n 111, // input 40 (0x28) => 'o' (0x6F)\n 112, // input 41 (0x29) => 'p' (0x70)\n 113, // input 42 (0x2A) => 'q' (0x71)\n 114, // input 43 (0x2B) => 'r' (0x72)\n 115, // input 44 (0x2C) => 's' (0x73)\n 116, // input 45 (0x2D) => 't' (0x74)\n 117, // input 46 (0x2E) => 'u' (0x75)\n 118, // input 47 (0x2F) => 'v' (0x76)\n 119, // input 48 (0x30) => 'w' (0x77)\n 120, // input 49 (0x31) => 'x' (0x78)\n 121, // input 50 (0x32) => 'y' (0x79)\n 122, // input 51 (0x33) => 'z' (0x7A)\n 48, // input 52 (0x34) => '0' (0x30)\n 49, // input 53 (0x35) => '1' (0x31)\n 50, // input 54 (0x36) => '2' (0x32)\n 51, // input 55 (0x37) => '3' (0x33)\n 52, // input 56 (0x38) => '4' (0x34)\n 53, // input 57 (0x39) => '5' (0x35)\n 54, // input 58 (0x3A) => '6' (0x36)\n 55, // input 59 (0x3B) => '7' (0x37)\n 56, // input 60 (0x3C) => '8' (0x38)\n 57, // input 61 (0x3D) => '9' (0x39)\n 45, // input 62 (0x3E) => '-' (0x2D)\n 95, // input 63 (0x3F) => '_' (0x5F)\n];\n#[rustfmt::skip]\npub const URL_SAFE_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n INVALID_VALUE, // input 43 (0x2B)\n INVALID_VALUE, // input 44 (0x2C)\n 62, // input 45 (0x2D char '-') => 62 (0x3E)\n INVALID_VALUE, // input 46 (0x2E)\n INVALID_VALUE, // input 47 (0x2F)\n 52, // input 48 (0x30 char '0') => 52 (0x34)\n 53, // input 49 (0x31 char '1') => 53 (0x35)\n 54, // input 50 (0x32 char '2') => 54 (0x36)\n 55, // input 51 (0x33 char '3') => 55 (0x37)\n 56, // input 52 (0x34 char '4') => 56 (0x38)\n 57, // input 53 (0x35 char '5') => 57 (0x39)\n 58, // input 54 (0x36 char '6') => 58 (0x3A)\n 59, // input 55 (0x37 char '7') => 59 (0x3B)\n 60, // input 56 (0x38 char '8') => 60 (0x3C)\n 61, // input 57 (0x39 char '9') => 61 (0x3D)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 0, // input 65 (0x41 char 'A') => 0 (0x0)\n 1, // input 66 (0x42 char 'B') => 1 (0x1)\n 2, // input 67 (0x43 char 'C') => 2 (0x2)\n 3, // input 68 (0x44 char 'D') => 3 (0x3)\n 4, // input 69 (0x45 char 'E') => 4 (0x4)\n 5, // input 70 (0x46 char 'F') => 5 (0x5)\n 6, // input 71 (0x47 char 'G') => 6 (0x6)\n 7, // input 72 (0x48 char 'H') => 7 (0x7)\n 8, // input 73 (0x49 char 'I') => 8 (0x8)\n 9, // input 74 (0x4A char 'J') => 9 (0x9)\n 10, // input 75 (0x4B char 'K') => 10 (0xA)\n 11, // input 76 (0x4C char 'L') => 11 (0xB)\n 12, // input 77 (0x4D char 'M') => 12 (0xC)\n 13, // input 78 (0x4E char 'N') => 13 (0xD)\n 14, // input 79 (0x4F char 'O') => 14 (0xE)\n 15, // input 80 (0x50 char 'P') => 15 (0xF)\n 16, // input 81 (0x51 char 'Q') => 16 (0x10)\n 17, // input 82 (0x52 char 'R') => 17 (0x11)\n 18, // input 83 (0x53 char 'S') => 18 (0x12)\n 19, // input 84 (0x54 char 'T') => 19 (0x13)\n 20, // input 85 (0x55 char 'U') => 20 (0x14)\n 21, // input 86 (0x56 char 'V') => 21 (0x15)\n 22, // input 87 (0x57 char 'W') => 22 (0x16)\n 23, // input 88 (0x58 char 'X') => 23 (0x17)\n 24, // input 89 (0x59 char 'Y') => 24 (0x18)\n 25, // input 90 (0x5A char 'Z') => 25 (0x19)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n 63, // input 95 (0x5F char '_') => 63 (0x3F)\n INVALID_VALUE, // input 96 (0x60)\n 26, // input 97 (0x61 char 'a') => 26 (0x1A)\n 27, // input 98 (0x62 char 'b') => 27 (0x1B)\n 28, // input 99 (0x63 char 'c') => 28 (0x1C)\n 29, // input 100 (0x64 char 'd') => 29 (0x1D)\n 30, // input 101 (0x65 char 'e') => 30 (0x1E)\n 31, // input 102 (0x66 char 'f') => 31 (0x1F)\n 32, // input 103 (0x67 char 'g') => 32 (0x20)\n 33, // input 104 (0x68 char 'h') => 33 (0x21)\n 34, // input 105 (0x69 char 'i') => 34 (0x22)\n 35, // input 106 (0x6A char 'j') => 35 (0x23)\n 36, // input 107 (0x6B char 'k') => 36 (0x24)\n 37, // input 108 (0x6C char 'l') => 37 (0x25)\n 38, // input 109 (0x6D char 'm') => 38 (0x26)\n 39, // input 110 (0x6E char 'n') => 39 (0x27)\n 40, // input 111 (0x6F char 'o') => 40 (0x28)\n 41, // input 112 (0x70 char 'p') => 41 (0x29)\n 42, // input 113 (0x71 char 'q') => 42 (0x2A)\n 43, // input 114 (0x72 char 'r') => 43 (0x2B)\n 44, // input 115 (0x73 char 's') => 44 (0x2C)\n 45, // input 116 (0x74 char 't') => 45 (0x2D)\n 46, // input 117 (0x75 char 'u') => 46 (0x2E)\n 47, // input 118 (0x76 char 'v') => 47 (0x2F)\n 48, // input 119 (0x77 char 'w') => 48 (0x30)\n 49, // input 120 (0x78 char 'x') => 49 (0x31)\n 50, // input 121 (0x79 char 'y') => 50 (0x32)\n 51, // input 122 (0x7A char 'z') => 51 (0x33)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const CRYPT_ENCODE: &[u8; 64] = &[\n 46, // input 0 (0x0) => '.' (0x2E)\n 47, // input 1 (0x1) => '/' (0x2F)\n 48, // input 2 (0x2) => '0' (0x30)\n 49, // input 3 (0x3) => '1' (0x31)\n 50, // input 4 (0x4) => '2' (0x32)\n 51, // input 5 (0x5) => '3' (0x33)\n 52, // input 6 (0x6) => '4' (0x34)\n 53, // input 7 (0x7) => '5' (0x35)\n 54, // input 8 (0x8) => '6' (0x36)\n 55, // input 9 (0x9) => '7' (0x37)\n 56, // input 10 (0xA) => '8' (0x38)\n 57, // input 11 (0xB) => '9' (0x39)\n 65, // input 12 (0xC) => 'A' (0x41)\n 66, // input 13 (0xD) => 'B' (0x42)\n 67, // input 14 (0xE) => 'C' (0x43)\n 68, // input 15 (0xF) => 'D' (0x44)\n 69, // input 16 (0x10) => 'E' (0x45)\n 70, // input 17 (0x11) => 'F' (0x46)\n 71, // input 18 (0x12) => 'G' (0x47)\n 72, // input 19 (0x13) => 'H' (0x48)\n 73, // input 20 (0x14) => 'I' (0x49)\n 74, // input 21 (0x15) => 'J' (0x4A)\n 75, // input 22 (0x16) => 'K' (0x4B)\n 76, // input 23 (0x17) => 'L' (0x4C)\n 77, // input 24 (0x18) => 'M' (0x4D)\n 78, // input 25 (0x19) => 'N' (0x4E)\n 79, // input 26 (0x1A) => 'O' (0x4F)\n 80, // input 27 (0x1B) => 'P' (0x50)\n 81, // input 28 (0x1C) => 'Q' (0x51)\n 82, // input 29 (0x1D) => 'R' (0x52)\n 83, // input 30 (0x1E) => 'S' (0x53)\n 84, // input 31 (0x1F) => 'T' (0x54)\n 85, // input 32 (0x20) => 'U' (0x55)\n 86, // input 33 (0x21) => 'V' (0x56)\n 87, // input 34 (0x22) => 'W' (0x57)\n 88, // input 35 (0x23) => 'X' (0x58)\n 89, // input 36 (0x24) => 'Y' (0x59)\n 90, // input 37 (0x25) => 'Z' (0x5A)\n 97, // input 38 (0x26) => 'a' (0x61)\n 98, // input 39 (0x27) => 'b' (0x62)\n 99, // input 40 (0x28) => 'c' (0x63)\n 100, // input 41 (0x29) => 'd' (0x64)\n 101, // input 42 (0x2A) => 'e' (0x65)\n 102, // input 43 (0x2B) => 'f' (0x66)\n 103, // input 44 (0x2C) => 'g' (0x67)\n 104, // input 45 (0x2D) => 'h' (0x68)\n 105, // input 46 (0x2E) => 'i' (0x69)\n 106, // input 47 (0x2F) => 'j' (0x6A)\n 107, // input 48 (0x30) => 'k' (0x6B)\n 108, // input 49 (0x31) => 'l' (0x6C)\n 109, // input 50 (0x32) => 'm' (0x6D)\n 110, // input 51 (0x33) => 'n' (0x6E)\n 111, // input 52 (0x34) => 'o' (0x6F)\n 112, // input 53 (0x35) => 'p' (0x70)\n 113, // input 54 (0x36) => 'q' (0x71)\n 114, // input 55 (0x37) => 'r' (0x72)\n 115, // input 56 (0x38) => 's' (0x73)\n 116, // input 57 (0x39) => 't' (0x74)\n 117, // input 58 (0x3A) => 'u' (0x75)\n 118, // input 59 (0x3B) => 'v' (0x76)\n 119, // input 60 (0x3C) => 'w' (0x77)\n 120, // input 61 (0x3D) => 'x' (0x78)\n 121, // input 62 (0x3E) => 'y' (0x79)\n 122, // input 63 (0x3F) => 'z' (0x7A)\n];\n#[rustfmt::skip]\npub const CRYPT_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n INVALID_VALUE, // input 43 (0x2B)\n INVALID_VALUE, // input 44 (0x2C)\n INVALID_VALUE, // input 45 (0x2D)\n 0, // input 46 (0x2E char '.') => 0 (0x0)\n 1, // input 47 (0x2F char '/') => 1 (0x1)\n 2, // input 48 (0x30 char '0') => 2 (0x2)\n 3, // input 49 (0x31 char '1') => 3 (0x3)\n 4, // input 50 (0x32 char '2') => 4 (0x4)\n 5, // input 51 (0x33 char '3') => 5 (0x5)\n 6, // input 52 (0x34 char '4') => 6 (0x6)\n 7, // input 53 (0x35 char '5') => 7 (0x7)\n 8, // input 54 (0x36 char '6') => 8 (0x8)\n 9, // input 55 (0x37 char '7') => 9 (0x9)\n 10, // input 56 (0x38 char '8') => 10 (0xA)\n 11, // input 57 (0x39 char '9') => 11 (0xB)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 12, // input 65 (0x41 char 'A') => 12 (0xC)\n 13, // input 66 (0x42 char 'B') => 13 (0xD)\n 14, // input 67 (0x43 char 'C') => 14 (0xE)\n 15, // input 68 (0x44 char 'D') => 15 (0xF)\n 16, // input 69 (0x45 char 'E') => 16 (0x10)\n 17, // input 70 (0x46 char 'F') => 17 (0x11)\n 18, // input 71 (0x47 char 'G') => 18 (0x12)\n 19, // input 72 (0x48 char 'H') => 19 (0x13)\n 20, // input 73 (0x49 char 'I') => 20 (0x14)\n 21, // input 74 (0x4A char 'J') => 21 (0x15)\n 22, // input 75 (0x4B char 'K') => 22 (0x16)\n 23, // input 76 (0x4C char 'L') => 23 (0x17)\n 24, // input 77 (0x4D char 'M') => 24 (0x18)\n 25, // input 78 (0x4E char 'N') => 25 (0x19)\n 26, // input 79 (0x4F char 'O') => 26 (0x1A)\n 27, // input 80 (0x50 char 'P') => 27 (0x1B)\n 28, // input 81 (0x51 char 'Q') => 28 (0x1C)\n 29, // input 82 (0x52 char 'R') => 29 (0x1D)\n 30, // input 83 (0x53 char 'S') => 30 (0x1E)\n 31, // input 84 (0x54 char 'T') => 31 (0x1F)\n 32, // input 85 (0x55 char 'U') => 32 (0x20)\n 33, // input 86 (0x56 char 'V') => 33 (0x21)\n 34, // input 87 (0x57 char 'W') => 34 (0x22)\n 35, // input 88 (0x58 char 'X') => 35 (0x23)\n 36, // input 89 (0x59 char 'Y') => 36 (0x24)\n 37, // input 90 (0x5A char 'Z') => 37 (0x25)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 38, // input 97 (0x61 char 'a') => 38 (0x26)\n 39, // input 98 (0x62 char 'b') => 39 (0x27)\n 40, // input 99 (0x63 char 'c') => 40 (0x28)\n 41, // input 100 (0x64 char 'd') => 41 (0x29)\n 42, // input 101 (0x65 char 'e') => 42 (0x2A)\n 43, // input 102 (0x66 char 'f') => 43 (0x2B)\n 44, // input 103 (0x67 char 'g') => 44 (0x2C)\n 45, // input 104 (0x68 char 'h') => 45 (0x2D)\n 46, // input 105 (0x69 char 'i') => 46 (0x2E)\n 47, // input 106 (0x6A char 'j') => 47 (0x2F)\n 48, // input 107 (0x6B char 'k') => 48 (0x30)\n 49, // input 108 (0x6C char 'l') => 49 (0x31)\n 50, // input 109 (0x6D char 'm') => 50 (0x32)\n 51, // input 110 (0x6E char 'n') => 51 (0x33)\n 52, // input 111 (0x6F char 'o') => 52 (0x34)\n 53, // input 112 (0x70 char 'p') => 53 (0x35)\n 54, // input 113 (0x71 char 'q') => 54 (0x36)\n 55, // input 114 (0x72 char 'r') => 55 (0x37)\n 56, // input 115 (0x73 char 's') => 56 (0x38)\n 57, // input 116 (0x74 char 't') => 57 (0x39)\n 58, // input 117 (0x75 char 'u') => 58 (0x3A)\n 59, // input 118 (0x76 char 'v') => 59 (0x3B)\n 60, // input 119 (0x77 char 'w') => 60 (0x3C)\n 61, // input 120 (0x78 char 'x') => 61 (0x3D)\n 62, // input 121 (0x79 char 'y') => 62 (0x3E)\n 63, // input 122 (0x7A char 'z') => 63 (0x3F)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const BCRYPT_ENCODE: &[u8; 64] = &[\n 46, // input 0 (0x0) => '.' (0x2E)\n 47, // input 1 (0x1) => '/' (0x2F)\n 65, // input 2 (0x2) => 'A' (0x41)\n 66, // input 3 (0x3) => 'B' (0x42)\n 67, // input 4 (0x4) => 'C' (0x43)\n 68, // input 5 (0x5) => 'D' (0x44)\n 69, // input 6 (0x6) => 'E' (0x45)\n 70, // input 7 (0x7) => 'F' (0x46)\n 71, // input 8 (0x8) => 'G' (0x47)\n 72, // input 9 (0x9) => 'H' (0x48)\n 73, // input 10 (0xA) => 'I' (0x49)\n 74, // input 11 (0xB) => 'J' (0x4A)\n 75, // input 12 (0xC) => 'K' (0x4B)\n 76, // input 13 (0xD) => 'L' (0x4C)\n 77, // input 14 (0xE) => 'M' (0x4D)\n 78, // input 15 (0xF) => 'N' (0x4E)\n 79, // input 16 (0x10) => 'O' (0x4F)\n 80, // input 17 (0x11) => 'P' (0x50)\n 81, // input 18 (0x12) => 'Q' (0x51)\n 82, // input 19 (0x13) => 'R' (0x52)\n 83, // input 20 (0x14) => 'S' (0x53)\n 84, // input 21 (0x15) => 'T' (0x54)\n 85, // input 22 (0x16) => 'U' (0x55)\n 86, // input 23 (0x17) => 'V' (0x56)\n 87, // input 24 (0x18) => 'W' (0x57)\n 88, // input 25 (0x19) => 'X' (0x58)\n 89, // input 26 (0x1A) => 'Y' (0x59)\n 90, // input 27 (0x1B) => 'Z' (0x5A)\n 97, // input 28 (0x1C) => 'a' (0x61)\n 98, // input 29 (0x1D) => 'b' (0x62)\n 99, // input 30 (0x1E) => 'c' (0x63)\n 100, // input 31 (0x1F) => 'd' (0x64)\n 101, // input 32 (0x20) => 'e' (0x65)\n 102, // input 33 (0x21) => 'f' (0x66)\n 103, // input 34 (0x22) => 'g' (0x67)\n 104, // input 35 (0x23) => 'h' (0x68)\n 105, // input 36 (0x24) => 'i' (0x69)\n 106, // input 37 (0x25) => 'j' (0x6A)\n 107, // input 38 (0x26) => 'k' (0x6B)\n 108, // input 39 (0x27) => 'l' (0x6C)\n 109, // input 40 (0x28) => 'm' (0x6D)\n 110, // input 41 (0x29) => 'n' (0x6E)\n 111, // input 42 (0x2A) => 'o' (0x6F)\n 112, // input 43 (0x2B) => 'p' (0x70)\n 113, // input 44 (0x2C) => 'q' (0x71)\n 114, // input 45 (0x2D) => 'r' (0x72)\n 115, // input 46 (0x2E) => 's' (0x73)\n 116, // input 47 (0x2F) => 't' (0x74)\n 117, // input 48 (0x30) => 'u' (0x75)\n 118, // input 49 (0x31) => 'v' (0x76)\n 119, // input 50 (0x32) => 'w' (0x77)\n 120, // input 51 (0x33) => 'x' (0x78)\n 121, // input 52 (0x34) => 'y' (0x79)\n 122, // input 53 (0x35) => 'z' (0x7A)\n 48, // input 54 (0x36) => '0' (0x30)\n 49, // input 55 (0x37) => '1' (0x31)\n 50, // input 56 (0x38) => '2' (0x32)\n 51, // input 57 (0x39) => '3' (0x33)\n 52, // input 58 (0x3A) => '4' (0x34)\n 53, // input 59 (0x3B) => '5' (0x35)\n 54, // input 60 (0x3C) => '6' (0x36)\n 55, // input 61 (0x3D) => '7' (0x37)\n 56, // input 62 (0x3E) => '8' (0x38)\n 57, // input 63 (0x3F) => '9' (0x39)\n];\n#[rustfmt::skip]\npub const BCRYPT_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n INVALID_VALUE, // input 43 (0x2B)\n INVALID_VALUE, // input 44 (0x2C)\n INVALID_VALUE, // input 45 (0x2D)\n 0, // input 46 (0x2E char '.') => 0 (0x0)\n 1, // input 47 (0x2F char '/') => 1 (0x1)\n 54, // input 48 (0x30 char '0') => 54 (0x36)\n 55, // input 49 (0x31 char '1') => 55 (0x37)\n 56, // input 50 (0x32 char '2') => 56 (0x38)\n 57, // input 51 (0x33 char '3') => 57 (0x39)\n 58, // input 52 (0x34 char '4') => 58 (0x3A)\n 59, // input 53 (0x35 char '5') => 59 (0x3B)\n 60, // input 54 (0x36 char '6') => 60 (0x3C)\n 61, // input 55 (0x37 char '7') => 61 (0x3D)\n 62, // input 56 (0x38 char '8') => 62 (0x3E)\n 63, // input 57 (0x39 char '9') => 63 (0x3F)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 2, // input 65 (0x41 char 'A') => 2 (0x2)\n 3, // input 66 (0x42 char 'B') => 3 (0x3)\n 4, // input 67 (0x43 char 'C') => 4 (0x4)\n 5, // input 68 (0x44 char 'D') => 5 (0x5)\n 6, // input 69 (0x45 char 'E') => 6 (0x6)\n 7, // input 70 (0x46 char 'F') => 7 (0x7)\n 8, // input 71 (0x47 char 'G') => 8 (0x8)\n 9, // input 72 (0x48 char 'H') => 9 (0x9)\n 10, // input 73 (0x49 char 'I') => 10 (0xA)\n 11, // input 74 (0x4A char 'J') => 11 (0xB)\n 12, // input 75 (0x4B char 'K') => 12 (0xC)\n 13, // input 76 (0x4C char 'L') => 13 (0xD)\n 14, // input 77 (0x4D char 'M') => 14 (0xE)\n 15, // input 78 (0x4E char 'N') => 15 (0xF)\n 16, // input 79 (0x4F char 'O') => 16 (0x10)\n 17, // input 80 (0x50 char 'P') => 17 (0x11)\n 18, // input 81 (0x51 char 'Q') => 18 (0x12)\n 19, // input 82 (0x52 char 'R') => 19 (0x13)\n 20, // input 83 (0x53 char 'S') => 20 (0x14)\n 21, // input 84 (0x54 char 'T') => 21 (0x15)\n 22, // input 85 (0x55 char 'U') => 22 (0x16)\n 23, // input 86 (0x56 char 'V') => 23 (0x17)\n 24, // input 87 (0x57 char 'W') => 24 (0x18)\n 25, // input 88 (0x58 char 'X') => 25 (0x19)\n 26, // input 89 (0x59 char 'Y') => 26 (0x1A)\n 27, // input 90 (0x5A char 'Z') => 27 (0x1B)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 28, // input 97 (0x61 char 'a') => 28 (0x1C)\n 29, // input 98 (0x62 char 'b') => 29 (0x1D)\n 30, // input 99 (0x63 char 'c') => 30 (0x1E)\n 31, // input 100 (0x64 char 'd') => 31 (0x1F)\n 32, // input 101 (0x65 char 'e') => 32 (0x20)\n 33, // input 102 (0x66 char 'f') => 33 (0x21)\n 34, // input 103 (0x67 char 'g') => 34 (0x22)\n 35, // input 104 (0x68 char 'h') => 35 (0x23)\n 36, // input 105 (0x69 char 'i') => 36 (0x24)\n 37, // input 106 (0x6A char 'j') => 37 (0x25)\n 38, // input 107 (0x6B char 'k') => 38 (0x26)\n 39, // input 108 (0x6C char 'l') => 39 (0x27)\n 40, // input 109 (0x6D char 'm') => 40 (0x28)\n 41, // input 110 (0x6E char 'n') => 41 (0x29)\n 42, // input 111 (0x6F char 'o') => 42 (0x2A)\n 43, // input 112 (0x70 char 'p') => 43 (0x2B)\n 44, // input 113 (0x71 char 'q') => 44 (0x2C)\n 45, // input 114 (0x72 char 'r') => 45 (0x2D)\n 46, // input 115 (0x73 char 's') => 46 (0x2E)\n 47, // input 116 (0x74 char 't') => 47 (0x2F)\n 48, // input 117 (0x75 char 'u') => 48 (0x30)\n 49, // input 118 (0x76 char 'v') => 49 (0x31)\n 50, // input 119 (0x77 char 'w') => 50 (0x32)\n 51, // input 120 (0x78 char 'x') => 51 (0x33)\n 52, // input 121 (0x79 char 'y') => 52 (0x34)\n 53, // input 122 (0x7A char 'z') => 53 (0x35)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const IMAP_MUTF7_ENCODE: &[u8; 64] = &[\n 65, // input 0 (0x0) => 'A' (0x41)\n 66, // input 1 (0x1) => 'B' (0x42)\n 67, // input 2 (0x2) => 'C' (0x43)\n 68, // input 3 (0x3) => 'D' (0x44)\n 69, // input 4 (0x4) => 'E' (0x45)\n 70, // input 5 (0x5) => 'F' (0x46)\n 71, // input 6 (0x6) => 'G' (0x47)\n 72, // input 7 (0x7) => 'H' (0x48)\n 73, // input 8 (0x8) => 'I' (0x49)\n 74, // input 9 (0x9) => 'J' (0x4A)\n 75, // input 10 (0xA) => 'K' (0x4B)\n 76, // input 11 (0xB) => 'L' (0x4C)\n 77, // input 12 (0xC) => 'M' (0x4D)\n 78, // input 13 (0xD) => 'N' (0x4E)\n 79, // input 14 (0xE) => 'O' (0x4F)\n 80, // input 15 (0xF) => 'P' (0x50)\n 81, // input 16 (0x10) => 'Q' (0x51)\n 82, // input 17 (0x11) => 'R' (0x52)\n 83, // input 18 (0x12) => 'S' (0x53)\n 84, // input 19 (0x13) => 'T' (0x54)\n 85, // input 20 (0x14) => 'U' (0x55)\n 86, // input 21 (0x15) => 'V' (0x56)\n 87, // input 22 (0x16) => 'W' (0x57)\n 88, // input 23 (0x17) => 'X' (0x58)\n 89, // input 24 (0x18) => 'Y' (0x59)\n 90, // input 25 (0x19) => 'Z' (0x5A)\n 97, // input 26 (0x1A) => 'a' (0x61)\n 98, // input 27 (0x1B) => 'b' (0x62)\n 99, // input 28 (0x1C) => 'c' (0x63)\n 100, // input 29 (0x1D) => 'd' (0x64)\n 101, // input 30 (0x1E) => 'e' (0x65)\n 102, // input 31 (0x1F) => 'f' (0x66)\n 103, // input 32 (0x20) => 'g' (0x67)\n 104, // input 33 (0x21) => 'h' (0x68)\n 105, // input 34 (0x22) => 'i' (0x69)\n 106, // input 35 (0x23) => 'j' (0x6A)\n 107, // input 36 (0x24) => 'k' (0x6B)\n 108, // input 37 (0x25) => 'l' (0x6C)\n 109, // input 38 (0x26) => 'm' (0x6D)\n 110, // input 39 (0x27) => 'n' (0x6E)\n 111, // input 40 (0x28) => 'o' (0x6F)\n 112, // input 41 (0x29) => 'p' (0x70)\n 113, // input 42 (0x2A) => 'q' (0x71)\n 114, // input 43 (0x2B) => 'r' (0x72)\n 115, // input 44 (0x2C) => 's' (0x73)\n 116, // input 45 (0x2D) => 't' (0x74)\n 117, // input 46 (0x2E) => 'u' (0x75)\n 118, // input 47 (0x2F) => 'v' (0x76)\n 119, // input 48 (0x30) => 'w' (0x77)\n 120, // input 49 (0x31) => 'x' (0x78)\n 121, // input 50 (0x32) => 'y' (0x79)\n 122, // input 51 (0x33) => 'z' (0x7A)\n 48, // input 52 (0x34) => '0' (0x30)\n 49, // input 53 (0x35) => '1' (0x31)\n 50, // input 54 (0x36) => '2' (0x32)\n 51, // input 55 (0x37) => '3' (0x33)\n 52, // input 56 (0x38) => '4' (0x34)\n 53, // input 57 (0x39) => '5' (0x35)\n 54, // input 58 (0x3A) => '6' (0x36)\n 55, // input 59 (0x3B) => '7' (0x37)\n 56, // input 60 (0x3C) => '8' (0x38)\n 57, // input 61 (0x3D) => '9' (0x39)\n 43, // input 62 (0x3E) => '+' (0x2B)\n 44, // input 63 (0x3F) => ',' (0x2C)\n];\n#[rustfmt::skip]\npub const IMAP_MUTF7_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n 62, // input 43 (0x2B char '+') => 62 (0x3E)\n 63, // input 44 (0x2C char ',') => 63 (0x3F)\n INVALID_VALUE, // input 45 (0x2D)\n INVALID_VALUE, // input 46 (0x2E)\n INVALID_VALUE, // input 47 (0x2F)\n 52, // input 48 (0x30 char '0') => 52 (0x34)\n 53, // input 49 (0x31 char '1') => 53 (0x35)\n 54, // input 50 (0x32 char '2') => 54 (0x36)\n 55, // input 51 (0x33 char '3') => 55 (0x37)\n 56, // input 52 (0x34 char '4') => 56 (0x38)\n 57, // input 53 (0x35 char '5') => 57 (0x39)\n 58, // input 54 (0x36 char '6') => 58 (0x3A)\n 59, // input 55 (0x37 char '7') => 59 (0x3B)\n 60, // input 56 (0x38 char '8') => 60 (0x3C)\n 61, // input 57 (0x39 char '9') => 61 (0x3D)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 0, // input 65 (0x41 char 'A') => 0 (0x0)\n 1, // input 66 (0x42 char 'B') => 1 (0x1)\n 2, // input 67 (0x43 char 'C') => 2 (0x2)\n 3, // input 68 (0x44 char 'D') => 3 (0x3)\n 4, // input 69 (0x45 char 'E') => 4 (0x4)\n 5, // input 70 (0x46 char 'F') => 5 (0x5)\n 6, // input 71 (0x47 char 'G') => 6 (0x6)\n 7, // input 72 (0x48 char 'H') => 7 (0x7)\n 8, // input 73 (0x49 char 'I') => 8 (0x8)\n 9, // input 74 (0x4A char 'J') => 9 (0x9)\n 10, // input 75 (0x4B char 'K') => 10 (0xA)\n 11, // input 76 (0x4C char 'L') => 11 (0xB)\n 12, // input 77 (0x4D char 'M') => 12 (0xC)\n 13, // input 78 (0x4E char 'N') => 13 (0xD)\n 14, // input 79 (0x4F char 'O') => 14 (0xE)\n 15, // input 80 (0x50 char 'P') => 15 (0xF)\n 16, // input 81 (0x51 char 'Q') => 16 (0x10)\n 17, // input 82 (0x52 char 'R') => 17 (0x11)\n 18, // input 83 (0x53 char 'S') => 18 (0x12)\n 19, // input 84 (0x54 char 'T') => 19 (0x13)\n 20, // input 85 (0x55 char 'U') => 20 (0x14)\n 21, // input 86 (0x56 char 'V') => 21 (0x15)\n 22, // input 87 (0x57 char 'W') => 22 (0x16)\n 23, // input 88 (0x58 char 'X') => 23 (0x17)\n 24, // input 89 (0x59 char 'Y') => 24 (0x18)\n 25, // input 90 (0x5A char 'Z') => 25 (0x19)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 26, // input 97 (0x61 char 'a') => 26 (0x1A)\n 27, // input 98 (0x62 char 'b') => 27 (0x1B)\n 28, // input 99 (0x63 char 'c') => 28 (0x1C)\n 29, // input 100 (0x64 char 'd') => 29 (0x1D)\n 30, // input 101 (0x65 char 'e') => 30 (0x1E)\n 31, // input 102 (0x66 char 'f') => 31 (0x1F)\n 32, // input 103 (0x67 char 'g') => 32 (0x20)\n 33, // input 104 (0x68 char 'h') => 33 (0x21)\n 34, // input 105 (0x69 char 'i') => 34 (0x22)\n 35, // input 106 (0x6A char 'j') => 35 (0x23)\n 36, // input 107 (0x6B char 'k') => 36 (0x24)\n 37, // input 108 (0x6C char 'l') => 37 (0x25)\n 38, // input 109 (0x6D char 'm') => 38 (0x26)\n 39, // input 110 (0x6E char 'n') => 39 (0x27)\n 40, // input 111 (0x6F char 'o') => 40 (0x28)\n 41, // input 112 (0x70 char 'p') => 41 (0x29)\n 42, // input 113 (0x71 char 'q') => 42 (0x2A)\n 43, // input 114 (0x72 char 'r') => 43 (0x2B)\n 44, // input 115 (0x73 char 's') => 44 (0x2C)\n 45, // input 116 (0x74 char 't') => 45 (0x2D)\n 46, // input 117 (0x75 char 'u') => 46 (0x2E)\n 47, // input 118 (0x76 char 'v') => 47 (0x2F)\n 48, // input 119 (0x77 char 'w') => 48 (0x30)\n 49, // input 120 (0x78 char 'x') => 49 (0x31)\n 50, // input 121 (0x79 char 'y') => 50 (0x32)\n 51, // input 122 (0x7A char 'z') => 51 (0x33)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const BINHEX_ENCODE: &[u8; 64] = &[\n 33, // input 0 (0x0) => '!' (0x21)\n 34, // input 1 (0x1) => '\"' (0x22)\n 35, // input 2 (0x2) => '#' (0x23)\n 36, // input 3 (0x3) => '$' (0x24)\n 37, // input 4 (0x4) => '%' (0x25)\n 38, // input 5 (0x5) => '&' (0x26)\n 39, // input 6 (0x6) => ''' (0x27)\n 40, // input 7 (0x7) => '(' (0x28)\n 41, // input 8 (0x8) => ')' (0x29)\n 42, // input 9 (0x9) => '*' (0x2A)\n 43, // input 10 (0xA) => '+' (0x2B)\n 44, // input 11 (0xB) => ',' (0x2C)\n 45, // input 12 (0xC) => '-' (0x2D)\n 48, // input 13 (0xD) => '0' (0x30)\n 49, // input 14 (0xE) => '1' (0x31)\n 50, // input 15 (0xF) => '2' (0x32)\n 51, // input 16 (0x10) => '3' (0x33)\n 52, // input 17 (0x11) => '4' (0x34)\n 53, // input 18 (0x12) => '5' (0x35)\n 54, // input 19 (0x13) => '6' (0x36)\n 55, // input 20 (0x14) => '7' (0x37)\n 56, // input 21 (0x15) => '8' (0x38)\n 57, // input 22 (0x16) => '9' (0x39)\n 64, // input 23 (0x17) => '@' (0x40)\n 65, // input 24 (0x18) => 'A' (0x41)\n 66, // input 25 (0x19) => 'B' (0x42)\n 67, // input 26 (0x1A) => 'C' (0x43)\n 68, // input 27 (0x1B) => 'D' (0x44)\n 69, // input 28 (0x1C) => 'E' (0x45)\n 70, // input 29 (0x1D) => 'F' (0x46)\n 71, // input 30 (0x1E) => 'G' (0x47)\n 72, // input 31 (0x1F) => 'H' (0x48)\n 73, // input 32 (0x20) => 'I' (0x49)\n 74, // input 33 (0x21) => 'J' (0x4A)\n 75, // input 34 (0x22) => 'K' (0x4B)\n 76, // input 35 (0x23) => 'L' (0x4C)\n 77, // input 36 (0x24) => 'M' (0x4D)\n 78, // input 37 (0x25) => 'N' (0x4E)\n 80, // input 38 (0x26) => 'P' (0x50)\n 81, // input 39 (0x27) => 'Q' (0x51)\n 82, // input 40 (0x28) => 'R' (0x52)\n 83, // input 41 (0x29) => 'S' (0x53)\n 84, // input 42 (0x2A) => 'T' (0x54)\n 85, // input 43 (0x2B) => 'U' (0x55)\n 86, // input 44 (0x2C) => 'V' (0x56)\n 88, // input 45 (0x2D) => 'X' (0x58)\n 89, // input 46 (0x2E) => 'Y' (0x59)\n 90, // input 47 (0x2F) => 'Z' (0x5A)\n 91, // input 48 (0x30) => '[' (0x5B)\n 96, // input 49 (0x31) => '`' (0x60)\n 97, // input 50 (0x32) => 'a' (0x61)\n 98, // input 51 (0x33) => 'b' (0x62)\n 99, // input 52 (0x34) => 'c' (0x63)\n 100, // input 53 (0x35) => 'd' (0x64)\n 101, // input 54 (0x36) => 'e' (0x65)\n 104, // input 55 (0x37) => 'h' (0x68)\n 105, // input 56 (0x38) => 'i' (0x69)\n 106, // input 57 (0x39) => 'j' (0x6A)\n 107, // input 58 (0x3A) => 'k' (0x6B)\n 108, // input 59 (0x3B) => 'l' (0x6C)\n 109, // input 60 (0x3C) => 'm' (0x6D)\n 112, // input 61 (0x3D) => 'p' (0x70)\n 113, // input 62 (0x3E) => 'q' (0x71)\n 114, // input 63 (0x3F) => 'r' (0x72)\n];\n#[rustfmt::skip]\npub const BINHEX_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n 0, // input 33 (0x21 char '!') => 0 (0x0)\n 1, // input 34 (0x22 char '\"') => 1 (0x1)\n 2, // input 35 (0x23 char '#') => 2 (0x2)\n 3, // input 36 (0x24 char '$') => 3 (0x3)\n 4, // input 37 (0x25 char '%') => 4 (0x4)\n 5, // input 38 (0x26 char '&') => 5 (0x5)\n 6, // input 39 (0x27 char ''') => 6 (0x6)\n 7, // input 40 (0x28 char '(') => 7 (0x7)\n 8, // input 41 (0x29 char ')') => 8 (0x8)\n 9, // input 42 (0x2A char '*') => 9 (0x9)\n 10, // input 43 (0x2B char '+') => 10 (0xA)\n 11, // input 44 (0x2C char ',') => 11 (0xB)\n 12, // input 45 (0x2D char '-') => 12 (0xC)\n INVALID_VALUE, // input 46 (0x2E)\n INVALID_VALUE, // input 47 (0x2F)\n 13, // input 48 (0x30 char '0') => 13 (0xD)\n 14, // input 49 (0x31 char '1') => 14 (0xE)\n 15, // input 50 (0x32 char '2') => 15 (0xF)\n 16, // input 51 (0x33 char '3') => 16 (0x10)\n 17, // input 52 (0x34 char '4') => 17 (0x11)\n 18, // input 53 (0x35 char '5') => 18 (0x12)\n 19, // input 54 (0x36 char '6') => 19 (0x13)\n 20, // input 55 (0x37 char '7') => 20 (0x14)\n 21, // input 56 (0x38 char '8') => 21 (0x15)\n 22, // input 57 (0x39 char '9') => 22 (0x16)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n 23, // input 64 (0x40 char '@') => 23 (0x17)\n 24, // input 65 (0x41 char 'A') => 24 (0x18)\n 25, // input 66 (0x42 char 'B') => 25 (0x19)\n 26, // input 67 (0x43 char 'C') => 26 (0x1A)\n 27, // input 68 (0x44 char 'D') => 27 (0x1B)\n 28, // input 69 (0x45 char 'E') => 28 (0x1C)\n 29, // input 70 (0x46 char 'F') => 29 (0x1D)\n 30, // input 71 (0x47 char 'G') => 30 (0x1E)\n 31, // input 72 (0x48 char 'H') => 31 (0x1F)\n 32, // input 73 (0x49 char 'I') => 32 (0x20)\n 33, // input 74 (0x4A char 'J') => 33 (0x21)\n 34, // input 75 (0x4B char 'K') => 34 (0x22)\n 35, // input 76 (0x4C char 'L') => 35 (0x23)\n 36, // input 77 (0x4D char 'M') => 36 (0x24)\n 37, // input 78 (0x4E char 'N') => 37 (0x25)\n INVALID_VALUE, // input 79 (0x4F)\n 38, // input 80 (0x50 char 'P') => 38 (0x26)\n 39, // input 81 (0x51 char 'Q') => 39 (0x27)\n 40, // input 82 (0x52 char 'R') => 40 (0x28)\n 41, // input 83 (0x53 char 'S') => 41 (0x29)\n 42, // input 84 (0x54 char 'T') => 42 (0x2A)\n 43, // input 85 (0x55 char 'U') => 43 (0x2B)\n 44, // input 86 (0x56 char 'V') => 44 (0x2C)\n INVALID_VALUE, // input 87 (0x57)\n 45, // input 88 (0x58 char 'X') => 45 (0x2D)\n 46, // input 89 (0x59 char 'Y') => 46 (0x2E)\n 47, // input 90 (0x5A char 'Z') => 47 (0x2F)\n 48, // input 91 (0x5B char '[') => 48 (0x30)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n 49, // input 96 (0x60 char '`') => 49 (0x31)\n 50, // input 97 (0x61 char 'a') => 50 (0x32)\n 51, // input 98 (0x62 char 'b') => 51 (0x33)\n 52, // input 99 (0x63 char 'c') => 52 (0x34)\n 53, // input 100 (0x64 char 'd') => 53 (0x35)\n 54, // input 101 (0x65 char 'e') => 54 (0x36)\n INVALID_VALUE, // input 102 (0x66)\n INVALID_VALUE, // input 103 (0x67)\n 55, // input 104 (0x68 char 'h') => 55 (0x37)\n 56, // input 105 (0x69 char 'i') => 56 (0x38)\n 57, // input 106 (0x6A char 'j') => 57 (0x39)\n 58, // input 107 (0x6B char 'k') => 58 (0x3A)\n 59, // input 108 (0x6C char 'l') => 59 (0x3B)\n 60, // input 109 (0x6D char 'm') => 60 (0x3C)\n INVALID_VALUE, // input 110 (0x6E)\n INVALID_VALUE, // input 111 (0x6F)\n 61, // input 112 (0x70 char 'p') => 61 (0x3D)\n 62, // input 113 (0x71 char 'q') => 62 (0x3E)\n 63, // input 114 (0x72 char 'r') => 63 (0x3F)\n INVALID_VALUE, // input 115 (0x73)\n INVALID_VALUE, // input 116 (0x74)\n INVALID_VALUE, // input 117 (0x75)\n INVALID_VALUE, // input 118 (0x76)\n INVALID_VALUE, // input 119 (0x77)\n INVALID_VALUE, // input 120 (0x78)\n INVALID_VALUE, // input 121 (0x79)\n INVALID_VALUE, // input 122 (0x7A)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];", "" ]
[ 0, 1, 0 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "//#[repr(align(64))]\n//pub struct StructStandardEncode { pub data: [u8; 64] }\n#[repr(align(64))]\npub struct StructStandardDecode { pub data: [u8; 256] }\n//#[repr(align(64))]\n//pub struct StructUrlSafeEncode { pub data: [u8; 64] }\n#[repr(align(64))]\npub struct StructUrlSafeDecode { pub data: [u8; 256] }\n//#[repr(align(64))]\n//pub struct StructCryptEncode { pub data: [u8; 64] }\n#[repr(align(64))]\npub struct StructCryptDecode { pub data: [u8; 256] }\n//#[repr(align(64))]\n//pub struct StructBcryptEncode { pub data: [u8; 64] }\n#[repr(align(64))]\npub struct StructBcryptDecode { pub data: [u8; 256] }\n//#[repr(align(64))]\n//pub struct StructImapMutf7Encode { pub data: [u8; 64] }\n#[repr(align(64))]\npub struct StructImapMutf7Decode { pub data: [u8; 256] }\n//#[repr(align(64))]\n//pub struct StructBinhexEncode { pub data: [u8; 64] }\n#[repr(align(64))]\npub struct StructBinhexDecode { pub data: [u8; 256] }", "pub const STANDARD_DECODE_HOLDER: StructStandardDecode = StructStandardDecode { data: *STANDARD_DECODE };\npub const URL_SAFE_DECODE_HOLDER: StructUrlSafeDecode = StructUrlSafeDecode { data: *URL_SAFE_DECODE };\npub const CRYPT_DECODE_HOLDER: StructCryptDecode = StructCryptDecode { data: *CRYPT_DECODE };\npub const BCRYPT_DECODE_HOLDER: StructBcryptDecode = StructBcryptDecode { data: *BCRYPT_DECODE };\npub const IMAP_MUTF7_DECODE_HOLDER: StructImapMutf7Decode = StructImapMutf7Decode { data: *IMAP_MUTF7_DECODE };\npub const BINHEX_DECODE_HOLDER: StructBinhexDecode = StructBinhexDecode { data: *BINHEX_DECODE };\n", "pub const INVALID_VALUE: u8 = 255;\n#[rustfmt::skip]\npub const STANDARD_ENCODE: &[u8; 64] = &[\n 65, // input 0 (0x0) => 'A' (0x41)\n 66, // input 1 (0x1) => 'B' (0x42)\n 67, // input 2 (0x2) => 'C' (0x43)\n 68, // input 3 (0x3) => 'D' (0x44)\n 69, // input 4 (0x4) => 'E' (0x45)\n 70, // input 5 (0x5) => 'F' (0x46)\n 71, // input 6 (0x6) => 'G' (0x47)\n 72, // input 7 (0x7) => 'H' (0x48)\n 73, // input 8 (0x8) => 'I' (0x49)\n 74, // input 9 (0x9) => 'J' (0x4A)\n 75, // input 10 (0xA) => 'K' (0x4B)\n 76, // input 11 (0xB) => 'L' (0x4C)\n 77, // input 12 (0xC) => 'M' (0x4D)\n 78, // input 13 (0xD) => 'N' (0x4E)\n 79, // input 14 (0xE) => 'O' (0x4F)\n 80, // input 15 (0xF) => 'P' (0x50)\n 81, // input 16 (0x10) => 'Q' (0x51)\n 82, // input 17 (0x11) => 'R' (0x52)\n 83, // input 18 (0x12) => 'S' (0x53)\n 84, // input 19 (0x13) => 'T' (0x54)\n 85, // input 20 (0x14) => 'U' (0x55)\n 86, // input 21 (0x15) => 'V' (0x56)\n 87, // input 22 (0x16) => 'W' (0x57)\n 88, // input 23 (0x17) => 'X' (0x58)\n 89, // input 24 (0x18) => 'Y' (0x59)\n 90, // input 25 (0x19) => 'Z' (0x5A)\n 97, // input 26 (0x1A) => 'a' (0x61)\n 98, // input 27 (0x1B) => 'b' (0x62)\n 99, // input 28 (0x1C) => 'c' (0x63)\n 100, // input 29 (0x1D) => 'd' (0x64)\n 101, // input 30 (0x1E) => 'e' (0x65)\n 102, // input 31 (0x1F) => 'f' (0x66)\n 103, // input 32 (0x20) => 'g' (0x67)\n 104, // input 33 (0x21) => 'h' (0x68)\n 105, // input 34 (0x22) => 'i' (0x69)\n 106, // input 35 (0x23) => 'j' (0x6A)\n 107, // input 36 (0x24) => 'k' (0x6B)\n 108, // input 37 (0x25) => 'l' (0x6C)\n 109, // input 38 (0x26) => 'm' (0x6D)\n 110, // input 39 (0x27) => 'n' (0x6E)\n 111, // input 40 (0x28) => 'o' (0x6F)\n 112, // input 41 (0x29) => 'p' (0x70)\n 113, // input 42 (0x2A) => 'q' (0x71)\n 114, // input 43 (0x2B) => 'r' (0x72)\n 115, // input 44 (0x2C) => 's' (0x73)\n 116, // input 45 (0x2D) => 't' (0x74)\n 117, // input 46 (0x2E) => 'u' (0x75)\n 118, // input 47 (0x2F) => 'v' (0x76)\n 119, // input 48 (0x30) => 'w' (0x77)\n 120, // input 49 (0x31) => 'x' (0x78)\n 121, // input 50 (0x32) => 'y' (0x79)\n 122, // input 51 (0x33) => 'z' (0x7A)\n 48, // input 52 (0x34) => '0' (0x30)\n 49, // input 53 (0x35) => '1' (0x31)\n 50, // input 54 (0x36) => '2' (0x32)\n 51, // input 55 (0x37) => '3' (0x33)\n 52, // input 56 (0x38) => '4' (0x34)\n 53, // input 57 (0x39) => '5' (0x35)\n 54, // input 58 (0x3A) => '6' (0x36)\n 55, // input 59 (0x3B) => '7' (0x37)\n 56, // input 60 (0x3C) => '8' (0x38)\n 57, // input 61 (0x3D) => '9' (0x39)\n 43, // input 62 (0x3E) => '+' (0x2B)\n 47, // input 63 (0x3F) => '/' (0x2F)\n];\n#[rustfmt::skip]\npub const STANDARD_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n 62, // input 43 (0x2B char '+') => 62 (0x3E)\n INVALID_VALUE, // input 44 (0x2C)\n INVALID_VALUE, // input 45 (0x2D)\n INVALID_VALUE, // input 46 (0x2E)\n 63, // input 47 (0x2F char '/') => 63 (0x3F)\n 52, // input 48 (0x30 char '0') => 52 (0x34)\n 53, // input 49 (0x31 char '1') => 53 (0x35)\n 54, // input 50 (0x32 char '2') => 54 (0x36)\n 55, // input 51 (0x33 char '3') => 55 (0x37)\n 56, // input 52 (0x34 char '4') => 56 (0x38)\n 57, // input 53 (0x35 char '5') => 57 (0x39)\n 58, // input 54 (0x36 char '6') => 58 (0x3A)\n 59, // input 55 (0x37 char '7') => 59 (0x3B)\n 60, // input 56 (0x38 char '8') => 60 (0x3C)\n 61, // input 57 (0x39 char '9') => 61 (0x3D)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 0, // input 65 (0x41 char 'A') => 0 (0x0)\n 1, // input 66 (0x42 char 'B') => 1 (0x1)\n 2, // input 67 (0x43 char 'C') => 2 (0x2)\n 3, // input 68 (0x44 char 'D') => 3 (0x3)\n 4, // input 69 (0x45 char 'E') => 4 (0x4)\n 5, // input 70 (0x46 char 'F') => 5 (0x5)\n 6, // input 71 (0x47 char 'G') => 6 (0x6)\n 7, // input 72 (0x48 char 'H') => 7 (0x7)\n 8, // input 73 (0x49 char 'I') => 8 (0x8)\n 9, // input 74 (0x4A char 'J') => 9 (0x9)\n 10, // input 75 (0x4B char 'K') => 10 (0xA)\n 11, // input 76 (0x4C char 'L') => 11 (0xB)\n 12, // input 77 (0x4D char 'M') => 12 (0xC)\n 13, // input 78 (0x4E char 'N') => 13 (0xD)\n 14, // input 79 (0x4F char 'O') => 14 (0xE)\n 15, // input 80 (0x50 char 'P') => 15 (0xF)\n 16, // input 81 (0x51 char 'Q') => 16 (0x10)\n 17, // input 82 (0x52 char 'R') => 17 (0x11)\n 18, // input 83 (0x53 char 'S') => 18 (0x12)\n 19, // input 84 (0x54 char 'T') => 19 (0x13)\n 20, // input 85 (0x55 char 'U') => 20 (0x14)\n 21, // input 86 (0x56 char 'V') => 21 (0x15)\n 22, // input 87 (0x57 char 'W') => 22 (0x16)\n 23, // input 88 (0x58 char 'X') => 23 (0x17)\n 24, // input 89 (0x59 char 'Y') => 24 (0x18)\n 25, // input 90 (0x5A char 'Z') => 25 (0x19)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 26, // input 97 (0x61 char 'a') => 26 (0x1A)\n 27, // input 98 (0x62 char 'b') => 27 (0x1B)\n 28, // input 99 (0x63 char 'c') => 28 (0x1C)\n 29, // input 100 (0x64 char 'd') => 29 (0x1D)\n 30, // input 101 (0x65 char 'e') => 30 (0x1E)\n 31, // input 102 (0x66 char 'f') => 31 (0x1F)\n 32, // input 103 (0x67 char 'g') => 32 (0x20)\n 33, // input 104 (0x68 char 'h') => 33 (0x21)\n 34, // input 105 (0x69 char 'i') => 34 (0x22)\n 35, // input 106 (0x6A char 'j') => 35 (0x23)\n 36, // input 107 (0x6B char 'k') => 36 (0x24)\n 37, // input 108 (0x6C char 'l') => 37 (0x25)\n 38, // input 109 (0x6D char 'm') => 38 (0x26)\n 39, // input 110 (0x6E char 'n') => 39 (0x27)\n 40, // input 111 (0x6F char 'o') => 40 (0x28)\n 41, // input 112 (0x70 char 'p') => 41 (0x29)\n 42, // input 113 (0x71 char 'q') => 42 (0x2A)\n 43, // input 114 (0x72 char 'r') => 43 (0x2B)\n 44, // input 115 (0x73 char 's') => 44 (0x2C)\n 45, // input 116 (0x74 char 't') => 45 (0x2D)\n 46, // input 117 (0x75 char 'u') => 46 (0x2E)\n 47, // input 118 (0x76 char 'v') => 47 (0x2F)\n 48, // input 119 (0x77 char 'w') => 48 (0x30)\n 49, // input 120 (0x78 char 'x') => 49 (0x31)\n 50, // input 121 (0x79 char 'y') => 50 (0x32)\n 51, // input 122 (0x7A char 'z') => 51 (0x33)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const URL_SAFE_ENCODE: &[u8; 64] = &[\n 65, // input 0 (0x0) => 'A' (0x41)\n 66, // input 1 (0x1) => 'B' (0x42)\n 67, // input 2 (0x2) => 'C' (0x43)\n 68, // input 3 (0x3) => 'D' (0x44)\n 69, // input 4 (0x4) => 'E' (0x45)\n 70, // input 5 (0x5) => 'F' (0x46)\n 71, // input 6 (0x6) => 'G' (0x47)\n 72, // input 7 (0x7) => 'H' (0x48)\n 73, // input 8 (0x8) => 'I' (0x49)\n 74, // input 9 (0x9) => 'J' (0x4A)\n 75, // input 10 (0xA) => 'K' (0x4B)\n 76, // input 11 (0xB) => 'L' (0x4C)\n 77, // input 12 (0xC) => 'M' (0x4D)\n 78, // input 13 (0xD) => 'N' (0x4E)\n 79, // input 14 (0xE) => 'O' (0x4F)\n 80, // input 15 (0xF) => 'P' (0x50)\n 81, // input 16 (0x10) => 'Q' (0x51)\n 82, // input 17 (0x11) => 'R' (0x52)\n 83, // input 18 (0x12) => 'S' (0x53)\n 84, // input 19 (0x13) => 'T' (0x54)\n 85, // input 20 (0x14) => 'U' (0x55)\n 86, // input 21 (0x15) => 'V' (0x56)\n 87, // input 22 (0x16) => 'W' (0x57)\n 88, // input 23 (0x17) => 'X' (0x58)\n 89, // input 24 (0x18) => 'Y' (0x59)\n 90, // input 25 (0x19) => 'Z' (0x5A)\n 97, // input 26 (0x1A) => 'a' (0x61)\n 98, // input 27 (0x1B) => 'b' (0x62)\n 99, // input 28 (0x1C) => 'c' (0x63)\n 100, // input 29 (0x1D) => 'd' (0x64)\n 101, // input 30 (0x1E) => 'e' (0x65)\n 102, // input 31 (0x1F) => 'f' (0x66)\n 103, // input 32 (0x20) => 'g' (0x67)\n 104, // input 33 (0x21) => 'h' (0x68)\n 105, // input 34 (0x22) => 'i' (0x69)\n 106, // input 35 (0x23) => 'j' (0x6A)\n 107, // input 36 (0x24) => 'k' (0x6B)\n 108, // input 37 (0x25) => 'l' (0x6C)\n 109, // input 38 (0x26) => 'm' (0x6D)\n 110, // input 39 (0x27) => 'n' (0x6E)\n 111, // input 40 (0x28) => 'o' (0x6F)\n 112, // input 41 (0x29) => 'p' (0x70)\n 113, // input 42 (0x2A) => 'q' (0x71)\n 114, // input 43 (0x2B) => 'r' (0x72)\n 115, // input 44 (0x2C) => 's' (0x73)\n 116, // input 45 (0x2D) => 't' (0x74)\n 117, // input 46 (0x2E) => 'u' (0x75)\n 118, // input 47 (0x2F) => 'v' (0x76)\n 119, // input 48 (0x30) => 'w' (0x77)\n 120, // input 49 (0x31) => 'x' (0x78)\n 121, // input 50 (0x32) => 'y' (0x79)\n 122, // input 51 (0x33) => 'z' (0x7A)\n 48, // input 52 (0x34) => '0' (0x30)\n 49, // input 53 (0x35) => '1' (0x31)\n 50, // input 54 (0x36) => '2' (0x32)\n 51, // input 55 (0x37) => '3' (0x33)\n 52, // input 56 (0x38) => '4' (0x34)\n 53, // input 57 (0x39) => '5' (0x35)\n 54, // input 58 (0x3A) => '6' (0x36)\n 55, // input 59 (0x3B) => '7' (0x37)\n 56, // input 60 (0x3C) => '8' (0x38)\n 57, // input 61 (0x3D) => '9' (0x39)\n 45, // input 62 (0x3E) => '-' (0x2D)\n 95, // input 63 (0x3F) => '_' (0x5F)\n];\n#[rustfmt::skip]\npub const URL_SAFE_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n INVALID_VALUE, // input 43 (0x2B)\n INVALID_VALUE, // input 44 (0x2C)\n 62, // input 45 (0x2D char '-') => 62 (0x3E)\n INVALID_VALUE, // input 46 (0x2E)\n INVALID_VALUE, // input 47 (0x2F)\n 52, // input 48 (0x30 char '0') => 52 (0x34)\n 53, // input 49 (0x31 char '1') => 53 (0x35)\n 54, // input 50 (0x32 char '2') => 54 (0x36)\n 55, // input 51 (0x33 char '3') => 55 (0x37)\n 56, // input 52 (0x34 char '4') => 56 (0x38)\n 57, // input 53 (0x35 char '5') => 57 (0x39)\n 58, // input 54 (0x36 char '6') => 58 (0x3A)\n 59, // input 55 (0x37 char '7') => 59 (0x3B)\n 60, // input 56 (0x38 char '8') => 60 (0x3C)\n 61, // input 57 (0x39 char '9') => 61 (0x3D)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 0, // input 65 (0x41 char 'A') => 0 (0x0)\n 1, // input 66 (0x42 char 'B') => 1 (0x1)\n 2, // input 67 (0x43 char 'C') => 2 (0x2)\n 3, // input 68 (0x44 char 'D') => 3 (0x3)\n 4, // input 69 (0x45 char 'E') => 4 (0x4)\n 5, // input 70 (0x46 char 'F') => 5 (0x5)\n 6, // input 71 (0x47 char 'G') => 6 (0x6)\n 7, // input 72 (0x48 char 'H') => 7 (0x7)\n 8, // input 73 (0x49 char 'I') => 8 (0x8)\n 9, // input 74 (0x4A char 'J') => 9 (0x9)\n 10, // input 75 (0x4B char 'K') => 10 (0xA)\n 11, // input 76 (0x4C char 'L') => 11 (0xB)\n 12, // input 77 (0x4D char 'M') => 12 (0xC)\n 13, // input 78 (0x4E char 'N') => 13 (0xD)\n 14, // input 79 (0x4F char 'O') => 14 (0xE)\n 15, // input 80 (0x50 char 'P') => 15 (0xF)\n 16, // input 81 (0x51 char 'Q') => 16 (0x10)\n 17, // input 82 (0x52 char 'R') => 17 (0x11)\n 18, // input 83 (0x53 char 'S') => 18 (0x12)\n 19, // input 84 (0x54 char 'T') => 19 (0x13)\n 20, // input 85 (0x55 char 'U') => 20 (0x14)\n 21, // input 86 (0x56 char 'V') => 21 (0x15)\n 22, // input 87 (0x57 char 'W') => 22 (0x16)\n 23, // input 88 (0x58 char 'X') => 23 (0x17)\n 24, // input 89 (0x59 char 'Y') => 24 (0x18)\n 25, // input 90 (0x5A char 'Z') => 25 (0x19)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n 63, // input 95 (0x5F char '_') => 63 (0x3F)\n INVALID_VALUE, // input 96 (0x60)\n 26, // input 97 (0x61 char 'a') => 26 (0x1A)\n 27, // input 98 (0x62 char 'b') => 27 (0x1B)\n 28, // input 99 (0x63 char 'c') => 28 (0x1C)\n 29, // input 100 (0x64 char 'd') => 29 (0x1D)\n 30, // input 101 (0x65 char 'e') => 30 (0x1E)\n 31, // input 102 (0x66 char 'f') => 31 (0x1F)\n 32, // input 103 (0x67 char 'g') => 32 (0x20)\n 33, // input 104 (0x68 char 'h') => 33 (0x21)\n 34, // input 105 (0x69 char 'i') => 34 (0x22)\n 35, // input 106 (0x6A char 'j') => 35 (0x23)\n 36, // input 107 (0x6B char 'k') => 36 (0x24)\n 37, // input 108 (0x6C char 'l') => 37 (0x25)\n 38, // input 109 (0x6D char 'm') => 38 (0x26)\n 39, // input 110 (0x6E char 'n') => 39 (0x27)\n 40, // input 111 (0x6F char 'o') => 40 (0x28)\n 41, // input 112 (0x70 char 'p') => 41 (0x29)\n 42, // input 113 (0x71 char 'q') => 42 (0x2A)\n 43, // input 114 (0x72 char 'r') => 43 (0x2B)\n 44, // input 115 (0x73 char 's') => 44 (0x2C)\n 45, // input 116 (0x74 char 't') => 45 (0x2D)\n 46, // input 117 (0x75 char 'u') => 46 (0x2E)\n 47, // input 118 (0x76 char 'v') => 47 (0x2F)\n 48, // input 119 (0x77 char 'w') => 48 (0x30)\n 49, // input 120 (0x78 char 'x') => 49 (0x31)\n 50, // input 121 (0x79 char 'y') => 50 (0x32)\n 51, // input 122 (0x7A char 'z') => 51 (0x33)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const CRYPT_ENCODE: &[u8; 64] = &[\n 46, // input 0 (0x0) => '.' (0x2E)\n 47, // input 1 (0x1) => '/' (0x2F)\n 48, // input 2 (0x2) => '0' (0x30)\n 49, // input 3 (0x3) => '1' (0x31)\n 50, // input 4 (0x4) => '2' (0x32)\n 51, // input 5 (0x5) => '3' (0x33)\n 52, // input 6 (0x6) => '4' (0x34)\n 53, // input 7 (0x7) => '5' (0x35)\n 54, // input 8 (0x8) => '6' (0x36)\n 55, // input 9 (0x9) => '7' (0x37)\n 56, // input 10 (0xA) => '8' (0x38)\n 57, // input 11 (0xB) => '9' (0x39)\n 65, // input 12 (0xC) => 'A' (0x41)\n 66, // input 13 (0xD) => 'B' (0x42)\n 67, // input 14 (0xE) => 'C' (0x43)\n 68, // input 15 (0xF) => 'D' (0x44)\n 69, // input 16 (0x10) => 'E' (0x45)\n 70, // input 17 (0x11) => 'F' (0x46)\n 71, // input 18 (0x12) => 'G' (0x47)\n 72, // input 19 (0x13) => 'H' (0x48)\n 73, // input 20 (0x14) => 'I' (0x49)\n 74, // input 21 (0x15) => 'J' (0x4A)\n 75, // input 22 (0x16) => 'K' (0x4B)\n 76, // input 23 (0x17) => 'L' (0x4C)\n 77, // input 24 (0x18) => 'M' (0x4D)\n 78, // input 25 (0x19) => 'N' (0x4E)\n 79, // input 26 (0x1A) => 'O' (0x4F)\n 80, // input 27 (0x1B) => 'P' (0x50)\n 81, // input 28 (0x1C) => 'Q' (0x51)\n 82, // input 29 (0x1D) => 'R' (0x52)\n 83, // input 30 (0x1E) => 'S' (0x53)\n 84, // input 31 (0x1F) => 'T' (0x54)\n 85, // input 32 (0x20) => 'U' (0x55)\n 86, // input 33 (0x21) => 'V' (0x56)\n 87, // input 34 (0x22) => 'W' (0x57)\n 88, // input 35 (0x23) => 'X' (0x58)\n 89, // input 36 (0x24) => 'Y' (0x59)\n 90, // input 37 (0x25) => 'Z' (0x5A)\n 97, // input 38 (0x26) => 'a' (0x61)\n 98, // input 39 (0x27) => 'b' (0x62)\n 99, // input 40 (0x28) => 'c' (0x63)\n 100, // input 41 (0x29) => 'd' (0x64)\n 101, // input 42 (0x2A) => 'e' (0x65)\n 102, // input 43 (0x2B) => 'f' (0x66)\n 103, // input 44 (0x2C) => 'g' (0x67)\n 104, // input 45 (0x2D) => 'h' (0x68)\n 105, // input 46 (0x2E) => 'i' (0x69)\n 106, // input 47 (0x2F) => 'j' (0x6A)\n 107, // input 48 (0x30) => 'k' (0x6B)\n 108, // input 49 (0x31) => 'l' (0x6C)\n 109, // input 50 (0x32) => 'm' (0x6D)\n 110, // input 51 (0x33) => 'n' (0x6E)\n 111, // input 52 (0x34) => 'o' (0x6F)\n 112, // input 53 (0x35) => 'p' (0x70)\n 113, // input 54 (0x36) => 'q' (0x71)\n 114, // input 55 (0x37) => 'r' (0x72)\n 115, // input 56 (0x38) => 's' (0x73)\n 116, // input 57 (0x39) => 't' (0x74)\n 117, // input 58 (0x3A) => 'u' (0x75)\n 118, // input 59 (0x3B) => 'v' (0x76)\n 119, // input 60 (0x3C) => 'w' (0x77)\n 120, // input 61 (0x3D) => 'x' (0x78)\n 121, // input 62 (0x3E) => 'y' (0x79)\n 122, // input 63 (0x3F) => 'z' (0x7A)\n];\n#[rustfmt::skip]\npub const CRYPT_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n INVALID_VALUE, // input 43 (0x2B)\n INVALID_VALUE, // input 44 (0x2C)\n INVALID_VALUE, // input 45 (0x2D)\n 0, // input 46 (0x2E char '.') => 0 (0x0)\n 1, // input 47 (0x2F char '/') => 1 (0x1)\n 2, // input 48 (0x30 char '0') => 2 (0x2)\n 3, // input 49 (0x31 char '1') => 3 (0x3)\n 4, // input 50 (0x32 char '2') => 4 (0x4)\n 5, // input 51 (0x33 char '3') => 5 (0x5)\n 6, // input 52 (0x34 char '4') => 6 (0x6)\n 7, // input 53 (0x35 char '5') => 7 (0x7)\n 8, // input 54 (0x36 char '6') => 8 (0x8)\n 9, // input 55 (0x37 char '7') => 9 (0x9)\n 10, // input 56 (0x38 char '8') => 10 (0xA)\n 11, // input 57 (0x39 char '9') => 11 (0xB)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 12, // input 65 (0x41 char 'A') => 12 (0xC)\n 13, // input 66 (0x42 char 'B') => 13 (0xD)\n 14, // input 67 (0x43 char 'C') => 14 (0xE)\n 15, // input 68 (0x44 char 'D') => 15 (0xF)\n 16, // input 69 (0x45 char 'E') => 16 (0x10)\n 17, // input 70 (0x46 char 'F') => 17 (0x11)\n 18, // input 71 (0x47 char 'G') => 18 (0x12)\n 19, // input 72 (0x48 char 'H') => 19 (0x13)\n 20, // input 73 (0x49 char 'I') => 20 (0x14)\n 21, // input 74 (0x4A char 'J') => 21 (0x15)\n 22, // input 75 (0x4B char 'K') => 22 (0x16)\n 23, // input 76 (0x4C char 'L') => 23 (0x17)\n 24, // input 77 (0x4D char 'M') => 24 (0x18)\n 25, // input 78 (0x4E char 'N') => 25 (0x19)\n 26, // input 79 (0x4F char 'O') => 26 (0x1A)\n 27, // input 80 (0x50 char 'P') => 27 (0x1B)\n 28, // input 81 (0x51 char 'Q') => 28 (0x1C)\n 29, // input 82 (0x52 char 'R') => 29 (0x1D)\n 30, // input 83 (0x53 char 'S') => 30 (0x1E)\n 31, // input 84 (0x54 char 'T') => 31 (0x1F)\n 32, // input 85 (0x55 char 'U') => 32 (0x20)\n 33, // input 86 (0x56 char 'V') => 33 (0x21)\n 34, // input 87 (0x57 char 'W') => 34 (0x22)\n 35, // input 88 (0x58 char 'X') => 35 (0x23)\n 36, // input 89 (0x59 char 'Y') => 36 (0x24)\n 37, // input 90 (0x5A char 'Z') => 37 (0x25)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 38, // input 97 (0x61 char 'a') => 38 (0x26)\n 39, // input 98 (0x62 char 'b') => 39 (0x27)\n 40, // input 99 (0x63 char 'c') => 40 (0x28)\n 41, // input 100 (0x64 char 'd') => 41 (0x29)\n 42, // input 101 (0x65 char 'e') => 42 (0x2A)\n 43, // input 102 (0x66 char 'f') => 43 (0x2B)\n 44, // input 103 (0x67 char 'g') => 44 (0x2C)\n 45, // input 104 (0x68 char 'h') => 45 (0x2D)\n 46, // input 105 (0x69 char 'i') => 46 (0x2E)\n 47, // input 106 (0x6A char 'j') => 47 (0x2F)\n 48, // input 107 (0x6B char 'k') => 48 (0x30)\n 49, // input 108 (0x6C char 'l') => 49 (0x31)\n 50, // input 109 (0x6D char 'm') => 50 (0x32)\n 51, // input 110 (0x6E char 'n') => 51 (0x33)\n 52, // input 111 (0x6F char 'o') => 52 (0x34)\n 53, // input 112 (0x70 char 'p') => 53 (0x35)\n 54, // input 113 (0x71 char 'q') => 54 (0x36)\n 55, // input 114 (0x72 char 'r') => 55 (0x37)\n 56, // input 115 (0x73 char 's') => 56 (0x38)\n 57, // input 116 (0x74 char 't') => 57 (0x39)\n 58, // input 117 (0x75 char 'u') => 58 (0x3A)\n 59, // input 118 (0x76 char 'v') => 59 (0x3B)\n 60, // input 119 (0x77 char 'w') => 60 (0x3C)\n 61, // input 120 (0x78 char 'x') => 61 (0x3D)\n 62, // input 121 (0x79 char 'y') => 62 (0x3E)\n 63, // input 122 (0x7A char 'z') => 63 (0x3F)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const BCRYPT_ENCODE: &[u8; 64] = &[\n 46, // input 0 (0x0) => '.' (0x2E)\n 47, // input 1 (0x1) => '/' (0x2F)\n 65, // input 2 (0x2) => 'A' (0x41)\n 66, // input 3 (0x3) => 'B' (0x42)\n 67, // input 4 (0x4) => 'C' (0x43)\n 68, // input 5 (0x5) => 'D' (0x44)\n 69, // input 6 (0x6) => 'E' (0x45)\n 70, // input 7 (0x7) => 'F' (0x46)\n 71, // input 8 (0x8) => 'G' (0x47)\n 72, // input 9 (0x9) => 'H' (0x48)\n 73, // input 10 (0xA) => 'I' (0x49)\n 74, // input 11 (0xB) => 'J' (0x4A)\n 75, // input 12 (0xC) => 'K' (0x4B)\n 76, // input 13 (0xD) => 'L' (0x4C)\n 77, // input 14 (0xE) => 'M' (0x4D)\n 78, // input 15 (0xF) => 'N' (0x4E)\n 79, // input 16 (0x10) => 'O' (0x4F)\n 80, // input 17 (0x11) => 'P' (0x50)\n 81, // input 18 (0x12) => 'Q' (0x51)\n 82, // input 19 (0x13) => 'R' (0x52)\n 83, // input 20 (0x14) => 'S' (0x53)\n 84, // input 21 (0x15) => 'T' (0x54)\n 85, // input 22 (0x16) => 'U' (0x55)\n 86, // input 23 (0x17) => 'V' (0x56)\n 87, // input 24 (0x18) => 'W' (0x57)\n 88, // input 25 (0x19) => 'X' (0x58)\n 89, // input 26 (0x1A) => 'Y' (0x59)\n 90, // input 27 (0x1B) => 'Z' (0x5A)\n 97, // input 28 (0x1C) => 'a' (0x61)\n 98, // input 29 (0x1D) => 'b' (0x62)\n 99, // input 30 (0x1E) => 'c' (0x63)\n 100, // input 31 (0x1F) => 'd' (0x64)\n 101, // input 32 (0x20) => 'e' (0x65)\n 102, // input 33 (0x21) => 'f' (0x66)\n 103, // input 34 (0x22) => 'g' (0x67)\n 104, // input 35 (0x23) => 'h' (0x68)\n 105, // input 36 (0x24) => 'i' (0x69)\n 106, // input 37 (0x25) => 'j' (0x6A)\n 107, // input 38 (0x26) => 'k' (0x6B)\n 108, // input 39 (0x27) => 'l' (0x6C)\n 109, // input 40 (0x28) => 'm' (0x6D)\n 110, // input 41 (0x29) => 'n' (0x6E)\n 111, // input 42 (0x2A) => 'o' (0x6F)\n 112, // input 43 (0x2B) => 'p' (0x70)\n 113, // input 44 (0x2C) => 'q' (0x71)\n 114, // input 45 (0x2D) => 'r' (0x72)\n 115, // input 46 (0x2E) => 's' (0x73)\n 116, // input 47 (0x2F) => 't' (0x74)\n 117, // input 48 (0x30) => 'u' (0x75)\n 118, // input 49 (0x31) => 'v' (0x76)\n 119, // input 50 (0x32) => 'w' (0x77)\n 120, // input 51 (0x33) => 'x' (0x78)\n 121, // input 52 (0x34) => 'y' (0x79)\n 122, // input 53 (0x35) => 'z' (0x7A)\n 48, // input 54 (0x36) => '0' (0x30)\n 49, // input 55 (0x37) => '1' (0x31)\n 50, // input 56 (0x38) => '2' (0x32)\n 51, // input 57 (0x39) => '3' (0x33)\n 52, // input 58 (0x3A) => '4' (0x34)\n 53, // input 59 (0x3B) => '5' (0x35)\n 54, // input 60 (0x3C) => '6' (0x36)\n 55, // input 61 (0x3D) => '7' (0x37)\n 56, // input 62 (0x3E) => '8' (0x38)\n 57, // input 63 (0x3F) => '9' (0x39)\n];\n#[rustfmt::skip]\npub const BCRYPT_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n INVALID_VALUE, // input 43 (0x2B)\n INVALID_VALUE, // input 44 (0x2C)\n INVALID_VALUE, // input 45 (0x2D)\n 0, // input 46 (0x2E char '.') => 0 (0x0)\n 1, // input 47 (0x2F char '/') => 1 (0x1)\n 54, // input 48 (0x30 char '0') => 54 (0x36)\n 55, // input 49 (0x31 char '1') => 55 (0x37)\n 56, // input 50 (0x32 char '2') => 56 (0x38)\n 57, // input 51 (0x33 char '3') => 57 (0x39)\n 58, // input 52 (0x34 char '4') => 58 (0x3A)\n 59, // input 53 (0x35 char '5') => 59 (0x3B)\n 60, // input 54 (0x36 char '6') => 60 (0x3C)\n 61, // input 55 (0x37 char '7') => 61 (0x3D)\n 62, // input 56 (0x38 char '8') => 62 (0x3E)\n 63, // input 57 (0x39 char '9') => 63 (0x3F)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 2, // input 65 (0x41 char 'A') => 2 (0x2)\n 3, // input 66 (0x42 char 'B') => 3 (0x3)\n 4, // input 67 (0x43 char 'C') => 4 (0x4)\n 5, // input 68 (0x44 char 'D') => 5 (0x5)\n 6, // input 69 (0x45 char 'E') => 6 (0x6)\n 7, // input 70 (0x46 char 'F') => 7 (0x7)\n 8, // input 71 (0x47 char 'G') => 8 (0x8)\n 9, // input 72 (0x48 char 'H') => 9 (0x9)\n 10, // input 73 (0x49 char 'I') => 10 (0xA)\n 11, // input 74 (0x4A char 'J') => 11 (0xB)\n 12, // input 75 (0x4B char 'K') => 12 (0xC)\n 13, // input 76 (0x4C char 'L') => 13 (0xD)\n 14, // input 77 (0x4D char 'M') => 14 (0xE)\n 15, // input 78 (0x4E char 'N') => 15 (0xF)\n 16, // input 79 (0x4F char 'O') => 16 (0x10)\n 17, // input 80 (0x50 char 'P') => 17 (0x11)\n 18, // input 81 (0x51 char 'Q') => 18 (0x12)\n 19, // input 82 (0x52 char 'R') => 19 (0x13)\n 20, // input 83 (0x53 char 'S') => 20 (0x14)\n 21, // input 84 (0x54 char 'T') => 21 (0x15)\n 22, // input 85 (0x55 char 'U') => 22 (0x16)\n 23, // input 86 (0x56 char 'V') => 23 (0x17)\n 24, // input 87 (0x57 char 'W') => 24 (0x18)\n 25, // input 88 (0x58 char 'X') => 25 (0x19)\n 26, // input 89 (0x59 char 'Y') => 26 (0x1A)\n 27, // input 90 (0x5A char 'Z') => 27 (0x1B)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 28, // input 97 (0x61 char 'a') => 28 (0x1C)\n 29, // input 98 (0x62 char 'b') => 29 (0x1D)\n 30, // input 99 (0x63 char 'c') => 30 (0x1E)\n 31, // input 100 (0x64 char 'd') => 31 (0x1F)\n 32, // input 101 (0x65 char 'e') => 32 (0x20)\n 33, // input 102 (0x66 char 'f') => 33 (0x21)\n 34, // input 103 (0x67 char 'g') => 34 (0x22)\n 35, // input 104 (0x68 char 'h') => 35 (0x23)\n 36, // input 105 (0x69 char 'i') => 36 (0x24)\n 37, // input 106 (0x6A char 'j') => 37 (0x25)\n 38, // input 107 (0x6B char 'k') => 38 (0x26)\n 39, // input 108 (0x6C char 'l') => 39 (0x27)\n 40, // input 109 (0x6D char 'm') => 40 (0x28)\n 41, // input 110 (0x6E char 'n') => 41 (0x29)\n 42, // input 111 (0x6F char 'o') => 42 (0x2A)\n 43, // input 112 (0x70 char 'p') => 43 (0x2B)\n 44, // input 113 (0x71 char 'q') => 44 (0x2C)\n 45, // input 114 (0x72 char 'r') => 45 (0x2D)\n 46, // input 115 (0x73 char 's') => 46 (0x2E)\n 47, // input 116 (0x74 char 't') => 47 (0x2F)\n 48, // input 117 (0x75 char 'u') => 48 (0x30)\n 49, // input 118 (0x76 char 'v') => 49 (0x31)\n 50, // input 119 (0x77 char 'w') => 50 (0x32)\n 51, // input 120 (0x78 char 'x') => 51 (0x33)\n 52, // input 121 (0x79 char 'y') => 52 (0x34)\n 53, // input 122 (0x7A char 'z') => 53 (0x35)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const IMAP_MUTF7_ENCODE: &[u8; 64] = &[\n 65, // input 0 (0x0) => 'A' (0x41)\n 66, // input 1 (0x1) => 'B' (0x42)\n 67, // input 2 (0x2) => 'C' (0x43)\n 68, // input 3 (0x3) => 'D' (0x44)\n 69, // input 4 (0x4) => 'E' (0x45)\n 70, // input 5 (0x5) => 'F' (0x46)\n 71, // input 6 (0x6) => 'G' (0x47)\n 72, // input 7 (0x7) => 'H' (0x48)\n 73, // input 8 (0x8) => 'I' (0x49)\n 74, // input 9 (0x9) => 'J' (0x4A)\n 75, // input 10 (0xA) => 'K' (0x4B)\n 76, // input 11 (0xB) => 'L' (0x4C)\n 77, // input 12 (0xC) => 'M' (0x4D)\n 78, // input 13 (0xD) => 'N' (0x4E)\n 79, // input 14 (0xE) => 'O' (0x4F)\n 80, // input 15 (0xF) => 'P' (0x50)\n 81, // input 16 (0x10) => 'Q' (0x51)\n 82, // input 17 (0x11) => 'R' (0x52)\n 83, // input 18 (0x12) => 'S' (0x53)\n 84, // input 19 (0x13) => 'T' (0x54)\n 85, // input 20 (0x14) => 'U' (0x55)\n 86, // input 21 (0x15) => 'V' (0x56)\n 87, // input 22 (0x16) => 'W' (0x57)\n 88, // input 23 (0x17) => 'X' (0x58)\n 89, // input 24 (0x18) => 'Y' (0x59)\n 90, // input 25 (0x19) => 'Z' (0x5A)\n 97, // input 26 (0x1A) => 'a' (0x61)\n 98, // input 27 (0x1B) => 'b' (0x62)\n 99, // input 28 (0x1C) => 'c' (0x63)\n 100, // input 29 (0x1D) => 'd' (0x64)\n 101, // input 30 (0x1E) => 'e' (0x65)\n 102, // input 31 (0x1F) => 'f' (0x66)\n 103, // input 32 (0x20) => 'g' (0x67)\n 104, // input 33 (0x21) => 'h' (0x68)\n 105, // input 34 (0x22) => 'i' (0x69)\n 106, // input 35 (0x23) => 'j' (0x6A)\n 107, // input 36 (0x24) => 'k' (0x6B)\n 108, // input 37 (0x25) => 'l' (0x6C)\n 109, // input 38 (0x26) => 'm' (0x6D)\n 110, // input 39 (0x27) => 'n' (0x6E)\n 111, // input 40 (0x28) => 'o' (0x6F)\n 112, // input 41 (0x29) => 'p' (0x70)\n 113, // input 42 (0x2A) => 'q' (0x71)\n 114, // input 43 (0x2B) => 'r' (0x72)\n 115, // input 44 (0x2C) => 's' (0x73)\n 116, // input 45 (0x2D) => 't' (0x74)\n 117, // input 46 (0x2E) => 'u' (0x75)\n 118, // input 47 (0x2F) => 'v' (0x76)\n 119, // input 48 (0x30) => 'w' (0x77)\n 120, // input 49 (0x31) => 'x' (0x78)\n 121, // input 50 (0x32) => 'y' (0x79)\n 122, // input 51 (0x33) => 'z' (0x7A)\n 48, // input 52 (0x34) => '0' (0x30)\n 49, // input 53 (0x35) => '1' (0x31)\n 50, // input 54 (0x36) => '2' (0x32)\n 51, // input 55 (0x37) => '3' (0x33)\n 52, // input 56 (0x38) => '4' (0x34)\n 53, // input 57 (0x39) => '5' (0x35)\n 54, // input 58 (0x3A) => '6' (0x36)\n 55, // input 59 (0x3B) => '7' (0x37)\n 56, // input 60 (0x3C) => '8' (0x38)\n 57, // input 61 (0x3D) => '9' (0x39)\n 43, // input 62 (0x3E) => '+' (0x2B)\n 44, // input 63 (0x3F) => ',' (0x2C)\n];\n#[rustfmt::skip]\npub const IMAP_MUTF7_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n INVALID_VALUE, // input 33 (0x21)\n INVALID_VALUE, // input 34 (0x22)\n INVALID_VALUE, // input 35 (0x23)\n INVALID_VALUE, // input 36 (0x24)\n INVALID_VALUE, // input 37 (0x25)\n INVALID_VALUE, // input 38 (0x26)\n INVALID_VALUE, // input 39 (0x27)\n INVALID_VALUE, // input 40 (0x28)\n INVALID_VALUE, // input 41 (0x29)\n INVALID_VALUE, // input 42 (0x2A)\n 62, // input 43 (0x2B char '+') => 62 (0x3E)\n 63, // input 44 (0x2C char ',') => 63 (0x3F)\n INVALID_VALUE, // input 45 (0x2D)\n INVALID_VALUE, // input 46 (0x2E)\n INVALID_VALUE, // input 47 (0x2F)\n 52, // input 48 (0x30 char '0') => 52 (0x34)\n 53, // input 49 (0x31 char '1') => 53 (0x35)\n 54, // input 50 (0x32 char '2') => 54 (0x36)\n 55, // input 51 (0x33 char '3') => 55 (0x37)\n 56, // input 52 (0x34 char '4') => 56 (0x38)\n 57, // input 53 (0x35 char '5') => 57 (0x39)\n 58, // input 54 (0x36 char '6') => 58 (0x3A)\n 59, // input 55 (0x37 char '7') => 59 (0x3B)\n 60, // input 56 (0x38 char '8') => 60 (0x3C)\n 61, // input 57 (0x39 char '9') => 61 (0x3D)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n INVALID_VALUE, // input 64 (0x40)\n 0, // input 65 (0x41 char 'A') => 0 (0x0)\n 1, // input 66 (0x42 char 'B') => 1 (0x1)\n 2, // input 67 (0x43 char 'C') => 2 (0x2)\n 3, // input 68 (0x44 char 'D') => 3 (0x3)\n 4, // input 69 (0x45 char 'E') => 4 (0x4)\n 5, // input 70 (0x46 char 'F') => 5 (0x5)\n 6, // input 71 (0x47 char 'G') => 6 (0x6)\n 7, // input 72 (0x48 char 'H') => 7 (0x7)\n 8, // input 73 (0x49 char 'I') => 8 (0x8)\n 9, // input 74 (0x4A char 'J') => 9 (0x9)\n 10, // input 75 (0x4B char 'K') => 10 (0xA)\n 11, // input 76 (0x4C char 'L') => 11 (0xB)\n 12, // input 77 (0x4D char 'M') => 12 (0xC)\n 13, // input 78 (0x4E char 'N') => 13 (0xD)\n 14, // input 79 (0x4F char 'O') => 14 (0xE)\n 15, // input 80 (0x50 char 'P') => 15 (0xF)\n 16, // input 81 (0x51 char 'Q') => 16 (0x10)\n 17, // input 82 (0x52 char 'R') => 17 (0x11)\n 18, // input 83 (0x53 char 'S') => 18 (0x12)\n 19, // input 84 (0x54 char 'T') => 19 (0x13)\n 20, // input 85 (0x55 char 'U') => 20 (0x14)\n 21, // input 86 (0x56 char 'V') => 21 (0x15)\n 22, // input 87 (0x57 char 'W') => 22 (0x16)\n 23, // input 88 (0x58 char 'X') => 23 (0x17)\n 24, // input 89 (0x59 char 'Y') => 24 (0x18)\n 25, // input 90 (0x5A char 'Z') => 25 (0x19)\n INVALID_VALUE, // input 91 (0x5B)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n INVALID_VALUE, // input 96 (0x60)\n 26, // input 97 (0x61 char 'a') => 26 (0x1A)\n 27, // input 98 (0x62 char 'b') => 27 (0x1B)\n 28, // input 99 (0x63 char 'c') => 28 (0x1C)\n 29, // input 100 (0x64 char 'd') => 29 (0x1D)\n 30, // input 101 (0x65 char 'e') => 30 (0x1E)\n 31, // input 102 (0x66 char 'f') => 31 (0x1F)\n 32, // input 103 (0x67 char 'g') => 32 (0x20)\n 33, // input 104 (0x68 char 'h') => 33 (0x21)\n 34, // input 105 (0x69 char 'i') => 34 (0x22)\n 35, // input 106 (0x6A char 'j') => 35 (0x23)\n 36, // input 107 (0x6B char 'k') => 36 (0x24)\n 37, // input 108 (0x6C char 'l') => 37 (0x25)\n 38, // input 109 (0x6D char 'm') => 38 (0x26)\n 39, // input 110 (0x6E char 'n') => 39 (0x27)\n 40, // input 111 (0x6F char 'o') => 40 (0x28)\n 41, // input 112 (0x70 char 'p') => 41 (0x29)\n 42, // input 113 (0x71 char 'q') => 42 (0x2A)\n 43, // input 114 (0x72 char 'r') => 43 (0x2B)\n 44, // input 115 (0x73 char 's') => 44 (0x2C)\n 45, // input 116 (0x74 char 't') => 45 (0x2D)\n 46, // input 117 (0x75 char 'u') => 46 (0x2E)\n 47, // input 118 (0x76 char 'v') => 47 (0x2F)\n 48, // input 119 (0x77 char 'w') => 48 (0x30)\n 49, // input 120 (0x78 char 'x') => 49 (0x31)\n 50, // input 121 (0x79 char 'y') => 50 (0x32)\n 51, // input 122 (0x7A char 'z') => 51 (0x33)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];\n#[rustfmt::skip]\npub const BINHEX_ENCODE: &[u8; 64] = &[\n 33, // input 0 (0x0) => '!' (0x21)\n 34, // input 1 (0x1) => '\"' (0x22)\n 35, // input 2 (0x2) => '#' (0x23)\n 36, // input 3 (0x3) => '$' (0x24)\n 37, // input 4 (0x4) => '%' (0x25)\n 38, // input 5 (0x5) => '&' (0x26)\n 39, // input 6 (0x6) => ''' (0x27)\n 40, // input 7 (0x7) => '(' (0x28)\n 41, // input 8 (0x8) => ')' (0x29)\n 42, // input 9 (0x9) => '*' (0x2A)\n 43, // input 10 (0xA) => '+' (0x2B)\n 44, // input 11 (0xB) => ',' (0x2C)\n 45, // input 12 (0xC) => '-' (0x2D)\n 48, // input 13 (0xD) => '0' (0x30)\n 49, // input 14 (0xE) => '1' (0x31)\n 50, // input 15 (0xF) => '2' (0x32)\n 51, // input 16 (0x10) => '3' (0x33)\n 52, // input 17 (0x11) => '4' (0x34)\n 53, // input 18 (0x12) => '5' (0x35)\n 54, // input 19 (0x13) => '6' (0x36)\n 55, // input 20 (0x14) => '7' (0x37)\n 56, // input 21 (0x15) => '8' (0x38)\n 57, // input 22 (0x16) => '9' (0x39)\n 64, // input 23 (0x17) => '@' (0x40)\n 65, // input 24 (0x18) => 'A' (0x41)\n 66, // input 25 (0x19) => 'B' (0x42)\n 67, // input 26 (0x1A) => 'C' (0x43)\n 68, // input 27 (0x1B) => 'D' (0x44)\n 69, // input 28 (0x1C) => 'E' (0x45)\n 70, // input 29 (0x1D) => 'F' (0x46)\n 71, // input 30 (0x1E) => 'G' (0x47)\n 72, // input 31 (0x1F) => 'H' (0x48)\n 73, // input 32 (0x20) => 'I' (0x49)\n 74, // input 33 (0x21) => 'J' (0x4A)\n 75, // input 34 (0x22) => 'K' (0x4B)\n 76, // input 35 (0x23) => 'L' (0x4C)\n 77, // input 36 (0x24) => 'M' (0x4D)\n 78, // input 37 (0x25) => 'N' (0x4E)\n 80, // input 38 (0x26) => 'P' (0x50)\n 81, // input 39 (0x27) => 'Q' (0x51)\n 82, // input 40 (0x28) => 'R' (0x52)\n 83, // input 41 (0x29) => 'S' (0x53)\n 84, // input 42 (0x2A) => 'T' (0x54)\n 85, // input 43 (0x2B) => 'U' (0x55)\n 86, // input 44 (0x2C) => 'V' (0x56)\n 88, // input 45 (0x2D) => 'X' (0x58)\n 89, // input 46 (0x2E) => 'Y' (0x59)\n 90, // input 47 (0x2F) => 'Z' (0x5A)\n 91, // input 48 (0x30) => '[' (0x5B)\n 96, // input 49 (0x31) => '`' (0x60)\n 97, // input 50 (0x32) => 'a' (0x61)\n 98, // input 51 (0x33) => 'b' (0x62)\n 99, // input 52 (0x34) => 'c' (0x63)\n 100, // input 53 (0x35) => 'd' (0x64)\n 101, // input 54 (0x36) => 'e' (0x65)\n 104, // input 55 (0x37) => 'h' (0x68)\n 105, // input 56 (0x38) => 'i' (0x69)\n 106, // input 57 (0x39) => 'j' (0x6A)\n 107, // input 58 (0x3A) => 'k' (0x6B)\n 108, // input 59 (0x3B) => 'l' (0x6C)\n 109, // input 60 (0x3C) => 'm' (0x6D)\n 112, // input 61 (0x3D) => 'p' (0x70)\n 113, // input 62 (0x3E) => 'q' (0x71)\n 114, // input 63 (0x3F) => 'r' (0x72)\n];\n#[rustfmt::skip]\npub const BINHEX_DECODE: &[u8; 256] = &[\n INVALID_VALUE, // input 0 (0x0)\n INVALID_VALUE, // input 1 (0x1)\n INVALID_VALUE, // input 2 (0x2)\n INVALID_VALUE, // input 3 (0x3)\n INVALID_VALUE, // input 4 (0x4)\n INVALID_VALUE, // input 5 (0x5)\n INVALID_VALUE, // input 6 (0x6)\n INVALID_VALUE, // input 7 (0x7)\n INVALID_VALUE, // input 8 (0x8)\n INVALID_VALUE, // input 9 (0x9)\n INVALID_VALUE, // input 10 (0xA)\n INVALID_VALUE, // input 11 (0xB)\n INVALID_VALUE, // input 12 (0xC)\n INVALID_VALUE, // input 13 (0xD)\n INVALID_VALUE, // input 14 (0xE)\n INVALID_VALUE, // input 15 (0xF)\n INVALID_VALUE, // input 16 (0x10)\n INVALID_VALUE, // input 17 (0x11)\n INVALID_VALUE, // input 18 (0x12)\n INVALID_VALUE, // input 19 (0x13)\n INVALID_VALUE, // input 20 (0x14)\n INVALID_VALUE, // input 21 (0x15)\n INVALID_VALUE, // input 22 (0x16)\n INVALID_VALUE, // input 23 (0x17)\n INVALID_VALUE, // input 24 (0x18)\n INVALID_VALUE, // input 25 (0x19)\n INVALID_VALUE, // input 26 (0x1A)\n INVALID_VALUE, // input 27 (0x1B)\n INVALID_VALUE, // input 28 (0x1C)\n INVALID_VALUE, // input 29 (0x1D)\n INVALID_VALUE, // input 30 (0x1E)\n INVALID_VALUE, // input 31 (0x1F)\n INVALID_VALUE, // input 32 (0x20)\n 0, // input 33 (0x21 char '!') => 0 (0x0)\n 1, // input 34 (0x22 char '\"') => 1 (0x1)\n 2, // input 35 (0x23 char '#') => 2 (0x2)\n 3, // input 36 (0x24 char '$') => 3 (0x3)\n 4, // input 37 (0x25 char '%') => 4 (0x4)\n 5, // input 38 (0x26 char '&') => 5 (0x5)\n 6, // input 39 (0x27 char ''') => 6 (0x6)\n 7, // input 40 (0x28 char '(') => 7 (0x7)\n 8, // input 41 (0x29 char ')') => 8 (0x8)\n 9, // input 42 (0x2A char '*') => 9 (0x9)\n 10, // input 43 (0x2B char '+') => 10 (0xA)\n 11, // input 44 (0x2C char ',') => 11 (0xB)\n 12, // input 45 (0x2D char '-') => 12 (0xC)\n INVALID_VALUE, // input 46 (0x2E)\n INVALID_VALUE, // input 47 (0x2F)\n 13, // input 48 (0x30 char '0') => 13 (0xD)\n 14, // input 49 (0x31 char '1') => 14 (0xE)\n 15, // input 50 (0x32 char '2') => 15 (0xF)\n 16, // input 51 (0x33 char '3') => 16 (0x10)\n 17, // input 52 (0x34 char '4') => 17 (0x11)\n 18, // input 53 (0x35 char '5') => 18 (0x12)\n 19, // input 54 (0x36 char '6') => 19 (0x13)\n 20, // input 55 (0x37 char '7') => 20 (0x14)\n 21, // input 56 (0x38 char '8') => 21 (0x15)\n 22, // input 57 (0x39 char '9') => 22 (0x16)\n INVALID_VALUE, // input 58 (0x3A)\n INVALID_VALUE, // input 59 (0x3B)\n INVALID_VALUE, // input 60 (0x3C)\n INVALID_VALUE, // input 61 (0x3D)\n INVALID_VALUE, // input 62 (0x3E)\n INVALID_VALUE, // input 63 (0x3F)\n 23, // input 64 (0x40 char '@') => 23 (0x17)\n 24, // input 65 (0x41 char 'A') => 24 (0x18)\n 25, // input 66 (0x42 char 'B') => 25 (0x19)\n 26, // input 67 (0x43 char 'C') => 26 (0x1A)\n 27, // input 68 (0x44 char 'D') => 27 (0x1B)\n 28, // input 69 (0x45 char 'E') => 28 (0x1C)\n 29, // input 70 (0x46 char 'F') => 29 (0x1D)\n 30, // input 71 (0x47 char 'G') => 30 (0x1E)\n 31, // input 72 (0x48 char 'H') => 31 (0x1F)\n 32, // input 73 (0x49 char 'I') => 32 (0x20)\n 33, // input 74 (0x4A char 'J') => 33 (0x21)\n 34, // input 75 (0x4B char 'K') => 34 (0x22)\n 35, // input 76 (0x4C char 'L') => 35 (0x23)\n 36, // input 77 (0x4D char 'M') => 36 (0x24)\n 37, // input 78 (0x4E char 'N') => 37 (0x25)\n INVALID_VALUE, // input 79 (0x4F)\n 38, // input 80 (0x50 char 'P') => 38 (0x26)\n 39, // input 81 (0x51 char 'Q') => 39 (0x27)\n 40, // input 82 (0x52 char 'R') => 40 (0x28)\n 41, // input 83 (0x53 char 'S') => 41 (0x29)\n 42, // input 84 (0x54 char 'T') => 42 (0x2A)\n 43, // input 85 (0x55 char 'U') => 43 (0x2B)\n 44, // input 86 (0x56 char 'V') => 44 (0x2C)\n INVALID_VALUE, // input 87 (0x57)\n 45, // input 88 (0x58 char 'X') => 45 (0x2D)\n 46, // input 89 (0x59 char 'Y') => 46 (0x2E)\n 47, // input 90 (0x5A char 'Z') => 47 (0x2F)\n 48, // input 91 (0x5B char '[') => 48 (0x30)\n INVALID_VALUE, // input 92 (0x5C)\n INVALID_VALUE, // input 93 (0x5D)\n INVALID_VALUE, // input 94 (0x5E)\n INVALID_VALUE, // input 95 (0x5F)\n 49, // input 96 (0x60 char '`') => 49 (0x31)\n 50, // input 97 (0x61 char 'a') => 50 (0x32)\n 51, // input 98 (0x62 char 'b') => 51 (0x33)\n 52, // input 99 (0x63 char 'c') => 52 (0x34)\n 53, // input 100 (0x64 char 'd') => 53 (0x35)\n 54, // input 101 (0x65 char 'e') => 54 (0x36)\n INVALID_VALUE, // input 102 (0x66)\n INVALID_VALUE, // input 103 (0x67)\n 55, // input 104 (0x68 char 'h') => 55 (0x37)\n 56, // input 105 (0x69 char 'i') => 56 (0x38)\n 57, // input 106 (0x6A char 'j') => 57 (0x39)\n 58, // input 107 (0x6B char 'k') => 58 (0x3A)\n 59, // input 108 (0x6C char 'l') => 59 (0x3B)\n 60, // input 109 (0x6D char 'm') => 60 (0x3C)\n INVALID_VALUE, // input 110 (0x6E)\n INVALID_VALUE, // input 111 (0x6F)\n 61, // input 112 (0x70 char 'p') => 61 (0x3D)\n 62, // input 113 (0x71 char 'q') => 62 (0x3E)\n 63, // input 114 (0x72 char 'r') => 63 (0x3F)\n INVALID_VALUE, // input 115 (0x73)\n INVALID_VALUE, // input 116 (0x74)\n INVALID_VALUE, // input 117 (0x75)\n INVALID_VALUE, // input 118 (0x76)\n INVALID_VALUE, // input 119 (0x77)\n INVALID_VALUE, // input 120 (0x78)\n INVALID_VALUE, // input 121 (0x79)\n INVALID_VALUE, // input 122 (0x7A)\n INVALID_VALUE, // input 123 (0x7B)\n INVALID_VALUE, // input 124 (0x7C)\n INVALID_VALUE, // input 125 (0x7D)\n INVALID_VALUE, // input 126 (0x7E)\n INVALID_VALUE, // input 127 (0x7F)\n INVALID_VALUE, // input 128 (0x80)\n INVALID_VALUE, // input 129 (0x81)\n INVALID_VALUE, // input 130 (0x82)\n INVALID_VALUE, // input 131 (0x83)\n INVALID_VALUE, // input 132 (0x84)\n INVALID_VALUE, // input 133 (0x85)\n INVALID_VALUE, // input 134 (0x86)\n INVALID_VALUE, // input 135 (0x87)\n INVALID_VALUE, // input 136 (0x88)\n INVALID_VALUE, // input 137 (0x89)\n INVALID_VALUE, // input 138 (0x8A)\n INVALID_VALUE, // input 139 (0x8B)\n INVALID_VALUE, // input 140 (0x8C)\n INVALID_VALUE, // input 141 (0x8D)\n INVALID_VALUE, // input 142 (0x8E)\n INVALID_VALUE, // input 143 (0x8F)\n INVALID_VALUE, // input 144 (0x90)\n INVALID_VALUE, // input 145 (0x91)\n INVALID_VALUE, // input 146 (0x92)\n INVALID_VALUE, // input 147 (0x93)\n INVALID_VALUE, // input 148 (0x94)\n INVALID_VALUE, // input 149 (0x95)\n INVALID_VALUE, // input 150 (0x96)\n INVALID_VALUE, // input 151 (0x97)\n INVALID_VALUE, // input 152 (0x98)\n INVALID_VALUE, // input 153 (0x99)\n INVALID_VALUE, // input 154 (0x9A)\n INVALID_VALUE, // input 155 (0x9B)\n INVALID_VALUE, // input 156 (0x9C)\n INVALID_VALUE, // input 157 (0x9D)\n INVALID_VALUE, // input 158 (0x9E)\n INVALID_VALUE, // input 159 (0x9F)\n INVALID_VALUE, // input 160 (0xA0)\n INVALID_VALUE, // input 161 (0xA1)\n INVALID_VALUE, // input 162 (0xA2)\n INVALID_VALUE, // input 163 (0xA3)\n INVALID_VALUE, // input 164 (0xA4)\n INVALID_VALUE, // input 165 (0xA5)\n INVALID_VALUE, // input 166 (0xA6)\n INVALID_VALUE, // input 167 (0xA7)\n INVALID_VALUE, // input 168 (0xA8)\n INVALID_VALUE, // input 169 (0xA9)\n INVALID_VALUE, // input 170 (0xAA)\n INVALID_VALUE, // input 171 (0xAB)\n INVALID_VALUE, // input 172 (0xAC)\n INVALID_VALUE, // input 173 (0xAD)\n INVALID_VALUE, // input 174 (0xAE)\n INVALID_VALUE, // input 175 (0xAF)\n INVALID_VALUE, // input 176 (0xB0)\n INVALID_VALUE, // input 177 (0xB1)\n INVALID_VALUE, // input 178 (0xB2)\n INVALID_VALUE, // input 179 (0xB3)\n INVALID_VALUE, // input 180 (0xB4)\n INVALID_VALUE, // input 181 (0xB5)\n INVALID_VALUE, // input 182 (0xB6)\n INVALID_VALUE, // input 183 (0xB7)\n INVALID_VALUE, // input 184 (0xB8)\n INVALID_VALUE, // input 185 (0xB9)\n INVALID_VALUE, // input 186 (0xBA)\n INVALID_VALUE, // input 187 (0xBB)\n INVALID_VALUE, // input 188 (0xBC)\n INVALID_VALUE, // input 189 (0xBD)\n INVALID_VALUE, // input 190 (0xBE)\n INVALID_VALUE, // input 191 (0xBF)\n INVALID_VALUE, // input 192 (0xC0)\n INVALID_VALUE, // input 193 (0xC1)\n INVALID_VALUE, // input 194 (0xC2)\n INVALID_VALUE, // input 195 (0xC3)\n INVALID_VALUE, // input 196 (0xC4)\n INVALID_VALUE, // input 197 (0xC5)\n INVALID_VALUE, // input 198 (0xC6)\n INVALID_VALUE, // input 199 (0xC7)\n INVALID_VALUE, // input 200 (0xC8)\n INVALID_VALUE, // input 201 (0xC9)\n INVALID_VALUE, // input 202 (0xCA)\n INVALID_VALUE, // input 203 (0xCB)\n INVALID_VALUE, // input 204 (0xCC)\n INVALID_VALUE, // input 205 (0xCD)\n INVALID_VALUE, // input 206 (0xCE)\n INVALID_VALUE, // input 207 (0xCF)\n INVALID_VALUE, // input 208 (0xD0)\n INVALID_VALUE, // input 209 (0xD1)\n INVALID_VALUE, // input 210 (0xD2)\n INVALID_VALUE, // input 211 (0xD3)\n INVALID_VALUE, // input 212 (0xD4)\n INVALID_VALUE, // input 213 (0xD5)\n INVALID_VALUE, // input 214 (0xD6)\n INVALID_VALUE, // input 215 (0xD7)\n INVALID_VALUE, // input 216 (0xD8)\n INVALID_VALUE, // input 217 (0xD9)\n INVALID_VALUE, // input 218 (0xDA)\n INVALID_VALUE, // input 219 (0xDB)\n INVALID_VALUE, // input 220 (0xDC)\n INVALID_VALUE, // input 221 (0xDD)\n INVALID_VALUE, // input 222 (0xDE)\n INVALID_VALUE, // input 223 (0xDF)\n INVALID_VALUE, // input 224 (0xE0)\n INVALID_VALUE, // input 225 (0xE1)\n INVALID_VALUE, // input 226 (0xE2)\n INVALID_VALUE, // input 227 (0xE3)\n INVALID_VALUE, // input 228 (0xE4)\n INVALID_VALUE, // input 229 (0xE5)\n INVALID_VALUE, // input 230 (0xE6)\n INVALID_VALUE, // input 231 (0xE7)\n INVALID_VALUE, // input 232 (0xE8)\n INVALID_VALUE, // input 233 (0xE9)\n INVALID_VALUE, // input 234 (0xEA)\n INVALID_VALUE, // input 235 (0xEB)\n INVALID_VALUE, // input 236 (0xEC)\n INVALID_VALUE, // input 237 (0xED)\n INVALID_VALUE, // input 238 (0xEE)\n INVALID_VALUE, // input 239 (0xEF)\n INVALID_VALUE, // input 240 (0xF0)\n INVALID_VALUE, // input 241 (0xF1)\n INVALID_VALUE, // input 242 (0xF2)\n INVALID_VALUE, // input 243 (0xF3)\n INVALID_VALUE, // input 244 (0xF4)\n INVALID_VALUE, // input 245 (0xF5)\n INVALID_VALUE, // input 246 (0xF6)\n INVALID_VALUE, // input 247 (0xF7)\n INVALID_VALUE, // input 248 (0xF8)\n INVALID_VALUE, // input 249 (0xF9)\n INVALID_VALUE, // input 250 (0xFA)\n INVALID_VALUE, // input 251 (0xFB)\n INVALID_VALUE, // input 252 (0xFC)\n INVALID_VALUE, // input 253 (0xFD)\n INVALID_VALUE, // input 254 (0xFE)\n INVALID_VALUE, // input 255 (0xFF)\n];", "\n#[test]\nfn alignment_check() {\n let p: *const u8 = STANDARD_DECODE_HOLDER.data.as_ptr();\n assert_eq!((p as u64) % 64, 0);\n let p: *const u8 = URL_SAFE_DECODE_HOLDER.data.as_ptr();\n assert_eq!((p as u64) % 64, 0);\n let p: *const u8 = CRYPT_DECODE_HOLDER.data.as_ptr();\n assert_eq!((p as u64) % 64, 0);\n let p: *const u8 = BCRYPT_DECODE_HOLDER.data.as_ptr();\n assert_eq!((p as u64) % 64, 0);\n let p: *const u8 = IMAP_MUTF7_DECODE_HOLDER.data.as_ptr();\n assert_eq!((p as u64) % 64, 0);\n let p: *const u8 = BINHEX_DECODE_HOLDER.data.as_ptr();\n assert_eq!((p as u64) % 64, 0);\n}" ]
[ 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [27, 526, 147, 1957], "buggy_code_start_loc": [27, 446, 141, 0], "filenames": ["Cargo.toml", "src/decode.rs", "src/lib.rs", "src/tables.rs"], "fixing_code_end_loc": [29, 563, 147, 2006], "fixing_code_start_loc": [28, 447, 141, 1], "message": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:apache:teaclave_sgx_sdk:1.1.3:*:*:*:*:rust:*:*", "matchCriteriaId": "9F4F7C7A-759B-410D-BD62-A7691A5034CB", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "In Apache Teaclave Rust SGX SDK 1.1.3, a side-channel vulnerability in base64 PEM file decoding allows system-level (administrator) attackers to obtain information about secret RSA keys via a controlled-channel and side-channel attack on software running in isolated environments that can be single stepped, especially Intel SGX."}, {"lang": "es", "value": "En Apache Teaclave Rust SGX SDK versi\u00f3n 1.1.3, una vulnerabilidad de canal lateral en la decodificaci\u00f3n de archivos PEM base64, permite a atacantes a nivel de sistema (administrador) obtener informaci\u00f3n sobre claves RSA secretas por medio de un ataque de canal controlado y de canal lateral en software ejecut\u00e1ndose entornos aislados que pueden ser de un solo paso, especialmente Intel SGX"}], "evaluatorComment": null, "id": "CVE-2021-24117", "lastModified": "2022-05-13T17:36:58.683", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 4.0, "confidentialityImpact": "PARTIAL", "integrityImpact": "NONE", "vectorString": "AV:N/AC:L/Au:S/C:P/I:N/A:N", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 4.9, "baseSeverity": "MEDIUM", "confidentialityImpact": "HIGH", "integrityImpact": "NONE", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:N/A:N", "version": "3.1"}, "exploitabilityScore": 1.2, "impactScore": 3.6, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2021-07-14T14:15:08.810", "references": [{"source": "cve@mitre.org", "tags": ["Product", "Third Party Advisory"], "url": "https://docs.rs/crate/sgx_tstd/1.1.1"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/UzL-ITS/util-lookup/blob/main/cve-vulnerability-publication.md"}, {"source": "cve@mitre.org", "tags": ["Issue Tracking", "Patch", "Third Party Advisory"], "url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-203"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/dingelish/rust-base64/commit/a554b7ae880553db6dde8a387101a093911d5b2a"}, "type": "CWE-203"}
35
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>\n * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>\n * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>\n * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>\n * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>\n * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@capnetworks.com>\n * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>\n * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>\n * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>\n * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>\n * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>\n * Copyright (C) 2010-2014 Philippe Grand <philippe.grand@atoo-net.com>\n * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>\n * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>\n * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>\n * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>\n * Copyright (C) 2014 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n *\t\\file htdocs/core/class/html.form.class.php\n * \\ingroup core\n *\t\\brief File of class with all html predefined components\n */", "\n/**\n *\tClass to manage generation of HTML components\n *\tOnly common components must be here.\n *\n * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable\n */\nclass Form\n{\n\tvar $db;\n\tvar $error;\n\tvar $num;", "\t// Cache arrays\n\tvar $cache_types_paiements=array();\n\tvar $cache_conditions_paiements=array();\n\tvar $cache_availability=array();\n\tvar $cache_demand_reason=array();\n\tvar $cache_types_fees=array();\n\tvar $cache_vatrates=array();", "\n\t/**\n\t * Constructor\n\t *\n\t * @param\t\tDoliDB\t\t$db Database handler\n\t */\n\tpublic function __construct($db)\n\t{\n\t\t$this->db = $db;\n\t}", "\t/**\n\t * Output key field for an editable field\n\t *\n\t * @param string\t$text\t\t\tText of label or key to translate\n\t * @param string\t$htmlname\t\tName of select field ('edit' prefix will be added)\n\t * @param string\t$preselected Value to show/edit (not used in this function)\n\t * @param\tobject\t$object\t\t\tObject\n\t * @param\tboolean\t$perm\t\t\tPermission to allow button to edit parameter. Set it to 0 to have a not edited field.\n\t * @param\tstring\t$typeofdata\t\tType of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)\n\t * @param\tstring\t$moreparam\t\tMore param to add on a href URL.\n\t * @param int $fieldrequired 1 if we want to show field as mandatory using the \"fieldrequired\" CSS.\n\t * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '\n\t * @return\tstring\t\t\t\t\tHTML edit field\n\t */\n\tfunction editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0)\n\t{\n\t\tglobal $conf,$langs;", "\t\t$ret='';", "\t\t// TODO change for compatibility\n\t\tif (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))\n\t\t{\n\t\t\tif (! empty($perm))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t$ret.= '<div class=\"editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'\" id=\"'.$htmlname.'\">';\n\t\t\t\tif ($fieldrequired) $ret.='<span class=\"fieldrequired\">';\n\t\t\t\t$ret.= $langs->trans($text);\n\t\t\t\tif ($fieldrequired) $ret.='</span>';\n\t\t\t\t$ret.= '</div>'.\"\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ($fieldrequired) $ret.='<span class=\"fieldrequired\">';\n\t\t\t\t$ret.= $langs->trans($text);\n\t\t\t\tif ($fieldrequired) $ret.='</span>';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class=\"nobordernopadding\" width=\"100%\"><tr><td class=\"nowrap\">';\n\t\t\tif ($fieldrequired) $ret.='<span class=\"fieldrequired\">';\n\t\t\t$ret.=$langs->trans($text);\n\t\t\tif ($fieldrequired) $ret.='</span>';\n\t\t\tif (! empty($notabletag)) $ret.=' ';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align=\"right\">';\n\t\t\tif ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href=\"'.$_SERVER[\"PHP_SELF\"].'?action=edit'.$htmlname.'&amp;id='.$object->id.$moreparam.'\">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';\n\t\t\tif (! empty($notabletag) && $notabletag == 1) $ret.=' : ';\n\t\t\tif (! empty($notabletag) && $notabletag == 3) $ret.=' ';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';\n\t\t}", "\t\treturn $ret;\n\t}", "\t/**\n\t * Output value of a field for an editable field\n\t *\n\t * @param\tstring\t$text\t\t\tText of label (not used in this function)\n\t * @param\tstring\t$htmlname\t\tName of select field\n\t * @param\tstring\t$value\t\t\tValue to show/edit\n\t * @param\tobject\t$object\t\t\tObject\n\t * @param\tboolean\t$perm\t\t\tPermission to allow button to edit parameter\n\t * @param\tstring\t$typeofdata\t\tType of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)\n\t * @param\tstring\t$editvalue\t\tWhen in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value\n\t * @param\tobject\t$extObject\t\tExternal object\n\t * @param\tmixed\t$custommsg\t\tString or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')\n\t * @param\tstring\t$moreparam\t\tMore param to add on a href URL\n\t * @param int $notabletag Do no output table tags\n\t * @param\tstring\t$formatfunc\t\tCall a specific function to output field\n\t * @return string\t\t\t\t\tHTML edit field\n\t */\n\tfunction editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='')\n\t{\n\t\tglobal $conf,$langs,$db;", "\t\t$ret='';", "\t\t// Check parameters\n\t\tif (empty($typeofdata)) return 'ErrorBadParameter';", "\t\t// When option to edit inline is activated\n\t\tif (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker\n\t\t{\n\t\t\t$ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (GETPOST('action','aZ09') == 'edit'.$htmlname)\n\t\t\t{\n\t\t\t\t$ret.=\"\\n\";\n\t\t\t\t$ret.='<form method=\"post\" action=\"'.$_SERVER[\"PHP_SELF\"].($moreparam?'?'.$moreparam:'').'\">';\n\t\t\t\t$ret.='<input type=\"hidden\" name=\"action\" value=\"set'.$htmlname.'\">';\n\t\t\t\t$ret.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t\t$ret.='<input type=\"hidden\" name=\"id\" value=\"'.$object->id.'\">';\n\t\t\t\tif (empty($notabletag)) $ret.='<table class=\"nobordernopadding\" cellpadding=\"0\" cellspacing=\"0\">';\n\t\t\t\tif (empty($notabletag)) $ret.='<tr><td>';\n\t\t\t\tif (preg_match('/^(string|email)/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t\t$ret.='<input type=\"text\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" value=\"'.($editvalue?$editvalue:$value).'\"'.($tmp[1]?' size=\"'.$tmp[1].'\"':'').'>';\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^(numeric|amount)/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t\t$valuetoshow=price2num($editvalue?$editvalue:$value);\n\t\t\t\t\t$ret.='<input type=\"text\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" value=\"'.($valuetoshow!=''?price($valuetoshow):'').'\"'.($tmp[1]?' size=\"'.$tmp[1].'\"':'').'>';\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t\t$cols=$tmp[2];\n\t\t\t\t\t$morealt='';\n\t\t\t\t\tif (preg_match('/%/',$cols))\n\t\t\t\t\t{\n\t\t\t\t\t\t$morealt=' style=\"width: '.$cols.'\"';\n\t\t\t\t\t\t$cols='';\n\t\t\t\t\t}\n\t\t\t\t\t$ret.='<textarea id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" wrap=\"soft\" rows=\"'.($tmp[1]?$tmp[1]:'20').'\"'.($cols?' cols=\"'.$cols.'\"':'class=\"quatrevingtpercent\"').$morealt.'\">'.($editvalue?$editvalue:$value).'</textarea>';\n\t\t\t\t}\n\t\t\t\telse if ($typeofdata == 'day' || $typeofdata == 'datepicker')\n\t\t\t\t{\n\t\t\t\t\t$ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1);\n\t\t\t\t}\n\t\t\t\telse if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')\n\t\t\t\t{\n\t\t\t\t\t$ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1);\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^select;/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));\n\t\t\t\t\t foreach($arraydata as $val)\n\t\t\t\t\t {\n\t\t\t\t\t\t $tmp=explode(':',$val);\n\t\t\t\t\t\t $arraylist[$tmp[0]]=$tmp[1];\n\t\t\t\t\t }\n\t\t\t\t\t $ret.=$this->selectarray($htmlname,$arraylist,$value);\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^ckeditor/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\t\t// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols\n\t\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';\n\t\t\t\t\t$doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));\n\t\t\t\t\t$ret.=$doleditor->Create(1);\n\t\t\t\t}\n\t\t\t\tif (empty($notabletag)) $ret.='</td>';", "\t\t\t\tif (empty($notabletag)) $ret.='<td align=\"left\">';\n\t\t\t\t//else $ret.='<div class=\"clearboth\"></div>';\n\t\t\t \t$ret.='<input type=\"submit\" class=\"button'.(empty($notabletag)?'':' ').'\" name=\"modify\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\t \tif (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'.\"\\n\";\n\t\t\t \t$ret.='<input type=\"submit\" class=\"button'.(empty($notabletag)?'':' ').'\" name=\"cancel\" value=\"'.$langs->trans(\"Cancel\").'\">';\n\t\t\t \tif (empty($notabletag)) $ret.='</td>';", "\t\t\t \tif (empty($notabletag)) $ret.='</tr></table>'.\"\\n\";\n\t\t\t\t$ret.='</form>'.\"\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1);\n\t\t\t\telseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');\n\t\t\t\telseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value);\n\t\t\t\telseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');\n\t\t\t\telseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');\n\t\t\t\telse if (preg_match('/^select;/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));\n\t\t\t\t\tforeach($arraydata as $val)\n\t\t\t\t\t{\n\t\t\t\t\t\t$tmp=explode(':',$val);\n\t\t\t\t\t\t$arraylist[$tmp[0]]=$tmp[1];\n\t\t\t\t\t}\n\t\t\t\t\t$ret.=$arraylist[$value];\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^ckeditor/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmpcontent=dol_htmlentitiesbr($value);\n\t\t\t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n\t\t\t\t\t{\n\t\t\t\t\t\t$firstline=preg_replace('/<br>.*/','',$tmpcontent);\n\t\t\t\t\t\t$firstline=preg_replace('/[\\n\\r].*/','',$firstline);\n\t\t\t\t\t\t$tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');\n\t\t\t\t\t}\n\t\t\t\t\t$ret.=$tmpcontent;\n\t\t\t\t}\n\t\t\t\telse $ret.=$value;", "\t\t\t\tif ($formatfunc && method_exists($object, $formatfunc))\n\t\t\t\t{\n\t\t\t\t\t$ret=$object->$formatfunc($ret);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $ret;\n\t}", "\t/**\n\t * Output edit in place form\n\t *\n\t * @param\tobject\t$object\t\t\tObject\n\t * @param\tstring\t$value\t\t\tValue to show/edit\n\t * @param\tstring\t$htmlname\t\tDIV ID (field name)\n\t * @param\tint\t\t$condition\t\tCondition to edit\n\t * @param\tstring\t$inputType\t\tType of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')\n\t * @param\tstring\t$editvalue\t\tWhen in edit mode, use this value as $value instead of value\n\t * @param\tobject\t$extObject\t\tExternal object\n\t * @param\tmixed\t$custommsg\t\tString or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')\n\t * @return\tstring \t\t \tHTML edit in place\n\t */\n\tprivate function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)\n\t{\n\t\tglobal $conf;", "\t\t$out='';", "\t\t// Check parameters\n\t\tif ($inputType == 'textarea') $value = dol_nl2br($value);\n\t\telse if (preg_match('/^numeric/',$inputType)) $value = price($value);\n\t\telse if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');", "\t\tif ($condition)\n\t\t{\n\t\t\t$element\t\t= false;\n\t\t\t$table_element\t= false;\n\t\t\t$fk_element\t\t= false;\n\t\t\t$loadmethod\t\t= false;\n\t\t\t$savemethod\t\t= false;\n\t\t\t$ext_element\t= false;\n\t\t\t$button_only\t= false;\n\t\t\t$inputOption = '';", "\t\t\tif (is_object($object))\n\t\t\t{\n\t\t\t\t$element = $object->element;\n\t\t\t\t$table_element = $object->table_element;\n\t\t\t\t$fk_element = $object->id;\n\t\t\t}", "\t\t\tif (is_object($extObject))\n\t\t\t{\n\t\t\t\t$ext_element = $extObject->element;\n\t\t\t}", "\t\t\tif (preg_match('/^(string|email|numeric)/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0];\n\t\t\t\tif (! empty($tmp[1])) $inputOption=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $savemethod=$tmp[2];\n\t\t\t\t$out.= '<input id=\"width_'.$htmlname.'\" value=\"'.$inputOption.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t}\n\t\t\telse if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0];\n\t\t\t\tif (! empty($tmp[1])) $inputOption=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $savemethod=$tmp[2];", "\t\t\t\t$out.= '<input id=\"timestamp\" type=\"hidden\"/>'.\"\\n\"; // Use for timestamp format\n\t\t\t}\n\t\t\telse if (preg_match('/^(select|autocomplete)/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0]; $loadmethod=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $savemethod=$tmp[2];\n\t\t\t\tif (! empty($tmp[3])) $button_only=true;\n\t\t\t}\n\t\t\telse if (preg_match('/^textarea/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0];\n\t\t\t\t$rows=(empty($tmp[1])?'8':$tmp[1]);\n\t\t\t\t$cols=(empty($tmp[2])?'80':$tmp[2]);\n\t\t\t}\n\t\t\telse if (preg_match('/^ckeditor/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0]; $toolbar=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $width=$tmp[2];\n\t\t\t\tif (! empty($tmp[3])) $heigth=$tmp[3];\n\t\t\t\tif (! empty($tmp[4])) $savemethod=$tmp[4];", "\t\t\t\tif (! empty($conf->fckeditor->enabled))\n\t\t\t\t{\n\t\t\t\t\t$out.= '<input id=\"ckeditor_toolbar\" value=\"'.$toolbar.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$inputType = 'textarea';\n\t\t\t\t}\n\t\t\t}", "\t\t\t$out.= '<input id=\"element_'.$htmlname.'\" value=\"'.$element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t$out.= '<input id=\"table_element_'.$htmlname.'\" value=\"'.$table_element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t$out.= '<input id=\"fk_element_'.$htmlname.'\" value=\"'.$fk_element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t$out.= '<input id=\"loadmethod_'.$htmlname.'\" value=\"'.$loadmethod.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\tif (! empty($savemethod))\t$out.= '<input id=\"savemethod_'.$htmlname.'\" value=\"'.$savemethod.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\tif (! empty($ext_element))\t$out.= '<input id=\"ext_element_'.$htmlname.'\" value=\"'.$ext_element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\tif (! empty($custommsg))\n\t\t\t{\n\t\t\t\tif (is_array($custommsg))\n\t\t\t\t{\n\t\t\t\t\tif (!empty($custommsg['success']))\n\t\t\t\t\t\t$out.= '<input id=\"successmsg_'.$htmlname.'\" value=\"'.$custommsg['success'].'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t\tif (!empty($custommsg['error']))\n\t\t\t\t\t\t$out.= '<input id=\"errormsg_'.$htmlname.'\" value=\"'.$custommsg['error'].'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t$out.= '<input id=\"successmsg_'.$htmlname.'\" value=\"'.$custommsg.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t}\n\t\t\tif ($inputType == 'textarea') {\n\t\t\t\t$out.= '<input id=\"textarea_'.$htmlname.'_rows\" value=\"'.$rows.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t$out.= '<input id=\"textarea_'.$htmlname.'_cols\" value=\"'.$cols.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t}\n\t\t\t$out.= '<span id=\"viewval_'.$htmlname.'\" class=\"viewval_'.$inputType.($button_only ? ' inactive' : ' active').'\">'.$value.'</span>'.\"\\n\";\n\t\t\t$out.= '<span id=\"editval_'.$htmlname.'\" class=\"editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject\">'.(! empty($editvalue) ? $editvalue : $value).'</span>'.\"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$out = $value;\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t *\tShow a text and picto with tooltip on text or picto.\n\t * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip\n\t *\n\t *\t@param\tstring\t\t$text\t\t\t\tText to show\n\t *\t@param\tstring\t\t$htmltext\t\t\tHTML content of tooltip. Must be HTML/UTF8 encoded.\n\t *\t@param\tint\t\t\t$tooltipon\t\t\t1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2\n\t *\t@param\tint\t\t\t$direction\t\t\t-1=image is before, 0=no image, 1=image is after\n\t *\t@param\tstring\t\t$img\t\t\t\tHtml code for image (use img_xxx() function to get it)\n\t *\t@param\tstring\t\t$extracss\t\t\tAdd a CSS style to td tags\n\t *\t@param\tint\t\t\t$notabs\t\t\t\t0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span\n\t *\t@param\tstring\t\t$incbefore\t\t\tInclude code before the text\n\t *\t@param\tint\t\t\t$noencodehtmltext\tDo not encode into html entity the htmltext\n\t * @param string $tooltiptrigger\t\t''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)\n\t * @param\tint\t\t\t$forcenowrap\t\tForce no wrap between text and picto (works with notabs=2 only)\n\t *\t@return\tstring\t\t\t\t\t\t\tCode html du tooltip (texte+picto)\n\t *\t@see\tUse function textwithpicto if you can.\n\t * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip\n\t */\n\tfunction textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)\n\t{\n\t\tglobal $conf;", "\t\tif ($incbefore) $text = $incbefore.$text;\n\t\tif (! $htmltext) return $text;", "\t\t$tag='td';\n\t\tif ($notabs == 2) $tag='div';\n\t\tif ($notabs == 3) $tag='span';\n\t\t// Sanitize tooltip\n\t\t$htmltext=str_replace(\"\\\\\",\"\\\\\\\\\",$htmltext);\n\t\t$htmltext=str_replace(\"\\r\",\"\",$htmltext);\n\t\t$htmltext=str_replace(\"\\n\",\"\",$htmltext);", "\t\t$extrastyle='';\n\t\tif ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }\n\t\tif ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }", "\t\t$classfortooltip='classfortooltip';", "\t\t$s='';$textfordialog='';", "\t\tif ($tooltiptrigger == '')\n\t\t{\n\t\t\t$htmltext=str_replace('\"',\"&quot;\",$htmltext);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$classfortooltip='classfortooltiponclick';\n\t\t\t$textfordialog.='<div style=\"display: none;\" id=\"idfortooltiponclick_'.$tooltiptrigger.'\" class=\"classfortooltiponclicktext\">'.$htmltext.'</div>';\n\t\t}\n\t\tif ($tooltipon == 2 || $tooltipon == 3)\n\t\t{\n\t\t\t$paramfortooltipimg=' class=\"'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'\" style=\"padding: 0px;'.($extrastyle?' '.$extrastyle:'').'\"';\n\t\t\tif ($tooltiptrigger == '') $paramfortooltipimg.=' title=\"'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'\"'; // Attribut to put on img tag to store tooltip\n\t\t\telse $paramfortooltipimg.=' dolid=\"'.$tooltiptrigger.'\"';\n\t\t}\n\t\telse $paramfortooltipimg =($extracss?' class=\"'.$extracss.'\"':'').($extrastyle?' style=\"'.$extrastyle.'\"':''); // Attribut to put on td text tag\n\t\tif ($tooltipon == 1 || $tooltipon == 3)\n\t\t{\n\t\t\t$paramfortooltiptd=' class=\"'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'\" style=\"padding: 0px;'.($extrastyle?' '.$extrastyle:'').'\" ';\n\t\t\tif ($tooltiptrigger == '') $paramfortooltiptd.=' title=\"'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'\"'; // Attribut to put on td tag to store tooltip\n\t\t\telse $paramfortooltiptd.=' dolid=\"'.$tooltiptrigger.'\"';\n\t\t}\n\t\telse $paramfortooltiptd =($extracss?' class=\"'.$extracss.'\"':'').($extrastyle?' style=\"'.$extrastyle.'\"':''); // Attribut to put on td text tag\n\t\tif (empty($notabs)) $s.='<table class=\"nobordernopadding\" summary=\"\"><tr style=\"height: auto;\">';\n\t\telseif ($notabs == 2) $s.='<div class=\"inline-block'.($forcenowrap?' nowrap':'').'\">';\n\t\t// Define value if value is before\n\t\tif ($direction < 0) {\n\t\t\t$s.='<'.$tag.$paramfortooltipimg;\n\t\t\tif ($tag == 'td') {\n\t\t\t\t$s .= ' valign=\"top\" width=\"14\"';\n\t\t\t}\n\t\t\t$s.= '>'.$textfordialog.$img.'</'.$tag.'>';\n\t\t}\n\t\t// Use another method to help avoid having a space in value in order to use this value with jquery\n\t\t// Define label\n\t\tif ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';\n\t\t// Define value if value is after\n\t\tif ($direction > 0) {\n\t\t\t$s.='<'.$tag.$paramfortooltipimg;\n\t\t\tif ($tag == 'td') $s .= ' valign=\"middle\" width=\"14\"';\n\t\t\t$s.= '>'.$textfordialog.$img.'</'.$tag.'>';\n\t\t}\n\t\tif (empty($notabs)) $s.='</tr></table>';\n\t\telseif ($notabs == 2) $s.='</div>';", "\t\treturn $s;\n\t}", "\t/**\n\t *\tShow a text with a picto and a tooltip on picto\n\t *\n\t *\t@param\tstring\t$text\t\t\t\tText to show\n\t *\t@param string\t$htmltext\t \tContent of tooltip\n\t *\t@param\tint\t\t$direction\t\t\t1=Icon is after text, -1=Icon is before text, 0=no icon\n\t * \t@param\tstring\t$type\t\t\t\tType of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath\n\t * @param string\t$extracss Add a CSS style to td, div or span tag\n\t * @param int\t\t$noencodehtmltext Do not encode into html entity the htmltext\n\t * @param\tint\t\t$notabs\t\t\t\t0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span\n\t * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)\n\t * @param\tint\t\t$forcenowrap\t\tForce no wrap between text and picto (works with notabs=2 only)\n\t * \t@return\tstring\t\t\t\t\t\tHTML code of text, picto, tooltip\n\t */\n\tfunction textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)\n\t{\n\t\tglobal $conf, $langs;", "\t\t$alt = '';\n\t\tif ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv(\"ClickToShowHelp\");", "\t\t//For backwards compatibility\n\t\tif ($type == '0') $type = 'info';\n\t\telseif ($type == '1') $type = 'help';", "\t\t// If info or help with no javascript, show only text\n\t\tif (empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\tif ($type == 'info' || $type == 'help')\treturn $text;\n\t\t\telse\n\t\t\t{\n\t\t\t\t$alt = $htmltext;\n\t\t\t\t$htmltext = '';\n\t\t\t}\n\t\t}", "\t\t// If info or help with smartphone, show only text (tooltip hover can't works)\n\t\tif (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))\n\t\t{\n\t\t\tif ($type == 'info' || $type == 'help') return $text;\n\t\t}\n\t\t// If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)\n\t\tif (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))\n\t\t{\n\t\t\tif ($type == 'info' || $type == 'help') return $text;\n\t\t}", "\t\tif ($type == 'info') $img = img_help(0, $alt);\n\t\telseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);\n\t\telseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');\n\t\telseif ($type == 'admin') $img = img_picto($alt, 'star');\n\t\telseif ($type == 'warning') $img = img_warning($alt);\n\t\telse $img = img_picto($alt, $type);", "\t\treturn $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);\n\t}", "\t/**\n\t * Generate select HTML to choose massaction\n\t *\n\t * @param\tstring\t$selected\t\tValue auto selected when at least one record is selected. Not a preselected value. Use '0' by default.\n\t * @param\tint\t\t$arrayofaction\tarray('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.\n\t * @param int $alwaysvisible 1=select button always visible\n\t * @return\tstring\t\t\t\t\tSelect list\n\t */\n\tfunction selectMassAction($selected, $arrayofaction, $alwaysvisible=0)\n\t{\n\t\tglobal $conf,$langs,$hookmanager;", "\t\tif (count($arrayofaction) == 0) return;", "\t\t$disabled=0;\n\t\t$ret='<div class=\"centpercent center\">';\n\t\t$ret.='<select class=\"flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect\" name=\"massaction\"'.($disabled?' disabled=\"disabled\"':'').'>';", "\t\t// Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook\n\t\tif (empty($reshook))\n\t\t{\n\t\t\t$ret.='<option value=\"0\"'.($disabled?' disabled=\"disabled\"':'').'>-- '.$langs->trans(\"SelectAction\").' --</option>';\n\t\t\tforeach($arrayofaction as $code => $label)\n\t\t\t{\n\t\t\t\t$ret.='<option value=\"'.$code.'\"'.($disabled?' disabled=\"disabled\"':'').'>'.$label.'</option>';\n\t\t\t}\n\t\t}\n\t\t$ret.=$hookmanager->resPrint;", "\t\t$ret.='</select>';\n\t\t// Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button\n\t\t$ret.='<input type=\"submit\" name=\"confirmmassactioninvisible\" style=\"display: none\" tabindex=\"-1\">';\t// Hidden button BEFORE so it is the one used when we submit with ENTER.\n\t\t$ret.='<input type=\"submit\" disabled name=\"confirmmassaction\" class=\"button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed\" value=\"'.dol_escape_htmltag($langs->trans(\"Confirm\")).'\">';\n\t\t$ret.='</div>';", "\t\tif (! empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\t$ret.='<!-- JS CODE TO ENABLE mass action select -->\n \t\t<script type=\"text/javascript\">\n \t\tfunction initCheckForSelect(mode)\t/* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */\n \t\t{\n \t\t\tatleastoneselected=0;\n \t \t\tjQuery(\".checkforselect\").each(function( index ) {\n \t \t\t\t\t/* console.log( index + \": \" + $( this ).text() ); */\n \t \t\t\t\tif ($(this).is(\\':checked\\')) atleastoneselected++;\n \t \t\t\t});\n\t\t\t\t\tconsole.log(\"initCheckForSelect mode=\"+mode+\" atleastoneselected=\"+atleastoneselected);\n \t \t\t\tif (atleastoneselected || '.$alwaysvisible.')\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massaction\").show();\n \t\t\t '.($selected ? 'if (atleastoneselected) { jQuery(\".massactionselect\").val(\"'.$selected.'\"); jQuery(\".massactionconfirmed\").prop(\\'disabled\\', false); }' : '').'\n \t\t\t '.($selected ? 'if (! atleastoneselected) { jQuery(\".massactionselect\").val(\"0\"); jQuery(\".massactionconfirmed\").prop(\\'disabled\\', true); } ' : '').'\n \t \t\t\t}\n \t \t\t\telse\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massaction\").hide();\n \t }\n \t\t}", " \tjQuery(document).ready(function () {\n \t\tinitCheckForSelect(0);\n \t\tjQuery(\".checkforselect\").click(function() {\n \t\t\tinitCheckForSelect(1);\n \t \t\t});\n \t \t\tjQuery(\".massactionselect\").change(function() {\n \t\t\tvar massaction = $( this ).val();\n \t\t\tvar urlform = $( this ).closest(\"form\").attr(\"action\").replace(\"#show_files\",\"\");\n \t\t\tif (massaction == \"builddoc\")\n {\n urlform = urlform + \"#show_files\";\n \t }\n \t\t\t$( this ).closest(\"form\").attr(\"action\", urlform);\n console.log(\"we select a mass action \"+massaction+\" - \"+urlform);\n \t /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */\n \t\t\tif ($(this).val() != \\'0\\')\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massactionconfirmed\").prop(\\'disabled\\', false);\n \t \t\t\t}\n \t \t\t\telse\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massactionconfirmed\").prop(\\'disabled\\', true);\n \t \t\t\t}\n \t });\n \t});\n \t\t</script>\n \t';\n\t\t}", "\t\treturn $ret;\n\t}", "\t/**\n\t * Return combo list of activated countries, into language of user\n\t *\n\t * @param\tstring\t$selected Id or Code or Label of preselected country\n\t * @param string\t$htmlname Name of html select object\n\t * @param string\t$htmloption Options html on select object\n\t * @param\tinteger\t$maxlength\t\tMax length for labels (0=no limit)\n\t * @param\tstring\t$morecss\t\tMore css class\n\t * @param\tstring\t$usecodeaskey\t'code3'=Use code on 3 alpha as key, 'code2\"=Use code on 2 alpha as key\n\t * @return string \t\tHTML string with select\n\t */\n\tfunction select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300',$usecodeaskey='')\n\t{\n\t\tglobal $conf,$langs;", "\t\t$langs->load(\"dict\");", "\t\t$out='';\n\t\t$countryArray=array();\n\t\t$favorite=array();\n\t\t$label=array();\n\t\t$atleastonefavorite=0;", "\t\t$sql = \"SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_country\";\n\t\t$sql.= \" WHERE active > 0\";\n\t\t//$sql.= \" ORDER BY code ASC\";", "\t\tdol_syslog(get_class($this).\"::select_country\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out.= '<select id=\"select'.$htmlname.'\" class=\"flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\" '.$htmloption.'>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\t$foundselected=false;", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$countryArray[$i]['rowid'] \t\t= $obj->rowid;\n\t\t\t\t\t$countryArray[$i]['code_iso'] \t= $obj->code_iso;\n\t\t\t\t\t$countryArray[$i]['code_iso3'] \t= $obj->code_iso3;\n\t\t\t\t\t$countryArray[$i]['label']\t\t= ($obj->code_iso && $langs->transnoentitiesnoconv(\"Country\".$obj->code_iso)!=\"Country\".$obj->code_iso?$langs->transnoentitiesnoconv(\"Country\".$obj->code_iso):($obj->label!='-'?$obj->label:''));\n\t\t\t\t\t$countryArray[$i]['favorite'] = $obj->favorite;\n\t\t\t\t\t$favorite[$i]\t\t\t\t\t= $obj->favorite;\n\t\t\t\t\t$label[$i] = dol_string_unaccent($countryArray[$i]['label']);\n\t\t\t\t\t$i++;\n\t\t\t\t}", "\t\t\t\tarray_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);", "\t\t\t\tforeach ($countryArray as $row)\n\t\t\t\t{\n\t\t\t\t\tif ($row['favorite'] && $row['code_iso']) $atleastonefavorite++;\n\t\t\t\t\tif (empty($row['favorite']) && $atleastonefavorite)\n\t\t\t\t\t{\n\t\t\t\t\t\t$atleastonefavorite=0;\n\t\t\t\t\t\t$out.= '<option a value=\"\" disabled class=\"selectoptiondisabledwhite\">----------------------</option>';\n\t\t\t\t\t}\n\t\t\t\t\tif ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )\n\t\t\t\t\t{\n\t\t\t\t\t\t$foundselected=true;\n\t\t\t\t\t\t$out.= '<option b value=\"'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'\" selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option c value=\"'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'\">';\n\t\t\t\t\t}\n\t\t\t\t\tif ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');\n\t\t\t\t\telse $out.= '&nbsp;';\n\t\t\t\t\tif ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';\n\t\t\t\t\t$out.= '</option>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\t// Make select dynamic\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t$out .= ajax_combobox('select'.$htmlname);", "\t\treturn $out;\n\t}", "\t/**\n\t * Return select list of incoterms\n\t *\n\t * @param\tstring\t$selected \t\tId or Code of preselected incoterm\n\t * @param\tstring\t$location_incoterms Value of input location\n\t * @param\tstring\t$page \t\t\tDefined the form action\n\t * @param string\t$htmlname \t\tName of html select object\n\t * @param string\t$htmloption \t\tOptions html on select object\n\t * \t@param\tint\t\t$forcecombo\t\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @param\tarray\t$events\t\t\t\t\tEvent options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @return string \t\t\t\tHTML string with select and input\n\t */\n\tfunction select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())\n\t{\n\t\tglobal $conf,$langs;", "\t\t$langs->load(\"dict\");", "\t\t$out='';\n\t\t$incotermArray=array();", "\t\t$sql = \"SELECT rowid, code\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_incoterms\";\n\t\t$sql.= \" WHERE active > 0\";\n\t\t$sql.= \" ORDER BY code ASC\";", "\t\tdol_syslog(get_class($this).\"::select_incoterm\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tif ($conf->use_javascript_ajax && ! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, $events);\n\t\t\t}", "\t\t\tif (!empty($page))\n\t\t\t{\n\t\t\t\t$out .= '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\t\t$out .= '<input type=\"hidden\" name=\"action\" value=\"set_incoterms\">';\n\t\t\t\t$out .= '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t}", "\t\t\t$out.= '<select id=\"'.$htmlname.'\" class=\"flat selectincoterm minwidth100imp noenlargeonsmartphone\" name=\"'.$htmlname.'\" '.$htmloption.'>';\n\t\t\t$out.= '<option value=\"0\">&nbsp;</option>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\t$foundselected=false;", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$incotermArray[$i]['rowid'] = $obj->rowid;\n\t\t\t\t\t$incotermArray[$i]['code'] = $obj->code;\n\t\t\t\t\t$i++;\n\t\t\t\t}", "\t\t\t\tforeach ($incotermArray as $row)\n\t\t\t\t{\n\t\t\t\t\tif ($selected && ($selected == $row['rowid'] || $selected == $row['code']))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$row['rowid'].'\" selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$row['rowid'].'\">';\n\t\t\t\t\t}", "\t\t\t\t\tif ($row['code']) $out.= $row['code'];", "\t\t\t\t\t$out.= '</option>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '</select>';", "\t\t\t$out .= '<input id=\"location_incoterms\" class=\"maxwidth100onsmartphone\" name=\"location_incoterms\" value=\"'.$location_incoterms.'\">';", "\t\t\tif (!empty($page))\n\t\t\t{\n\t\t\t\t$out .= '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\"></form>';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn list of types of lines (product or service)\n\t * \tExample: 0=product, 1=service, 9=other (for external module)\n\t *\n\t *\t@param string\t$selected Preselected type\n\t *\t@param string\t$htmlname Name of field in html form\n\t * \t@param\tint\t\t$showempty\t\tAdd an empty field\n\t * \t@param\tint\t\t$hidetext\t\tDo not show label 'Type' before combo box (used only if there is at least 2 choices to select)\n\t * \t@param\tinteger\t$forceall\t\t1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service')\n\t * @return\tvoid\n\t */\n\tfunction select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)\n\t{\n\t\tglobal $db,$langs,$user,$conf;", "\t\t// If product & services are enabled or both disabled.\n\t\tif ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))\n\t\t|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )\n\t\t{\n\t\t\tif (empty($hidetext)) print $langs->trans(\"Type\").': ';\n\t\t\tprint '<select class=\"flat\" id=\"select_'.$htmlname.'\" name=\"'.$htmlname.'\">';\n\t\t\tif ($showempty)\n\t\t\t{\n\t\t\t\tprint '<option value=\"-1\"';\n\t\t\t\tif ($selected == -1) print ' selected';\n\t\t\t\tprint '>&nbsp;</option>';\n\t\t\t}", "\t\t\tprint '<option value=\"0\"';\n\t\t\tif (0 == $selected) print ' selected';\n\t\t\tprint '>'.$langs->trans(\"Product\");", "\t\t\tprint '<option value=\"1\"';\n\t\t\tif (1 == $selected) print ' selected';\n\t\t\tprint '>'.$langs->trans(\"Service\");", "\t\t\tprint '</select>';\n\t\t\t//if ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t\t}\n\t\tif (empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled))\n\t\t{\n\t\t\tprint $langs->trans(\"Service\");\n\t\t\tprint '<input type=\"hidden\" name=\"'.$htmlname.'\" value=\"1\">';\n\t\t}\n\t\tif (empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled))\n\t\t{\n\t\t\tprint $langs->trans(\"Product\");\n\t\t\tprint '<input type=\"hidden\" name=\"'.$htmlname.'\" value=\"0\">';\n\t\t}\n\t\tif ($forceall < 0)\t// This should happened only for contracts when both predefined product and service are disabled.\n\t\t{\n\t\t\tprint '<input type=\"hidden\" name=\"'.$htmlname.'\" value=\"1\">';\t// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1\n\t\t}\n\t}", "\t/**\n\t *\tLoad into cache cache_types_fees, array of types of fees\n\t *\n\t *\t@return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_types_fees()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_types_fees);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$langs->load(\"trips\");", "\t\t$sql = \"SELECT c.code, c.label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_type_fees as c\";\n\t\t$sql.= \" WHERE active > 0\";", "\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;", "\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));\n\t\t\t\t$this->cache_types_fees[$obj->code] = $label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\tasort($this->cache_types_fees);", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of types of notes\n\t *\n\t *\t@param\tstring\t\t$selected\t\tPreselected type\n\t *\t@param string\t\t$htmlname\t\tName of field in form\n\t * \t@param\tint\t\t\t$showempty\t\tAdd an empty field\n\t * \t@return\tvoid\n\t */\n\tfunction select_type_fees($selected='',$htmlname='type',$showempty=0)\n\t{\n\t\tglobal $user, $langs;", "\t\tdol_syslog(__METHOD__.\" selected=\".$selected.\", htmlname=\".$htmlname, LOG_DEBUG);", "\t\t$this->load_cache_types_fees();", "\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\tif ($showempty)\n\t\t{\n\t\t\tprint '<option value=\"-1\"';\n\t\t\tif ($selected == -1) print ' selected';\n\t\t\tprint '>&nbsp;</option>';\n\t\t}", "\t\tforeach($this->cache_types_fees as $key => $value)\n\t\t{\n\t\t\tprint '<option value=\"'.$key.'\"';\n\t\t\tif ($key == $selected) print ' selected';\n\t\t\tprint '>';\n\t\t\tprint $value;\n\t\t\tprint '</option>';\n\t\t}", "\t\tprint '</select>';\n\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\n\t/**\n\t * Return HTML code to select a company.\n\t *\n\t * @param\t\tint\t\t\t$selected\t\t\t\tPreselected products\n\t * @param\t\tstring\t\t$htmlname\t\t\t\tName of HTML select field (must be unique in page)\n\t * @param\t\tint\t\t\t$filter\t\t\t\t\tFilter on thirdparty\n\t * @param\t\tint\t\t\t$limit\t\t\t\t\tLimit on number of returned lines\n\t * @param\t\tarray\t\t$ajaxoptions\t\t\tOptions for ajax_autocompleter\n\t * \t@param\t\tint\t\t\t$forcecombo\t\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @return\t\tstring\t\t\t\t\t\t\t\tReturn select box for thirdparty.\n\t * @deprecated\t3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)\n\t */\n\tfunction select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)\n\t{\n \t\treturn $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);\n\t}", "\t/**\n\t * Output html form to select a third party\n\t *\n\t *\t@param\tstring\t$selected \t\tPreselected type\n\t *\t@param string\t$htmlname \t\tName of field in form\n\t * @param string\t$filter \t\toptional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')\n\t *\t@param\tstring\t$showempty\t\t\t\tAdd an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')\n\t * \t@param\tint\t\t$showtype\t\t\t\tShow third party type in combolist (customer, prospect or supplier)\n\t * \t@param\tint\t\t$forcecombo\t\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @param\tarray\t$events\t\t\t\t\tAjax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t *\t@param\tint\t\t$limit\t\t\t\t\tMaximum number of elements\n\t * @param\tstring\t$morecss\t\t\t\tAdd more css styles to the SELECT component\n\t *\t@param string\t$moreparam \t\tAdd more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t *\t@param\tstring\t$selected_input_value\tValue of preselected input text (for use with ajax)\n\t * @param\tint\t\t$hidelabel\t\t\t\tHide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)\n\t * @param\tarray\t$ajaxoptions\t\t\tOptions for ajax_autocompleter\n\t * \t@return\tstring\t\t\t\t\t\t\tHTML string with select box for thirdparty.\n\t */\n\tfunction select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array())\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t$out='';", "\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)\n\t\t{\n\t\t\t// No immediate load of all database\n\t\t\t$placeholder='';\n\t\t\tif ($selected && empty($selected_input_value))\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';\n\t\t\t\t$societetmp = new Societe($this->db);\n\t\t\t\t$societetmp->fetch($selected);\n\t\t\t\t$selected_input_value=$societetmp->name;\n\t\t\t\tunset($societetmp);\n\t\t\t}\n\t\t\t// mode 1\n\t\t\t$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');\n\t\t\t$out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);\n\t\t\t$out.='<style type=\"text/css\">.ui-autocomplete { z-index: 250; }</style>';\n\t\t\tif (empty($hidelabel)) print $langs->trans(\"RefOrLabel\").' : ';\n\t\t\telse if ($hidelabel > 1) {\n\t\t\t\t$placeholder=' placeholder=\"'.$langs->trans(\"RefOrLabel\").'\"';\n\t\t\t\tif ($hidelabel == 2) {\n\t\t\t\t\t$out.= img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '<input type=\"text\" class=\"'.$morecss.'\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$selected_input_value.'\"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';\n\t\t\tif ($hidelabel == 3) {\n\t\t\t\t$out.= img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Immediate load of all database\n\t\t\t$out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Output html form to select a third party.\n\t * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.\n\t *\n\t *\t@param\tstring\t$selected Preselected type\n\t *\t@param string\t$htmlname Name of field in form", "\t * @param string\t$filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')", "\t *\t@param\tstring\t$showempty\t\tAdd an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')\n\t * \t@param\tint\t\t$showtype\t\tShow third party type in combolist (customer, prospect or supplier)\n\t * \t@param\tint\t\t$forcecombo\t\tForce to use standard HTML select component without beautification\n\t * @param\tarray\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @param\tstring\t$filterkey\t\tFilter on key value\n\t * @param\tint\t\t$outputmode\t\t0=HTML select string, 1=Array\n\t * @param\tint\t\t$limit\t\t\tLimit number of answers\n\t * @param\tstring\t$morecss\t\tAdd more css styles to the SELECT component\n\t *\t@param string\t$moreparam Add more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t * \t@return\tstring\t\t\t\t\tHTML string with\n\t */\n\tfunction select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='')\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t$out='';\n\t\t$num=0;\n\t\t$outarray=array();", "", "\n\t\t// On recherche les societes\n\t\t$sql = \"SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"societe as s\";\n\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= \", \".MAIN_DB_PREFIX.\"societe_commerciaux as sc\";\n\t\t$sql.= \" WHERE s.entity IN (\".getEntity('societe').\")\";\n\t\tif (! empty($user->societe_id)) $sql.= \" AND s.rowid = \".$user->societe_id;\n\t\tif ($filter) $sql.= \" AND (\".$filter.\")\";\n\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= \" AND s.rowid = sc.fk_soc AND sc.fk_user = \" .$user->id;\n\t\tif (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= \" AND s.status <> 0\";\n\t\t// Add criteria\n\t\tif ($filterkey && $filterkey != '')\n\t\t{\n\t\t\t$sql.=\" AND (\";\n\t\t\t$prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';\t// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on\n\t\t\t// For natural search\n\t\t\t$scrit = explode(' ', $filterkey);\n\t\t\t$i=0;\n\t\t\tif (count($scrit) > 1) $sql.=\"(\";\n\t\t\tforeach ($scrit as $crit) {\n\t\t\t\tif ($i > 0) $sql.=\" AND \";\n\t\t\t\t$sql.=\"(s.nom LIKE '\".$this->db->escape($prefix.$crit).\"%')\";\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tif (count($scrit) > 1) $sql.=\")\";\n\t\t\tif (! empty($conf->barcode->enabled))\n\t\t\t{\n\t\t\t\t$sql .= \" OR s.barcode LIKE '\".$this->db->escape($filterkey).\"%'\";\n\t\t\t}\n\t\t\t$sql.=\")\";\n\t\t}\n\t\t$sql.=$this->db->order(\"nom\",\"ASC\");\n\t\t$sql.=$this->db->plimit($limit, 0);", "\t\t// Build output string\n\t\tdol_syslog(get_class($this).\"::select_thirdparty_list\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t \tif (! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);\n\t\t\t}", "\t\t\t// Construct $out and $outarray\n\t\t\t$out.= '<select id=\"'.$htmlname.'\" class=\"flat'.($morecss?' '.$morecss:'').'\"'.($moreparam?' '.$moreparam:'').' name=\"'.$htmlname.'\">'.\"\\n\";", "\t\t\t$textifempty='';\n\t\t\t// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.\n\t\t\t//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';\n\t\t\tif (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))\n\t\t\t{\n\t\t\t\tif ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);\n\t\t\t\telse $textifempty.=$langs->trans(\"All\");\n\t\t\t}\n\t\t\tif ($showempty) $out.= '<option value=\"-1\">'.$textifempty.'</option>'.\"\\n\";", "\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$label='';\n\t\t\t\t\tif ($conf->global->SOCIETE_ADD_REF_IN_LIST) {\n\t\t\t\t\t\tif (($obj->client) && (!empty($obj->code_client))) {\n\t\t\t\t\t\t\t$label = $obj->code_client. ' - ';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {\n\t\t\t\t\t\t\t$label .= $obj->code_fournisseur. ' - ';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$label.=' '.$obj->name;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$label=$obj->name;\n\t\t\t\t\t}", "\t\t\t\t\tif(!empty($obj->name_alias)) {\n\t\t\t\t\t\t$label.=' ('.$obj->name_alias.')';\n\t\t\t\t\t}", "\t\t\t\t\tif ($showtype)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($obj->client || $obj->fournisseur) $label.=' (';\n\t\t\t\t\t\tif ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans(\"Customer\");\n\t\t\t\t\t\tif ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans(\"Prospect\");\n\t\t\t\t\t\tif ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans(\"Supplier\");\n\t\t\t\t\t\tif ($obj->client || $obj->fournisseur) $label.=')';\n\t\t\t\t\t}", "\t\t\t\t\tif (empty($outputmode))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($selected > 0 && $selected == $obj->rowid)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\" selected>'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\">'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tarray_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));\n\t\t\t\t\t}", "\t\t\t\t\t$i++;\n\t\t\t\t\tif (($i % 10) == 0) $out.=\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '</select>'.\"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\t$this->result=array('nbofthirdparties'=>$num);", "\t\tif ($outputmode) return $outarray;\n\t\treturn $out;\n\t}", "\n\t/**\n\t * \tReturn HTML combo list of absolute discounts\n\t *\n\t * \t@param\tstring\t$selected Id remise fixe pre-selectionnee\n\t * \t@param string\t$htmlname Nom champ formulaire\n\t * \t@param string\t$filter Criteres optionnels de filtre\n\t * \t\t@param\tint\t\t$socid\t\t\tId of thirdparty\n\t * \t\t@param\tint\t\t$maxvalue\t\tMax value for lines that can be selected\n\t * \t\t@return\tint\t\t\t\t\t\tReturn number of qualifed lines in list\n\t */\n\tfunction select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)\n\t{\n\t\tglobal $langs,$conf;", "\t\t// On recherche les remises\n\t\t$sql = \"SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,\";\n\t\t$sql.= \" re.description, re.fk_facture_source\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"societe_remise_except as re\";\n\t\t$sql.= \" WHERE re.fk_soc = \".(int) $socid;\n\t\t$sql.= \" AND re.entity = \" . $conf->entity;\n\t\tif ($filter) $sql.= \" AND \".$filter;\n\t\t$sql.= \" ORDER BY re.description ASC\";", "\t\tdol_syslog(get_class($this).\"::select_remises\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tprint '<select class=\"flat maxwidthonsmartphone\" name=\"'.$htmlname.'\">';\n\t\t\t$num = $this->db->num_rows($resql);", "\t\t\t$qualifiedlines=$num;", "\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tprint '<option value=\"0\">&nbsp;</option>';\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$desc=dol_trunc($obj->description,40);\n\t\t\t\t\tif (preg_match('/\\(CREDIT_NOTE\\)/', $desc)) $desc=preg_replace('/\\(CREDIT_NOTE\\)/', $langs->trans(\"CreditNote\"), $desc);\n\t\t\t\t\tif (preg_match('/\\(DEPOSIT\\)/', $desc)) $desc=preg_replace('/\\(DEPOSIT\\)/', $langs->trans(\"Deposit\"), $desc);\n\t\t\t\t\tif (preg_match('/\\(EXCESS RECEIVED\\)/', $desc)) $desc=preg_replace('/\\(EXCESS RECEIVED\\)/', $langs->trans(\"ExcessReceived\"), $desc);", "\t\t\t\t\t$selectstring='';\n\t\t\t\t\tif ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';", "\t\t\t\t\t$disabled='';\n\t\t\t\t\tif ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)\n\t\t\t\t\t{\n\t\t\t\t\t\t$qualifiedlines--;\n\t\t\t\t\t\t$disabled=' disabled';\n\t\t\t\t\t}", "\t\t\t\t\tif (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))\n\t\t\t\t\t{\n\t\t\t\t\t\t$tmpfac = new Facture($this->db);\n\t\t\t\t\t\tif ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;\n\t\t\t\t\t}", "\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans(\"HT\").' - '.price($obj->amount_ttc).' '.$langs->trans(\"TTC\").')</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tprint '</select>';\n\t\t\treturn $qualifiedlines;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of all contacts (for a third party or all)\n\t *\n\t *\t@param\tint\t\t$socid \tId ot third party or 0 for all\n\t *\t@param string\t$selected \tId contact pre-selectionne\n\t *\t@param string\t$htmlname \t Name of HTML field ('none' for a not editable field)\n\t *\t@param int\t\t$showempty 0=no empty value, 1=add an empty value\n\t *\t@param string\t$exclude List of contacts id to exclude\n\t *\t@param\tstring\t$limitto\t\tDisable answers that are not id in this array list\n\t *\t@param\tinteger\t$showfunction Add function into label\n\t *\t@param\tstring\t$moreclass\t\tAdd more class to class style\n\t *\t@param\tinteger\t$showsoc\t Add company into label\n\t * \t@param\tint\t\t$forcecombo\t\tForce to use combo box\n\t * @param\tarray\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @param\tbool\t$options_only\tReturn options only (for ajax treatment)\n\t * @param\tstring\t$moreparam\t\tAdd more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t * @param\tstring\t$htmlid\t\t\tHtml id to use instead of htmlname\n\t *\t@return\tint\t\t\t\t\t\t<0 if KO, Nb of contact in list if OK\n\t * @deprected\t\t\t\t\t\tYou can use selectcontacts directly (warning order of param was changed)\n\t */\n\tfunction select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')\n\t{\n\t\tprint $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);\n\t\treturn $this->num;\n\t}", "\t/**\n\t *\tReturn HTML code of the SELECT of list of all contacts (for a third party or all).\n\t * This also set the number of contacts found into $this->num\n\t *\n\t *\t@param\tint\t\t\t$socid \tId ot third party or 0 for all\n\t *\t@param array|int\t$selected \tArray of ID of pre-selected contact id\n\t *\t@param string\t\t$htmlname \t Name of HTML field ('none' for a not editable field)\n\t *\t@param int\t\t\t$showempty \t0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit)\n\t *\t@param string\t\t$exclude List of contacts id to exclude\n\t *\t@param\tstring\t\t$limitto\t\tDisable answers that are not id in this array list\n\t *\t@param\tinteger\t\t$showfunction Add function into label\n\t *\t@param\tstring\t\t$moreclass\t\tAdd more class to class style\n\t *\t@param\tbool\t\t$options_only\tReturn options only (for ajax treatment)\n\t *\t@param\tinteger\t\t$showsoc\t Add company into label\n\t * \t@param\tint\t\t\t$forcecombo\t\tForce to use combo box\n\t * @param\tarray\t\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @param\tstring\t\t$moreparam\t\tAdd more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t * @param\tstring\t\t$htmlid\t\t\tHtml id to use instead of htmlname\n\t *\t@return\t int\t\t\t\t\t\t<0 if KO, Nb of contact in list if OK\n\t */\n\tfunction selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='')\n\t{\n\t\tglobal $conf,$langs;", "\t\t$langs->load('companies');", "\t\tif (empty($htmlid)) $htmlid = $htmlname;\n $out='';", "\t\t// On recherche les societes\n\t\t$sql = \"SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste\";\n\t\tif ($showsoc > 0) $sql.= \" , s.nom as company\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"socpeople as sp\";\n\t\tif ($showsoc > 0) $sql.= \" LEFT OUTER JOIN \".MAIN_DB_PREFIX .\"societe as s ON s.rowid=sp.fk_soc\";\n\t\t$sql.= \" WHERE sp.entity IN (\".getEntity('societe').\")\";\n\t\tif ($socid > 0) $sql.= \" AND sp.fk_soc=\".$socid;\n\t\tif (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= \" AND sp.statut <> 0\";\n\t\t$sql.= \" ORDER BY sp.lastname ASC\";", "\t\tdol_syslog(get_class($this).\"::select_contacts\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num=$this->db->num_rows($resql);", "\t\t\tif ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);\n\t\t\t}", "\t\t\tif ($htmlname != 'none' || $options_only) $out.= '<select class=\"flat'.($moreclass?' '.$moreclass:'').'\" id=\"'.$htmlid.'\" name=\"'.$htmlname.'\" '.(!empty($moreparam) ? $moreparam : '').'>';\n\t\t\tif ($showempty == 1) $out.= '<option value=\"0\"'.($selected=='0'?' selected':'').'>&nbsp;</option>';\n\t\t\tif ($showempty == 2) $out.= '<option value=\"0\"'.($selected=='0'?' selected':'').'>'.$langs->trans(\"Internal\").'</option>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';\n\t\t\t\t$contactstatic=new Contact($this->db);", "\t\t\t\tif (!is_array($selected)) $selected = array($selected);\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t\t$contactstatic->id=$obj->rowid;\n\t\t\t\t\t$contactstatic->lastname=$obj->lastname;\n\t\t\t\t\t$contactstatic->firstname=$obj->firstname;\n\t\t\t\t\tif ($obj->statut == 1){\n\t\t\t\t\tif ($htmlname != 'none')\n\t\t\t\t\t{\n\t\t\t\t\t\t$disabled=0;\n\t\t\t\t\t\tif (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;\n\t\t\t\t\t\tif (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;\n\t\t\t\t\t\tif (!empty($selected) && in_array($obj->rowid, $selected))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\t\tif ($disabled) $out.= ' disabled';\n\t\t\t\t\t\t\t$out.= ' selected>';\n\t\t\t\t\t\t\t$out.= $contactstatic->getFullName($langs);\n\t\t\t\t\t\t\tif ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';\n\t\t\t\t\t\t\tif (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';\n\t\t\t\t\t\t\t$out.= '</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\t\tif ($disabled) $out.= ' disabled';\n\t\t\t\t\t\t\t$out.= '>';\n\t\t\t\t\t\t\t$out.= $contactstatic->getFullName($langs);\n\t\t\t\t\t\t\tif ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';\n\t\t\t\t\t\t\tif (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';\n\t\t\t\t\t\t\t$out.= '</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (in_array($obj->rowid, $selected))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= $contactstatic->getFullName($langs);\n\t\t\t\t\t\t\tif ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';\n\t\t\t\t\t\t\tif (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.= '<option value=\"-1\"'.($showempty==2?'':' selected').' disabled>'.$langs->trans($socid?\"NoContactDefinedForThirdParty\":\"NoContactDefined\").'</option>';\n\t\t\t}\n\t\t\tif ($htmlname != 'none' || $options_only)\n\t\t\t{\n\t\t\t\t$out.= '</select>';\n\t\t\t}", "\t\t\t$this->num = $num;\n\t\t\treturn $out;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn select list of users\n\t *\n\t * @param\tstring\t$selected Id user preselected\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue\n\t * @param array\t$exclude Array list of users id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param array\t$include Array list of users id to include\n\t * \t@param\tint\t\t$enableonly\t\tArray list of users id to be enabled. All other must be disabled\n\t * @param\tstring\t$force_entity\t'0' or Ids of environment to force\n\t * \t@return\tvoid\n\t * @deprecated\t\tUse select_dolusers instead\n\t * @see select_dolusers()\n\t */\n\tfunction select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')\n\t{\n\t\tprint $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);\n\t}", "\t/**\n\t *\tReturn select list of users\n\t *\n\t * @param\tstring\t$selected User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=list with no empty value, 1=add also an empty value into list\n\t * @param array\t$exclude Array list of users id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param array|string\t$include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me\n\t * \t@param\tarray\t$enableonly\t\tArray list of users id to be enabled. If defined, it means that others will be disabled\n\t * @param\tstring\t$force_entity\t'0' or Ids of environment to force\n\t * @param\tint\t\t$maxlength\t\tMaximum length of string into list (0=no limit)\n\t * @param\tint\t\t$showstatus\t\t0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status\n\t * @param\tstring\t$morefilter\t\tAdd more filters into sql request (Example: 'employee = 1')\n\t * @param\tinteger\t$show_every\t\t0=default list, 1=add also a value \"Everybody\" at beginning of list\n\t * @param\tstring\t$enableonlytext\tIf option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.\n\t * @param\tstring\t$morecss\t\tMore css\n\t * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).\n\t * \t@return\tstring\t\t\t\t\tHTML select string\n\t * @see select_dolgroups\n\t */\n\tfunction select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0)\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t// If no preselected user defined, we take current user\n\t\tif ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;", "\t\t$excludeUsers=null;\n\t\t$includeUsers=null;", "\t\t// Permettre l'exclusion d'utilisateurs\n\t\tif (is_array($exclude))\t$excludeUsers = implode(\",\",$exclude);\n\t\t// Permettre l'inclusion d'utilisateurs\n\t\tif (is_array($include))\t$includeUsers = implode(\",\",$include);\n\t\telse if ($include == 'hierarchy')\n\t\t{\n\t\t\t// Build list includeUsers to have only hierarchy\n\t\t\t$includeUsers = implode(\",\",$user->getAllChildIds(0));\n\t\t}\n\t\telse if ($include == 'hierarchyme')\n\t\t{\n\t\t\t// Build list includeUsers to have only hierarchy and current user\n\t\t\t$includeUsers = implode(\",\",$user->getAllChildIds(1));\n\t\t}", "\t\t$out='';", "\t\t// Forge request to select users\n\t\t$sql = \"SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity\";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \", e.label\";\n\t\t}\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"user as u\";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX .\"entity as e ON e.rowid=u.entity\";\n\t\t\tif ($force_entity) $sql.= \" WHERE u.entity IN (0,\".$force_entity.\")\";\n\t\t\telse $sql.= \" WHERE u.entity IS NOT NULL\";\n\t\t}\n\t\telse\n\t {\n\t\t\tif (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))\n\t\t\t{\n\t\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"usergroup_user as ug\";\n\t\t\t\t$sql.= \" ON ug.fk_user = u.rowid\";\n\t\t\t\t$sql.= \" WHERE ug.entity = \".$conf->entity;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$sql.= \" WHERE u.entity IN (0,\".$conf->entity.\")\";\n\t\t\t}\n\t\t}\n\t\tif (! empty($user->societe_id)) $sql.= \" AND u.fk_soc = \".$user->societe_id;\n\t\tif (is_array($exclude) && $excludeUsers) $sql.= \" AND u.rowid NOT IN (\".$excludeUsers.\")\";\n\t\tif ($includeUsers) $sql.= \" AND u.rowid IN (\".$includeUsers.\")\";\n\t\tif (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= \" AND u.statut <> 0\";\n\t\tif (! empty($morefilter)) $sql.=\" \".$morefilter;", "\t\tif(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){\n\t\t\t$sql.= \" ORDER BY u.firstname ASC\";\n\t\t}else{\n\t\t\t$sql.= \" ORDER BY u.lastname ASC\";\n\t\t}", "\t\tdol_syslog(get_class($this).\"::select_dolusers\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t \t\t// Enhance with select2\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname);", "\t\t\t\t// do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined\n\t\t\t\t$out.= '<select class=\"flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.($disabled?' disabled':'').'>';\n\t\t\t\tif ($show_empty) $out.= '<option value=\"-1\"'.((empty($selected) || $selected==-1)?' selected':'').'>&nbsp;</option>'.\"\\n\";\n\t\t\t\tif ($show_every) $out.= '<option value=\"-2\"'.(($selected==-2)?' selected':'').'>-- '.$langs->trans(\"Everybody\").' --</option>'.\"\\n\";", "\t\t\t\t$userstatic=new User($this->db);", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t\t$userstatic->id=$obj->rowid;\n\t\t\t\t\t$userstatic->lastname=$obj->lastname;\n\t\t\t\t\t$userstatic->firstname=$obj->firstname;", "\t\t\t\t\t$disableline='';\n\t\t\t\t\tif (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');", "\t\t\t\t\tif ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\tif ($disableline) $out.= ' disabled';\n\t\t\t\t\t\t$out.= ' selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\tif ($disableline) $out.= ' disabled';\n\t\t\t\t\t\t$out.= '>';\n\t\t\t\t\t}", "\t\t\t\t\t$fullNameMode = 0; //Lastname + firstname\n\t\t\t\t\tif(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){\n\t\t\t\t\t\t$fullNameMode = 1; //firstname + lastname\n\t\t\t\t\t}\n\t\t\t\t\t$out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);", "\t\t\t\t\t// Complete name with more info\n\t\t\t\t\t$moreinfo=0;\n\t\t\t\t\tif (! empty($conf->global->MAIN_SHOW_LOGIN))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= ($moreinfo?' - ':' (').$obj->login;\n\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t}\n\t\t\t\t\tif ($showstatus >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($obj->statut == 1 && $showstatus == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ($obj->statut == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (! $obj->entity)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').$langs->trans(\"AllEntities\");\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans(\"EntityNameNotDefined\"));\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t \t}\n\t\t\t\t\t}\n\t\t\t\t\t$out.=($moreinfo?')':'');\n\t\t\t\t\tif ($disableline && $disableline != '1')\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.=' - '.$disableline;\t// This is text from $enableonlytext parameter\n\t\t\t\t\t}\n\t\t\t\t\t$out.= '</option>';", "\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.= '<select class=\"flat\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" disabled>';\n\t\t\t\t$out.= '<option value=\"\">'.$langs->trans(\"None\").'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn select list of users. Selected users are stored into session.\n\t * List of users are provided into $_SESSION['assignedtouser'].\n\t *\n\t * @param string\t$action Value for $action\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=list without the empty value, 1=add empty value\n\t * @param array\t$exclude Array list of users id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param array\t$include Array list of users id to include or 'hierarchy' to have only supervised users\n\t * \t@param\tarray\t$enableonly\t\tArray list of users id to be enabled. All other must be disabled\n\t * @param\tint\t\t$force_entity\t'0' or Ids of environment to force\n\t * @param\tint\t\t$maxlength\t\tMaximum length of string into list (0=no limit)\n\t * @param\tint\t\t$showstatus\t\t0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status\n\t * @param\tstring\t$morefilter\t\tAdd more filters into sql request\n\t * @param\tint\t\t$showproperties\t\tShow properties of each attendees\n\t * @param\tarray\t$listofuserid\t\tArray with properties of each user\n\t * @param\tarray\t$listofcontactid\tArray with properties of each contact\n\t * @param\tarray\t$listofotherid\t\tArray with properties of each other contact\n\t * \t@return\tstring\t\t\t\t\tHTML select string\n\t * @see select_dolgroups\n\t */\n\tfunction select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())\n\t{\n\t\tglobal $conf, $user, $langs;", "\t\t$userstatic=new User($this->db);\n\t\t$out='';", "\t\t// Method with no ajax\n\t\t//$out.='<form method=\"POST\" action=\"'.$_SERVER[\"PHP_SELF\"].'\">';\n\t\tif ($action == 'view')\n\t\t{\n\t\t\t$out.='';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$out.='<input type=\"hidden\" class=\"removedassignedhidden\" name=\"removedassigned\" value=\"\">';\n\t\t\t$out.='<script type=\"text/javascript\" language=\"javascript\">jQuery(document).ready(function () { jQuery(\".removedassigned\").click(function() { jQuery(\".removedassignedhidden\").val(jQuery(this).val()); });})</script>';\n\t\t\t$out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);\n\t\t\t$out.=' <input type=\"submit\" class=\"button valignmiddle\" name=\"'.$action.'assignedtouser\" value=\"'.dol_escape_htmltag($langs->trans(\"Add\")).'\">';\n\t\t\t$out.='<br>';\n\t\t}\n\t\t$assignedtouser=array();\n\t\tif (!empty($_SESSION['assignedtouser']))\n\t\t{\n\t\t\t$assignedtouser=json_decode($_SESSION['assignedtouser'], true);\n\t\t}\n\t\t$nbassignetouser=count($assignedtouser);", "\t\tif ($nbassignetouser && $action != 'view') $out.='<br>';\n\t\tif ($nbassignetouser) $out.='<ul class=\"attendees\">';\n\t\t$i=0; $ownerid=0;\n\t\tforeach($assignedtouser as $key => $value)\n\t\t{\n\t\t\tif ($value['id'] == $ownerid) continue;", "\t\t\t$out.='<li>';\n\t\t\t$userstatic->fetch($value['id']);\n\t\t\t$out.= $userstatic->getNomUrl(-1);\n\t\t\tif ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans(\"Owner\").')'; }\n\t\t\tif ($nbassignetouser > 1 && $action != 'view') $out.=' <input type=\"image\" style=\"border: 0px;\" src=\"'.img_picto($langs->trans(\"Remove\"), 'delete', '', 0, 1).'\" value=\"'.$userstatic->id.'\" class=\"removedassigned\" id=\"removedassigned_'.$userstatic->id.'\" name=\"removedassigned_'.$userstatic->id.'\">';\n\t\t\t// Show my availability\n\t\t\tif ($showproperties)\n\t\t\t{\n\t\t\t\tif ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))\n\t\t\t\t{\n\t\t\t\t\t$out.='<div class=\"myavailability inline-block\">';\n\t\t\t\t\t$out.='&nbsp;-&nbsp;<span class=\"opacitymedium\">'.$langs->trans(\"Availability\").':</span> <input id=\"transparency\" class=\"marginleftonly marginrightonly\" '.($action == 'view'?'disabled':'').' type=\"checkbox\" name=\"transparency\"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans(\"Busy\");\n\t\t\t\t\t$out.='</div>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t//$out.=' '.($value['mandatory']?$langs->trans(\"Mandatory\"):$langs->trans(\"Optional\"));\n\t\t\t//$out.=' '.($value['transparency']?$langs->trans(\"Busy\"):$langs->trans(\"NotBusy\"));", "\t\t\t$out.='</li>';\n\t\t\t$i++;\n\t\t}\n\t\tif ($nbassignetouser) $out.='</ul>';", "\t\t//$out.='</form>';\n\t\treturn $out;\n\t}", "\n\t/**\n\t * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list\n\t *\n\t * @param\t\tint\t\t\t$selected\t\t\t\tPreselected products\n\t * @param\t\tstring\t\t$htmlname\t\t\t\tName of HTML select field (must be unique in page)\n\t * @param\t\tint\t\t\t$filtertype\t\t\t\tFilter on product type (''=nofilter, 0=product, 1=service)\n\t * @param\t\tint\t\t\t$limit\t\t\t\t\tLimit on number of returned lines\n\t * @param\t\tint\t\t\t$price_level\t\t\tLevel of price to show\n\t * @param\t\tint\t\t\t$status\t\t\t\t\t-1=Return all products, 0=Products not on sell, 1=Products on sell\n\t * @param\t\tint\t\t\t$finished\t\t\t\t2=all, 1=finished, 0=raw material\n\t * @param\t\tstring\t\t$selected_input_value\tValue of preselected input text (for use with ajax)\n\t * @param\t\tint\t\t\t$hidelabel\t\t\t\tHide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)\n\t * @param\t\tarray\t\t$ajaxoptions\t\t\tOptions for ajax_autocompleter\n\t * @param int\t\t\t$socid\t\t\t\t\tThirdparty Id (to get also price dedicated to this customer)\n\t * @param\t\tstring\t\t$showempty\t\t\t\t'' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.\n\t * \t@param\t\tint\t\t\t$forcecombo\t\t\t\tForce to use combo box\n\t * @param string $morecss Add more css on select\n\t * @param int $hidepriceinlabel 1=Hide prices in label\n\t * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseopen' = select products from open warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseclosed' = select products from closed warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseinternal' = select products from warehouses for internal correct/transfer only\n\t * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])\n\t * @return\t\tvoid\n\t */\n\tfunction select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())\n\t{\n\t\tglobal $langs,$conf;", "\t\t$price_level = (! empty($price_level) ? $price_level : 0);", "\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))\n\t\t{\n\t\t\t$placeholder='';", "\t\t\tif ($selected && empty($selected_input_value))\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\n\t\t\t\t$producttmpselect = new Product($this->db);\n\t\t\t\t$producttmpselect->fetch($selected);\n\t\t\t\t$selected_input_value=$producttmpselect->ref;\n\t\t\t\tunset($producttmpselect);\n\t\t\t}\n\t\t\t// mode=1 means customers products\n\t\t\t$urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;\n\t\t\t//Price by customer\n\t\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {\n\t\t\t\t$urloption.='&socid='.$socid;\n\t\t\t}\n\t\t\tprint ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);", "\t\t\tif (!empty($conf->variants->enabled)) {\n\t\t\t\t?>\n\t\t\t\t<script>", "\t\t\t\t\tselected = <?php echo json_encode($selected_combinations) ?>;\n\t\t\t\t\tcombvalues = {};", "\t\t\t\t\tjQuery(document).ready(function () {", "\t\t\t\t\t\tjQuery(\"input[name='prod_entry_mode']\").change(function () {\n\t\t\t\t\t\t\tif (jQuery(this).val() == 'free') {\n\t\t\t\t\t\t\t\tjQuery('div#attributes_box').empty();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});", "\t\t\t\t\t\tjQuery(\"input#<?php echo $htmlname ?>\").change(function () {", "\t\t\t\t\t\t\tif (!jQuery(this).val()) {\n\t\t\t\t\t\t\t\tjQuery('div#attributes_box').empty();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tjQuery.getJSON(\"<?php echo dol_buildpath('/variants/ajax/getCombinations.php', 2) ?>\", {\n\t\t\t\t\t\t\t\tid: jQuery(this).val()\n\t\t\t\t\t\t\t}, function (data) {\n\t\t\t\t\t\t\t\tjQuery('div#attributes_box').empty();", "\t\t\t\t\t\t\t\tjQuery.each(data, function (key, val) {", "\t\t\t\t\t\t\t\t\tcombvalues[val.id] = val.values;", "\t\t\t\t\t\t\t\t\tvar span = jQuery(document.createElement('div')).css({\n\t\t\t\t\t\t\t\t\t\t'display': 'table-row'\n\t\t\t\t\t\t\t\t\t});", "\t\t\t\t\t\t\t\t\tspan.append(\n\t\t\t\t\t\t\t\t\t\tjQuery(document.createElement('div')).text(val.label).css({\n\t\t\t\t\t\t\t\t\t\t\t'font-weight': 'bold',\n\t\t\t\t\t\t\t\t\t\t\t'display': 'table-cell',\n\t\t\t\t\t\t\t\t\t\t\t'text-align': 'right'\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t);", "\t\t\t\t\t\t\t\t\tvar html = jQuery(document.createElement('select')).attr('name', 'combinations[' + val.id + ']').css({\n\t\t\t\t\t\t\t\t\t\t'margin-left': '15px',\n\t\t\t\t\t\t\t\t\t\t'white-space': 'pre'\n\t\t\t\t\t\t\t\t\t}).append(\n\t\t\t\t\t\t\t\t\t\tjQuery(document.createElement('option')).val('')\n\t\t\t\t\t\t\t\t\t);", "\t\t\t\t\t\t\t\t\tjQuery.each(combvalues[val.id], function (key, val) {\n\t\t\t\t\t\t\t\t\t\tvar tag = jQuery(document.createElement('option')).val(val.id).html(val.value);", "\t\t\t\t\t\t\t\t\t\tif (selected[val.fk_product_attribute] == val.id) {\n\t\t\t\t\t\t\t\t\t\t\ttag.attr('selected', 'selected');\n\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\thtml.append(tag);\n\t\t\t\t\t\t\t\t\t});", "\t\t\t\t\t\t\t\t\tspan.append(html);\n\t\t\t\t\t\t\t\t\tjQuery('div#attributes_box').append(span);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t});", "\t\t\t\t\t\t<?php if ($selected): ?>\n\t\t\t\t\t\tjQuery(\"input#<?php echo $htmlname ?>\").change();\n\t\t\t\t\t\t<?php endif ?>\n\t\t\t\t\t});\n\t\t\t\t</script>\n <?php\n\t\t\t}\n\t\t\tif (empty($hidelabel)) print $langs->trans(\"RefOrLabel\").' : ';\n\t\t\telse if ($hidelabel > 1) {\n\t\t\t\t$placeholder=' placeholder=\"'.$langs->trans(\"RefOrLabel\").'\"';\n\t\t\t\tif ($hidelabel == 2) {\n\t\t\t\t\tprint img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t\t}\n\t\t\t}\n\t\t\tprint '<input type=\"text\" class=\"minwidth100\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$selected_input_value.'\"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';\n\t\t\tif ($hidelabel == 3) {\n\t\t\t\tprint img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprint $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of products for a customer\n\t *\n\t *\t@param int\t\t$selected Preselected product\n\t *\t@param string\t$htmlname Name of select html\n\t * @param\t\tstring\t$filtertype Filter on product type (''=nofilter, 0=product, 1=service)\n\t *\t@param int\t\t$limit Limit on number of returned lines\n\t *\t@param int\t\t$price_level Level of price to show\n\t * \t@param string\t$filterkey Filter on product\n\t *\t@param\t\tint\t\t$status -1=Return all products, 0=Products not on sell, 1=Products on sell\n\t * @param int\t\t$finished Filter on finished field: 2=No filter\n\t * @param int\t\t$outputmode 0=HTML select string, 1=Array\n\t * @param int\t\t$socid \t\t Thirdparty Id (to get also price dedicated to this customer)\n\t * @param\t\tstring\t$showempty\t\t '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.\n\t * \t@param\t\tint\t\t$forcecombo\t\t Force to use combo box\n\t * @param string $morecss Add more css on select\n\t * @param int $hidepriceinlabel 1=Hide prices in label\n\t * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseopen' = select products from open warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseclosed' = select products from closed warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseinternal' = select products from warehouses for internal correct/transfer only\n\t * @return array \t\t\t\t Array of keys for json\n\t */\n\tfunction select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')\n\t{\n\t\tglobal $langs,$conf,$user,$db;", "\t\t$out='';\n\t\t$outarray=array();", "\t\t$warehouseStatusArray = array();\n\t\tif (! empty($warehouseStatus))\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';\n\t\t\tif (preg_match('/warehouseclosed/', $warehouseStatus))\n\t\t\t{\n\t\t\t\t$warehouseStatusArray[] = Entrepot::STATUS_CLOSED;\n\t\t\t}\n\t\t\tif (preg_match('/warehouseopen/', $warehouseStatus))\n\t\t\t{\n\t\t\t\t$warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;\n\t\t\t}\n\t\t\tif (preg_match('/warehouseinternal/', $warehouseStatus))\n\t\t\t{\n\t\t\t\t$warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;\n\t\t\t}\n\t\t}", "\t\t$selectFields = \" p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression\";\n\t\t(count($warehouseStatusArray)) ? $selectFieldsGrouped = \", sum(ps.reel) as stock\" : $selectFieldsGrouped = \", p.stock\";", "\t\t$sql = \"SELECT \";\n\t\t$sql.= $selectFields . $selectFieldsGrouped;\n\t\t//Price by customer\n\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))\n\t\t{\n\t\t\t$sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';\n\t\t\t$sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';\n\t\t\t$selectFields.= \", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx\";\n\t\t}", "\t\t// Multilang : we add translation\n\t\tif (! empty($conf->global->MAIN_MULTILANGS))\n\t\t{\n\t\t\t$sql.= \", pl.label as label_translated\";\n\t\t\t$selectFields.= \", label_translated\";\n\t\t}\n\t\t// Price by quantity\n\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))\n\t\t{\n\t\t\t$sql.= \", (SELECT pp.rowid FROM \".MAIN_DB_PREFIX.\"product_price as pp WHERE pp.fk_product = p.rowid\";\n\t\t\tif ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= \" AND price_level=\".$price_level;\n\t\t\t$sql.= \" ORDER BY date_price\";\n\t\t\t$sql.= \" DESC LIMIT 1) as price_rowid\";\n\t\t\t$sql.= \", (SELECT pp.price_by_qty FROM \".MAIN_DB_PREFIX.\"product_price as pp WHERE pp.fk_product = p.rowid\";\t// price_by_qty is 1 if some prices by qty exists in subtable\n\t\t\tif ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= \" AND price_level=\".$price_level;\n\t\t\t$sql.= \" ORDER BY date_price\";\n\t\t\t$sql.= \" DESC LIMIT 1) as price_by_qty\";\n\t\t\t$selectFields.= \", price_rowid, price_by_qty\";\n\t\t}\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product as p\";\n\t\tif (count($warehouseStatusArray))\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_stock as ps on ps.fk_product = p.rowid\";\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"entrepot as e on ps.fk_entrepot = e.rowid\";\n\t\t}", "\t\t//Price by customer\n\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {\n\t\t\t$sql.=\" LEFT JOIN \".MAIN_DB_PREFIX.\"product_customer_price as pcp ON pcp.fk_soc=\".$socid.\" AND pcp.fk_product=p.rowid\";\n\t\t}\n\t\t// Multilang : we add translation\n\t\tif (! empty($conf->global->MAIN_MULTILANGS))\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='\". $langs->getDefaultLang() .\"'\";\n\t\t}", "\t\tif (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {\n\t\t\t$sql .= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_attribute_combination pac ON pac.fk_product_child = p.rowid\";\n\t\t}", "\t\t$sql.= ' WHERE p.entity IN ('.getEntity('product').')';\n\t\tif (count($warehouseStatusArray))\n\t\t{\n\t\t\t$sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';\n\t\t}", "\t\tif (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {\n\t\t\t$sql .= \" AND pac.rowid IS NULL\";\n\t\t}", "\t\tif ($finished == 0)\n\t\t{\n\t\t\t$sql.= \" AND p.finished = \".$finished;\n\t\t}\n\t\telseif ($finished == 1)\n\t\t{\n\t\t\t$sql.= \" AND p.finished = \".$finished;\n\t\t\tif ($status >= 0) $sql.= \" AND p.tosell = \".$status;\n\t\t}\n\t\telseif ($status >= 0)\n\t\t{\n\t\t\t$sql.= \" AND p.tosell = \".$status;\n\t\t}\n\t\tif (strval($filtertype) != '') $sql.=\" AND p.fk_product_type=\".$filtertype;\n\t\t// Add criteria on ref/label\n\t\tif ($filterkey != '')\n\t\t{\n\t\t\t$sql.=' AND (';\n\t\t\t$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';\t// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on\n\t\t\t// For natural search\n\t\t\t$scrit = explode(' ', $filterkey);\n\t\t\t$i=0;\n\t\t\tif (count($scrit) > 1) $sql.=\"(\";\n\t\t\tforeach ($scrit as $crit)\n\t\t\t{\n\t\t\t\tif ($i > 0) $sql.=\" AND \";\n\t\t\t\t$sql.=\"(p.ref LIKE '\".$db->escape($prefix.$crit).\"%' OR p.label LIKE '\".$db->escape($prefix.$crit).\"%'\";\n\t\t\t\tif (! empty($conf->global->MAIN_MULTILANGS)) $sql.=\" OR pl.label LIKE '\".$db->escape($prefix.$crit).\"%'\";\n\t\t\t\t$sql.=\")\";\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tif (count($scrit) > 1) $sql.=\")\";\n\t\t \tif (! empty($conf->barcode->enabled)) $sql.= \" OR p.barcode LIKE '\".$db->escape($prefix.$filterkey).\"%'\";\n\t\t\t$sql.=')';\n\t\t}\n\t\tif (count($warehouseStatusArray))\n\t\t{\n\t\t\t$sql.= ' GROUP BY'.$selectFields;\n\t\t}\n\t\t$sql.= $db->order(\"p.ref\");\n\t\t$sql.= $db->plimit($limit, 0);", "\t\t// Build output string\n\t\tdol_syslog(get_class($this).\"::select_produits_list search product\", LOG_DEBUG);\n\t\t$result=$this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';\n\t\t\t$num = $this->db->num_rows($result);", "\t\t\t$events=null;", "\t\t\tif (! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);\n\t\t\t}", "\t\t\t$out.='<select class=\"flat'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';", "\t\t\t$textifempty='';\n\t\t\t// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.\n\t\t\t//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';\n\t\t\tif (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))\n\t\t\t{\n\t\t\t\tif ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);\n\t\t\t\telse $textifempty.=$langs->trans(\"All\");\n\t\t\t}\n\t\t\tif ($showempty) $out.='<option value=\"0\" selected>'.$textifempty.'</option>';", "\t\t\t$i = 0;\n\t\t\twhile ($num && $i < $num)\n\t\t\t{\n\t\t\t\t$opt = '';\n\t\t\t\t$optJson = array();\n\t\t\t\t$objp = $this->db->fetch_object($result);", "\t\t\t\tif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)\n\t\t\t\t{ // Price by quantity will return many prices for the same product\n\t\t\t\t\t$sql = \"SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type\";\n\t\t\t\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product_price_by_qty\";\n\t\t\t\t\t$sql.= \" WHERE fk_product_price=\".$objp->price_rowid;\n\t\t\t\t\t$sql.= \" ORDER BY quantity ASC\";", "\t\t\t\t\tdol_syslog(get_class($this).\"::select_produits_list search price by qty\", LOG_DEBUG);\n\t\t\t\t\t$result2 = $this->db->query($sql);\n\t\t\t\t\tif ($result2)\n\t\t\t\t\t{\n\t\t\t\t\t\t$nb_prices = $this->db->num_rows($result2);\n\t\t\t\t\t\t$j = 0;\n\t\t\t\t\t\twhile ($nb_prices && $j < $nb_prices) {\n\t\t\t\t\t\t\t$objp2 = $this->db->fetch_object($result2);", "\t\t\t\t\t\t\t$objp->price_by_qty_rowid = $objp2->rowid;\n\t\t\t\t\t\t\t$objp->price_by_qty_price_base_type = $objp2->price_base_type;\n\t\t\t\t\t\t\t$objp->price_by_qty_quantity = $objp2->quantity;\n\t\t\t\t\t\t\t$objp->price_by_qty_unitprice = $objp2->unitprice;\n\t\t\t\t\t\t\t$objp->price_by_qty_remise_percent = $objp2->remise_percent;\n\t\t\t\t\t\t\t// For backward compatibility\n\t\t\t\t\t\t\t$objp->quantity = $objp2->quantity;\n\t\t\t\t\t\t\t$objp->price = $objp2->price;\n\t\t\t\t\t\t\t$objp->unitprice = $objp2->unitprice;\n\t\t\t\t\t\t\t$objp->remise_percent = $objp2->remise_percent;\n\t\t\t\t\t\t\t$objp->remise = $objp2->remise;", "\t\t\t\t\t\t\t$this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);", "\t\t\t\t\t\t\t$j++;", "\t\t\t\t\t\t\t// Add new entry\n\t\t\t\t\t\t\t// \"key\" value of json key array is used by jQuery automatically as selected value\n\t\t\t\t\t\t\t// \"label\" value of json key array is used by jQuery automatically as text for combo box\n\t\t\t\t\t\t\t$out.=$opt;\n\t\t\t\t\t\t\tarray_push($outarray, $optJson);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {\n\t\t\t\t\t\t$price_product = new Product($this->db);\n\t\t\t\t\t\t$price_product->fetch($objp->rowid, '', '', 1);\n\t\t\t\t\t\t$priceparser = new PriceParser($this->db);\n\t\t\t\t\t\t$price_result = $priceparser->parseProduct($price_product);\n\t\t\t\t\t\tif ($price_result >= 0) {\n\t\t\t\t\t\t\t$objp->price = $price_result;\n\t\t\t\t\t\t\t$objp->unitprice = $price_result;\n\t\t\t\t\t\t\t//Calculate the VAT\n\t\t\t\t\t\t\t$objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));\n\t\t\t\t\t\t\t$objp->price_ttc = price2num($objp->price_ttc,'MU');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);\n\t\t\t\t\t// Add new entry\n\t\t\t\t\t// \"key\" value of json key array is used by jQuery automatically as selected value\n\t\t\t\t\t// \"label\" value of json key array is used by jQuery automatically as text for combo box\n\t\t\t\t\t$out.=$opt;\n\t\t\t\t\tarray_push($outarray, $optJson);\n\t\t\t\t}", "\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$out.='</select>';", "\t\t\t$this->db->free($result);", "\t\t\tif (empty($outputmode)) return $out;\n\t\t\treturn $outarray;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}\n\t}", "\t/**\n\t * constructProductListOption\n\t *\n\t * @param \tresultset\t$objp\t\t\t Resultset of fetch\n\t * @param \tstring\t\t$opt\t\t\t Option (var used for returned value in string option format)\n\t * @param \tstring\t\t$optJson\t\t Option (var used for returned value in json format)\n\t * @param \tint\t\t\t$price_level\t Price level\n\t * @param \tstring\t\t$selected\t\t Preselected value\n\t * @param int $hidepriceinlabel Hide price in label\n\t * @return\tvoid\n\t */\n\tprivate function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)\n\t{\n\t\tglobal $langs,$conf,$user,$db;", "\t\t$outkey='';\n\t\t$outval='';\n\t\t$outref='';\n\t\t$outlabel='';\n\t\t$outdesc='';\n\t\t$outbarcode='';\n\t\t$outtype='';\n\t\t$outprice_ht='';\n\t\t$outprice_ttc='';\n\t\t$outpricebasetype='';\n\t\t$outtva_tx='';\n\t\t$outqty=1;\n\t\t$outdiscount=0;", "\t\t$maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);", "\t\t$label=$objp->label;\n\t\tif (! empty($objp->label_translated)) $label=$objp->label_translated;\n\t\tif (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);", "\t\t$outkey=$objp->rowid;\n\t\t$outref=$objp->ref;\n\t\t$outlabel=$objp->label;\n\t\t$outdesc=$objp->description;\n\t\t$outbarcode=$objp->barcode;", "\t\t$outtype=$objp->fk_product_type;\n\t\t$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';\n\t\t$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';", "\t\t$opt = '<option value=\"'.$objp->rowid.'\"';\n\t\t$opt.= ($objp->rowid == $selected)?' selected':'';\n\t\tif (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)\n\t\t{\n\t\t\t$opt.= ' pbq=\"'.$objp->price_by_qty_rowid.'\" data-pbq=\"'.$objp->price_by_qty_rowid.'\" data-pbqqty=\"'.$objp->price_by_qty_quantity.'\" data-pbqpercent=\"'.$objp->price_by_qty_remise_percent.'\"';\n\t\t}\n\t\tif (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))\n\t\t{\n\t\t\tif ($objp->stock > 0) $opt.= ' class=\"product_line_stock_ok\"';\n\t\t\telse if ($objp->stock <= 0) $opt.= ' class=\"product_line_stock_too_low\"';\n\t\t}\n\t\t$opt.= '>';\n\t\t$opt.= $objp->ref;\n\t\tif ($outbarcode) $opt.=' ('.$outbarcode.')';\n\t\t$opt.=' - '.dol_trunc($label,$maxlengtharticle);", "\t\t$objRef = $objp->ref;\n\t\tif (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);\n\t\t$outval.=$objRef;\n\t\tif ($outbarcode) $outval.=' ('.$outbarcode.')';\n\t\t$outval.=' - '.dol_trunc($label,$maxlengtharticle);", "\t\t$found=0;", "\t\t// Multiprice\n\t\tif (empty($hidepriceinlabel) && $price_level >= 1 && $conf->global->PRODUIT_MULTIPRICES)\t\t// If we need a particular price level (from 1 to 6)\n\t\t{\n\t\t\t$sql = \"SELECT price, price_ttc, price_base_type, tva_tx\";\n\t\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product_price\";\n\t\t\t$sql.= \" WHERE fk_product='\".$objp->rowid.\"'\";\n\t\t\t$sql.= \" AND entity IN (\".getEntity('productprice').\")\";\n\t\t\t$sql.= \" AND price_level=\".$price_level;\n\t\t\t$sql.= \" ORDER BY date_price DESC, rowid DESC\"; // Warning DESC must be both on date_price and rowid.\n\t\t\t$sql.= \" LIMIT 1\";", "\t\t\tdol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);\n\t\t\t$result2 = $this->db->query($sql);\n\t\t\tif ($result2)\n\t\t\t{\n\t\t\t\t$objp2 = $this->db->fetch_object($result2);\n\t\t\t\tif ($objp2)\n\t\t\t\t{\n\t\t\t\t\t$found=1;\n\t\t\t\t\tif ($objp2->price_base_type == 'HT')\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"HT\");\n\t\t\t\t\t\t$outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"HT\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"TTC\");\n\t\t\t\t\t\t$outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"TTC\");\n\t\t\t\t\t}\n\t\t\t\t\t$outprice_ht=price($objp2->price);\n\t\t\t\t\t$outprice_ttc=price($objp2->price_ttc);\n\t\t\t\t\t$outpricebasetype=$objp2->price_base_type;\n\t\t\t\t\t$outtva_tx=$objp2->tva_tx;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdol_print_error($this->db);\n\t\t\t}\n\t\t}", "\t\t// Price by quantity\n\t\tif (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))\n\t\t{\n\t\t\t$found = 1;\n\t\t\t$outqty=$objp->quantity;\n\t\t\t$outdiscount=$objp->remise_percent;\n\t\t\tif ($objp->quantity == 1)\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t$outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t$opt.= $langs->trans(\"Unit\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t$outval.=$langs->transnoentities(\"Unit\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t$opt.= $langs->trans(\"Units\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t$outval.=$langs->transnoentities(\"Units\");\n\t\t\t}", "\t\t\t$outprice_ht=price($objp->unitprice);\n\t\t\t$outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));\n\t\t\t$outpricebasetype=$objp->price_base_type;\n\t\t\t$outtva_tx=$objp->tva_tx;\n\t\t}\n\t\tif (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)\n\t\t{\n\t\t\t$opt.=\" (\".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\".$langs->trans(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t$outval.=\" (\".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency).\"/\".$langs->transnoentities(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t}\n\t\tif (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)\n\t\t{\n\t\t\t$opt.=\" - \".$langs->trans(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t\t$outval.=\" - \".$langs->transnoentities(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t}", "\t\t// Price by customer\n\t\tif (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))\n\t\t{\n\t\t\tif (!empty($objp->idprodcustprice))\n\t\t\t{\n\t\t\t\t$found = 1;", "\t\t\t\tif ($objp->custprice_base_type == 'HT')\n\t\t\t\t{\n\t\t\t\t\t$opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"HT\");\n\t\t\t\t\t$outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"HT\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"TTC\");\n\t\t\t\t\t$outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"TTC\");\n\t\t\t\t}", "\t\t\t\t$outprice_ht=price($objp->custprice);\n\t\t\t\t$outprice_ttc=price($objp->custprice_ttc);\n\t\t\t\t$outpricebasetype=$objp->custprice_base_type;\n\t\t\t\t$outtva_tx=$objp->custtva_tx;\n\t\t\t}\n\t\t}", "\t\t// If level no defined or multiprice not found, we used the default price\n\t\tif (empty($hidepriceinlabel) && ! $found)\n\t\t{\n\t\t\tif ($objp->price_base_type == 'HT')\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"HT\");\n\t\t\t\t$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"HT\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"TTC\");\n\t\t\t\t$outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"TTC\");\n\t\t\t}\n\t\t\t$outprice_ht=price($objp->price);\n\t\t\t$outprice_ttc=price($objp->price_ttc);\n\t\t\t$outpricebasetype=$objp->price_base_type;\n\t\t\t$outtva_tx=$objp->tva_tx;\n\t\t}", "\t\tif (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)\n\t\t{\n\t\t\t$opt.= ' - '.$langs->trans(\"Stock\").':'.$objp->stock;", "\t\t\tif ($objp->stock > 0) {\n\t\t\t\t$outval.= ' - <span class=\"product_line_stock_ok\">'.$langs->transnoentities(\"Stock\").':'.$objp->stock.'</span>';\n\t\t\t}elseif ($objp->stock <= 0) {\n\t\t\t\t$outval.= ' - <span class=\"product_line_stock_too_low\">'.$langs->transnoentities(\"Stock\").':'.$objp->stock.'</span>';\n\t\t\t}\n\t\t}", "\t\tif ($outdurationvalue && $outdurationunit)\n\t\t{\n\t\t\t$da=array(\"h\"=>$langs->trans(\"Hour\"),\"d\"=>$langs->trans(\"Day\"),\"w\"=>$langs->trans(\"Week\"),\"m\"=>$langs->trans(\"Month\"),\"y\"=>$langs->trans(\"Year\"));\n\t\t\tif (isset($da[$outdurationunit]))\n\t\t\t{\n\t\t\t\t$key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');\n\t\t\t\t$opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);\n\t\t\t\t$outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);\n\t\t\t}\n\t\t}", "\t\t$opt.= \"</option>\\n\";\n\t\t$optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);\n\t}", "\t/**\n\t *\tReturn list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)\n\t *\n\t *\t@param\tint\t\t$socid\t\t\tId third party\n\t *\t@param string\t$selected Preselected product\n\t *\t@param string\t$htmlname Name of HTML Select\n\t * @param\tstring\t$filtertype Filter on product type (''=nofilter, 0=product, 1=service)\n\t *\t@param string\t$filtre\t\t\tFor a SQL filter\n\t *\t@param\tarray\t$ajaxoptions\tOptions for ajax_autocompleter\n\t * @param\tint\t\t$hidelabel\t\tHide label (0=no, 1=yes)\n\t * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices\n\t *\t@return\tvoid\n\t */\n\tfunction select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)\n\t{\n\t\tglobal $langs,$conf;\n\t\tglobal $price_level, $status, $finished;", "\t\t$selected_input_value='';\n\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))\n\t\t{\n\t\t\tif ($selected > 0)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\n\t\t\t\t$producttmpselect = new Product($this->db);\n\t\t\t\t$producttmpselect->fetch($selected);\n\t\t\t\t$selected_input_value=$producttmpselect->ref;\n\t\t\t\tunset($producttmpselect);\n\t\t\t}", "\t\t\t// mode=2 means suppliers products\n\t\t\t$urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;\n\t\t\tprint ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);\n\t\t\tprint ($hidelabel?'':$langs->trans(\"RefOrLabel\").' : ').'<input type=\"text\" size=\"20\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$selected_input_value.'\">';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprint $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of suppliers products\n\t *\n\t *\t@param\tint\t\t$socid \t\tId societe fournisseur (0 pour aucun filtre)\n\t *\t@param int\t\t$selected Produit pre-selectionne\n\t *\t@param string\t$htmlname Nom de la zone select\n\t * @param\tstring\t$filtertype Filter on product type (''=nofilter, 0=product, 1=service)\n\t *\t@param string\t$filtre Pour filtre sql\n\t *\t@param string\t$filterkey Filtre des produits\n\t * @param int\t\t$statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)\n\t * @param int\t\t$outputmode 0=HTML select string, 1=Array\n\t * @param int $limit Limit of line number\n\t * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices\n\t * @return array \t\tArray of keys for json\n\t */\n\tfunction select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)\n\t{\n\t\tglobal $langs,$conf,$db;", "\t\t$out='';\n\t\t$outarray=array();", "\t\t$langs->load('stocks');", "\t\t$sql = \"SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,\";\n\t\t$sql.= \" pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,\";\n\t\t$sql.= \" pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,\";\n\t\t$sql.= \" pfp.supplier_reputation\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product as p\";\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_fournisseur_price as pfp ON p.rowid = pfp.fk_product\";\n\t\tif ($socid) $sql.= \" AND pfp.fk_soc = \".$socid;\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"societe as s ON pfp.fk_soc = s.rowid\";\n\t\t$sql.= \" WHERE p.entity IN (\".getEntity('product').\")\";\n\t\t$sql.= \" AND p.tobuy = 1\";\n\t\tif (strval($filtertype) != '') $sql.=\" AND p.fk_product_type=\".$this->db->escape($filtertype);\n\t\tif (! empty($filtre)) $sql.=\" \".$filtre;\n\t\t// Add criteria on ref/label\n\t\tif ($filterkey != '')\n\t\t{\n\t\t\t$sql.=' AND (';\n\t\t\t$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';\t// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on\n\t\t\t// For natural search\n\t\t\t$scrit = explode(' ', $filterkey);\n\t\t\t$i=0;\n\t\t\tif (count($scrit) > 1) $sql.=\"(\";\n\t\t\tforeach ($scrit as $crit)\n\t\t\t{\n\t\t\t\tif ($i > 0) $sql.=\" AND \";\n\t\t\t\t$sql.=\"(pfp.ref_fourn LIKE '\".$this->db->escape($prefix.$crit).\"%' OR p.ref LIKE '\".$this->db->escape($prefix.$crit).\"%' OR p.label LIKE '\".$this->db->escape($prefix.$crit).\"%')\";\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tif (count($scrit) > 1) $sql.=\")\";\n\t\t\tif (! empty($conf->barcode->enabled)) $sql.= \" OR p.barcode LIKE '\".$this->db->escape($prefix.$filterkey).\"%'\";\n\t\t\t$sql.=')';\n\t\t}\n\t\t$sql.= \" ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC\";\n\t\t$sql.= $db->plimit($limit, 0);", "\t\t// Build output string", "\t\tdol_syslog(get_class($this).\"::select_produits_fournisseurs_list\", LOG_DEBUG);\n\t\t$result=$this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';", "\t\t\t$num = $this->db->num_rows($result);", "\t\t\t//$out.='<select class=\"flat\" id=\"select'.$htmlname.'\" name=\"'.$htmlname.'\">';\t// remove select to have id same with combo and ajax\n\t\t\t$out.='<select class=\"flat maxwidthonsmartphone\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\">';\n\t\t\tif (! $selected) $out.='<option value=\"0\" selected>&nbsp;</option>';\n\t\t\telse $out.='<option value=\"0\">&nbsp;</option>';", "\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$objp = $this->db->fetch_object($result);", "\t\t\t\t$outkey=$objp->idprodfournprice; // id in table of price\n\t\t\t\tif (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product", "\t\t\t\t$outref=$objp->ref;\n\t\t\t\t$outval='';\n\t\t\t\t$outqty=1;\n\t\t\t\t$outdiscount=0;\n\t\t\t\t$outtype=$objp->fk_product_type;\n\t\t\t\t$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';\n\t\t\t\t$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';", "\t\t\t\t$opt = '<option value=\"'.$outkey.'\"';\n\t\t\t\tif ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';\n\t\t\t\tif (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';\n\t\t\t\t$opt.= '>';", "\t\t\t\t$objRef = $objp->ref;\n\t\t\t\tif ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);\n\t\t\t\t$objRefFourn = $objp->ref_fourn;\n\t\t\t\tif ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);\n\t\t\t\t$label = $objp->label;\n\t\t\t\tif ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);", "\t\t\t\t$opt.=$objp->ref;\n\t\t\t\tif (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))\n\t\t\t\t\t$opt.=' ('.$objp->ref_fourn.')';\n\t\t\t\t$opt.=' - ';\n\t\t\t\t$outval.=$objRef;\n\t\t\t\tif (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))\n\t\t\t\t\t$outval.=' ('.$objRefFourn.')';\n\t\t\t\t$outval.=' - ';\n\t\t\t\t$opt.=dol_trunc($label, 72).' - ';\n\t\t\t\t$outval.=dol_trunc($label, 72).' - ';", "\t\t\t\tif (! empty($objp->idprodfournprice))\n\t\t\t\t{\n\t\t\t\t\t$outqty=$objp->quantity;\n\t\t\t\t\t$outdiscount=$objp->remise_percent;\n\t\t\t\t\tif (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {\n\t\t\t\t\t\t$prod_supplier = new ProductFournisseur($this->db);\n\t\t\t\t\t\t$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;\n\t\t\t\t\t\t$prod_supplier->id = $objp->fk_product;\n\t\t\t\t\t\t$prod_supplier->fourn_qty = $objp->quantity;\n\t\t\t\t\t\t$prod_supplier->fourn_tva_tx = $objp->tva_tx;\n\t\t\t\t\t\t$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;\n\t\t\t\t\t\t$priceparser = new PriceParser($this->db);\n\t\t\t\t\t\t$price_result = $priceparser->parseProductSupplier($prod_supplier);\n\t\t\t\t\t\tif ($price_result >= 0) {\n\t\t\t\t\t\t\t$objp->fprice = $price_result;\n\t\t\t\t\t\t\tif ($objp->quantity >= 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$objp->unitprice = $objp->fprice / $objp->quantity;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->quantity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t\t\t$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t\t\t$opt.= $langs->trans(\"Unit\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t\t$outval.=$langs->transnoentities(\"Unit\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t\t\t$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t\t\t$opt.= ' '.$langs->trans(\"Units\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t\t$outval.= ' '.$langs->transnoentities(\"Units\");\n\t\t\t\t\t}", "\t\t\t\t\tif ($objp->quantity >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.=\" (\".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\".$langs->trans(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t\t$outval.=\" (\".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency).\"/\".$langs->transnoentities(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->remise_percent >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.=\" - \".$langs->trans(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t\t\t\t\t$outval.=\" - \".$langs->transnoentities(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->duration)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt .= \" - \".$objp->duration;\n\t\t\t\t\t\t$outval.=\" - \".$objp->duration;\n\t\t\t\t\t}\n\t\t\t\t\tif (! $socid)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt .= \" - \".dol_trunc($objp->name,8);\n\t\t\t\t\t\t$outval.=\" - \".dol_trunc($objp->name,8);\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->supplier_reputation)\n\t\t\t\t\t{\n\t\t\t\t\t\t//TODO dictionary\n\t\t\t\t\t\t$reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));", "\t\t\t\t\t\t$opt .= \" - \".$reputations[$objp->supplier_reputation];\n\t\t\t\t\t\t$outval.=\" - \".$reputations[$objp->supplier_reputation];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t\t$outval.=$langs->transnoentities(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t}\n\t\t\t\t\telse // No supplier price defined for product, even on other suppliers\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t\t$outval.=$langs->transnoentities(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$opt .= \"</option>\\n\";", "\n\t\t\t\t// Add new entry\n\t\t\t\t// \"key\" value of json key array is used by jQuery automatically as selected value\n\t\t\t\t// \"label\" value of json key array is used by jQuery automatically as text for combo box\n\t\t\t\t$out.=$opt;\n\t\t\t\tarray_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));\n\t\t\t\t// Exemple of var_dump $outarray\n\t\t\t\t// array(1) {[0]=>array(6) {[key\"]=>string(1) \"2\" [\"value\"]=>string(3) \"ppp\"\n\t\t\t\t// [\"label\"]=>string(76) \"ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)\"\n\t\t\t\t// \t [\"qty\"]=>string(1) \"1\" [\"discount\"]=>string(1) \"0\" [\"disabled\"]=>bool(false)\n\t\t\t\t//}\n\t\t\t\t//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));\n\t\t\t\t//$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');\n\t\t\t\t//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));", "\t\t\t\t$i++;\n\t\t\t}\n\t\t\t$out.='</select>';", "\t\t\t$this->db->free($result);", "\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t$out.=ajax_combobox($htmlname);", "\t\t\tif (empty($outputmode)) return $out;\n\t\t\treturn $outarray;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of suppliers prices for a product\n\t *\n\t * @param\t int\t\t$productid \tId of product\n\t * @param string\t$htmlname \tName of HTML field\n\t * @param int\t\t$selected_supplier Pre-selected supplier if more than 1 result\n\t * @return\t void\n\t */\n\tfunction select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')\n\t{\n\t\tglobal $langs,$conf;", "\t\t$langs->load('stocks');", "\t\t$sql = \"SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,\";\n\t\t$sql.= \" pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,\";\n\t\t$sql.= \" pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product as p\";\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_fournisseur_price as pfp ON p.rowid = pfp.fk_product\";\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"societe as s ON pfp.fk_soc = s.rowid\";\n\t\t$sql.= \" WHERE pfp.entity IN (\".getEntity('productprice').\")\";\n\t\t$sql.= \" AND p.tobuy = 1\";\n\t\t$sql.= \" AND s.fournisseur = 1\";\n\t\t$sql.= \" AND p.rowid = \".$productid;\n\t\t$sql.= \" ORDER BY s.nom, pfp.ref_fourn DESC\";", "\t\tdol_syslog(get_class($this).\"::select_product_fourn_price\", LOG_DEBUG);\n\t\t$result=$this->db->query($sql);", "\t\tif ($result)\n\t\t{\n\t\t\t$num = $this->db->num_rows($result);", "\t\t\t$form = '<select class=\"flat\" name=\"'.$htmlname.'\">';", "\t\t\tif (! $num)\n\t\t\t{\n\t\t\t\t$form.= '<option value=\"0\">-- '.$langs->trans(\"NoSupplierPriceDefinedForThisProduct\").' --</option>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';\n\t\t\t\t$form.= '<option value=\"0\">&nbsp;</option>';", "\t\t\t\t$i = 0;\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$objp = $this->db->fetch_object($result);", "\t\t\t\t\t$opt = '<option value=\"'.$objp->idprodfournprice.'\"';\n\t\t\t\t\t//if there is only one supplier, preselect it\n\t\t\t\t\tif($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {\n\t\t\t\t\t\t$opt .= ' selected';\n\t\t\t\t\t}\n\t\t\t\t\t$opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';", "\t\t\t\t\tif (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {\n\t\t\t\t\t\t$prod_supplier = new ProductFournisseur($this->db);\n\t\t\t\t\t\t$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;\n\t\t\t\t\t\t$prod_supplier->id = $productid;\n\t\t\t\t\t\t$prod_supplier->fourn_qty = $objp->quantity;\n\t\t\t\t\t\t$prod_supplier->fourn_tva_tx = $objp->tva_tx;\n\t\t\t\t\t\t$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;\n\t\t\t\t\t\t$priceparser = new PriceParser($this->db);\n\t\t\t\t\t\t$price_result = $priceparser->parseProductSupplier($prod_supplier);\n\t\t\t\t\t\tif ($price_result >= 0) {\n\t\t\t\t\t\t\t$objp->fprice = $price_result;\n\t\t\t\t\t\t\tif ($objp->quantity >= 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$objp->unitprice = $objp->fprice / $objp->quantity;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->quantity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t\t}", "\t\t\t\t\t$opt.= $objp->quantity.' ';", "\t\t\t\t\tif ($objp->quantity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"Unit\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"Units\");\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->quantity > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.=\" - \";\n\t\t\t\t\t\t$opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\".$langs->trans(\"Unit\");\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->duration) $opt .= \" - \".$objp->duration;\n\t\t\t\t\t$opt .= \"</option>\\n\";", "\t\t\t\t\t$form.= $opt;\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}", "\t\t\t$form.= '</select>';\n\t\t\t$this->db->free($result);\n\t\t\treturn $form;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Return list of delivery address\n\t *\n\t * @param string\t$selected \tId contact pre-selectionn\n\t * @param int\t\t$socid\t\t\t\tId of company\n\t * @param string\t$htmlname \tName of HTML field\n\t * @param int\t\t$showempty \tAdd an empty field\n\t * @return\tinteger|null\n\t */\n\tfunction select_address($selected, $socid, $htmlname='address_id',$showempty=0)\n\t{\n\t\t// On recherche les utilisateurs\n\t\t$sql = \"SELECT a.rowid, a.label\";\n\t\t$sql .= \" FROM \".MAIN_DB_PREFIX .\"societe_address as a\";\n\t\t$sql .= \" WHERE a.fk_soc = \".$socid;\n\t\t$sql .= \" ORDER BY a.label ASC\";", "\t\tdol_syslog(get_class($this).\"::select_address\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\t\tif ($showempty) print '<option value=\"0\">&nbsp;</option>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t\tif ($selected && $selected == $obj->rowid)\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>'.$obj->label.'</option>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">'.$obj->label.'</option>';\n\t\t\t\t\t}\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tprint '</select>';\n\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\n\t/**\n\t * Load into cache list of payment terms\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_conditions_paiements()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_conditions_paiements);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$sql = \"SELECT rowid, code, libelle as label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.'c_payment_term';\n\t\t$sql.= \" WHERE entity = \" . getEntity('c_payment_term');\n\t\t$sql.= \" AND active > 0\";\n\t\t$sql.= \" ORDER BY sortorder\";", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->trans(\"PaymentConditionShort\".$obj->code)!=(\"PaymentConditionShort\".$obj->code)?$langs->trans(\"PaymentConditionShort\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;\n\t\t\t\t$this->cache_conditions_paiements[$obj->rowid]['label']=$label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t//$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);\t\t// We use the field sortorder of table", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t * Charge dans cache la liste des délais de livraison possibles\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_availability()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_availability);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$langs->load('propal');", "\t\t$sql = \"SELECT rowid, code, label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.'c_availability';\n\t\t$sql.= \" WHERE active > 0\";", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->trans(\"AvailabilityType\".$obj->code)!=(\"AvailabilityType\".$obj->code)?$langs->trans(\"AvailabilityType\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$this->cache_availability[$obj->rowid]['code'] =$obj->code;\n\t\t\t\t$this->cache_availability[$obj->rowid]['label']=$label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t * Retourne la liste des types de delais de livraison possibles\n\t *\n\t * @param\tint\t\t$selected Id du type de delais pre-selectionne\n\t * @param string\t$htmlname Nom de la zone select\n\t * @param string\t$filtertype To add a filter\n\t *\t\t@param\tint\t\t$addempty\t\tAdd empty entry\n\t *\t\t@return\tvoid\n\t */\n\tfunction selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)\n\t{\n\t\tglobal $langs,$user;", "\t\t$this->load_cache_availability();", "\t\tdol_syslog(__METHOD__.\" selected=\".$selected.\", htmlname=\".$htmlname, LOG_DEBUG);", "\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\tif ($addempty) print '<option value=\"0\">&nbsp;</option>';\n\t\tforeach($this->cache_availability as $id => $arrayavailability)\n\t\t{\n\t\t\tif ($selected == $id)\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\">';\n\t\t\t}\n\t\t\tprint $arrayavailability['label'];\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\t/**\n\t * Load into cache cache_demand_reason, array of input reasons\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction loadCacheInputReason()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_demand_reason);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\t$sql = \"SELECT rowid, code, label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.'c_input_reason';\n\t\t$sql.= \" WHERE active > 0\";", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\t$tmparray=array();\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->trans(\"DemandReasonType\".$obj->code)!=(\"DemandReasonType\".$obj->code)?$langs->trans(\"DemandReasonType\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$tmparray[$obj->rowid]['id'] =$obj->rowid;\n\t\t\t\t$tmparray[$obj->rowid]['code'] =$obj->code;\n\t\t\t\t$tmparray[$obj->rowid]['label']=$label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);", "\t\t\tunset($tmparray);\n\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)\n\t * List found into table c_input_reason loaded by loadCacheInputReason\n\t *\n\t * @param\tint\t\t$selected Id or code of type origin to select by default\n\t * @param string\t$htmlname Nom de la zone select\n\t * @param string\t$exclude To exclude a code value (Example: SRC_PROP)\n\t *\t@param\tint\t\t$addempty\t\t Add an empty entry\n\t *\t@return\tvoid\n\t */\n\tfunction selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)\n\t{\n\t\tglobal $langs,$user;", "\t\t$this->loadCacheInputReason();", "\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\tif ($addempty) print '<option value=\"0\"'.(empty($selected)?' selected':'').'>&nbsp;</option>';\n\t\tforeach($this->cache_demand_reason as $id => $arraydemandreason)\n\t\t{\n\t\t\tif ($arraydemandreason['code']==$exclude) continue;", "\t\t\tif ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$arraydemandreason['id'].'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$arraydemandreason['id'].'\">';\n\t\t\t}\n\t\t\tprint $arraydemandreason['label'];\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\t/**\n\t * Charge dans cache la liste des types de paiements possibles\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_types_paiements()\n\t{\n\t\tglobal $langs;", "\t\t$num=count($this->cache_types_paiements);\n\t\tif ($num > 0) return $num; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$this->cache_types_paiements = array();", "\t\t$sql = \"SELECT id, code, libelle as label, type, active\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_paiement\";\n\t\t$sql.= \" WHERE entity IN (\".getEntity('c_paiement').\")\";\n\t\t//if ($active >= 0) $sql.= \" AND active = \".$active;", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->transnoentitiesnoconv(\"PaymentTypeShort\".$obj->code)!=(\"PaymentTypeShort\".$obj->code)?$langs->transnoentitiesnoconv(\"PaymentTypeShort\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$this->cache_types_paiements[$obj->id]['id'] =$obj->id;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['code'] =$obj->code;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['label']=$label;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['type'] =$obj->type;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['active'] =$obj->active;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\n\t/**\n\t * Return list of payment modes.\n\t * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.\n\t * See instead to force the default value by the caller.\n\t *\n\t * @param\tint\t\t$selected\t\tId of payment term to preselect by default\n\t * @param\tstring\t$htmlname\t\tNom de la zone select\n\t * @param\tint\t\t$filtertype\t\tNot used\n\t *\t\t@param\tint\t\t$addempty\t\tAdd an empty entry\n\t * \t\t@param\tint\t\t$noinfoadmin\t\t0=Add admin info, 1=Disable admin info\n\t * \t\t@param\tstring\t$morecss\t\t\tAdd more CSS on select tag\n\t *\t\t@return\tvoid\n\t */\n\tfunction select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')\n\t{\n\t\tglobal $langs, $user, $conf;", "\t\tdol_syslog(__METHOD__.\" selected=\".$selected.\", htmlname=\".$htmlname, LOG_DEBUG);", "\t\t$this->load_cache_conditions_paiements();", "\t\t// Set default value if not already set by caller\n\t\tif (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;", "\t\tprint '<select id=\"'.$htmlname.'\" class=\"flat selectpaymentterms'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\">';\n\t\tif ($addempty) print '<option value=\"0\">&nbsp;</option>';\n\t\tforeach($this->cache_conditions_paiements as $id => $arrayconditions)\n\t\t{\n\t\t\tif ($selected == $id)\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\">';\n\t\t\t}\n\t\t\tprint $arrayconditions['label'];\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\n\t/**\n\t * Return list of payment methods\n\t *\n\t * @param\tstring\t$selected Id du mode de paiement pre-selectionne\n\t * @param string\t$htmlname Nom de la zone select\n\t * @param string\t$filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))\n\t * @param int\t\t$format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code\n\t * @param int\t\t$empty\t\t\t1=peut etre vide, 0 sinon\n\t * \t\t@param\tint\t\t$noadmininfo\t0=Add admin info, 1=Disable admin info\n\t * @param int\t\t$maxlength Max length of label\n\t * @param int $active Active or not, -1 = all\n\t * @param string $morecss Add more CSS on select tag\n\t * \t\t@return\tvoid\n\t */\n\tfunction select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')\n\t{\n\t\tglobal $langs,$user;", "\t\tdol_syslog(__METHOD__.\" \".$selected.\", \".$htmlname.\", \".$filtertype.\", \".$format, LOG_DEBUG);", "\t\t$filterarray=array();\n\t\tif ($filtertype == 'CRDT') \t$filterarray=array(0,2,3);\n\t\telseif ($filtertype == 'DBIT') \t$filterarray=array(1,2,3);\n\t\telseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);", "\t\t$this->load_cache_types_paiements();", "\t\tprint '<select id=\"select'.$htmlname.'\" class=\"flat selectpaymenttypes'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\">';\n\t\tif ($empty) print '<option value=\"\">&nbsp;</option>';\n\t\tforeach($this->cache_types_paiements as $id => $arraytypes)\n\t\t{\n\t\t\t// If not good status\n\t\t\tif ($active >= 0 && $arraytypes['active'] != $active) continue;", "\t\t\t// On passe si on a demande de filtrer sur des modes de paiments particuliers\n\t\t\tif (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;", "\t\t\t// We discard empty line if showempty is on because an empty line has already been output.\n\t\t\tif ($empty && empty($arraytypes['code'])) continue;", "\t\t\tif ($format == 0) print '<option value=\"'.$id.'\"';\n\t\t\tif ($format == 1) print '<option value=\"'.$arraytypes['code'].'\"';\n\t\t\tif ($format == 2) print '<option value=\"'.$arraytypes['code'].'\"';\n\t\t\tif ($format == 3) print '<option value=\"'.$id.'\"';\n\t\t\t// Si selected est text, on compare avec code, sinon avec id\n\t\t\tif (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';\n\t\t\telseif ($selected == $id) print ' selected';\n\t\t\tprint '>';\n\t\t\tif ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);\n\t\t\tif ($format == 1) $value=$arraytypes['code'];\n\t\t\tif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);\n\t\t\tif ($format == 3) $value=$arraytypes['code'];\n\t\t\tprint $value?$value:'&nbsp;';\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin && ! $noadmininfo) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\n\t/**\n\t * Selection HT or TTC\n\t *\n\t * @param\tstring\t$selected Id pre-selectionne\n\t * @param string\t$htmlname Nom de la zone select\n\t * \t@return\tstring\t\t\t\t\tCode of HTML select to chose tax or not\n\t */\n\tfunction selectPriceBaseType($selected='',$htmlname='price_base_type')\n\t{\n\t\tglobal $langs;", "\t\t$return='';", "\t\t$return.= '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\t$options = array(\n\t\t\t'HT'=>$langs->trans(\"HT\"),\n\t\t\t'TTC'=>$langs->trans(\"TTC\")\n\t\t);\n\t\tforeach($options as $id => $value)\n\t\t{\n\t\t\tif ($selected == $id)\n\t\t\t{\n\t\t\t\t$return.= '<option value=\"'.$id.'\" selected>'.$value;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$return.= '<option value=\"'.$id.'\">'.$value;\n\t\t\t}\n\t\t\t$return.= '</option>';\n\t\t}\n\t\t$return.= '</select>';", "\t\treturn $return;\n\t}", "\t/**\n\t * Return a HTML select list of shipping mode\n\t *\n\t * @param\tstring\t$selected Id shipping mode pre-selected\n\t * @param string\t$htmlname Name of select zone\n\t * @param string\t$filtre To filter list\n\t * @param int\t\t$useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @param string\t$moreattrib To add more attribute on select\n\t * \t@return\tvoid\n\t */\n\tfunction selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')\n\t{\n\t\tglobal $langs, $conf, $user;", "\t\t$langs->load(\"admin\");\n\t\t$langs->load(\"deliveries\");", "\t\t$sql = \"SELECT rowid, code, libelle as label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_shipment_mode\";\n\t\t$sql.= \" WHERE active > 0\";\n\t\tif ($filtre) $sql.=\" AND \".$filtre;\n\t\t$sql.= \" ORDER BY libelle ASC\";", "\t\tdol_syslog(get_class($this).\"::selectShippingMode\", LOG_DEBUG);\n\t\t$result = $this->db->query($sql);\n\t\tif ($result) {\n\t\t\t$num = $this->db->num_rows($result);\n\t\t\t$i = 0;\n\t\t\tif ($num) {\n\t\t\t\tprint '<select id=\"select'.$htmlname.'\" class=\"flat selectshippingmethod\" name=\"'.$htmlname.'\"'.($moreattrib?' '.$moreattrib:'').'>';\n\t\t\t\tif ($useempty == 1 || ($useempty == 2 && $num > 1)) {\n\t\t\t\t\tprint '<option value=\"-1\">&nbsp;</option>';\n\t\t\t\t}\n\t\t\t\twhile ($i < $num) {\n\t\t\t\t\t$obj = $this->db->fetch_object($result);\n\t\t\t\t\tif ($selected == $obj->rowid) {\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">';\n\t\t\t\t\t}\n\t\t\t\t\tprint ($langs->trans(\"SendingMethod\".strtoupper($obj->code)) != \"SendingMethod\".strtoupper($obj->code)) ? $langs->trans(\"SendingMethod\".strtoupper($obj->code)) : $obj->label;\n\t\t\t\t\tprint '</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t\tprint \"</select>\";\n\t\t\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t\t\t} else {\n\t\t\t\tprint $langs->trans(\"NoShippingMethodDefined\");\n\t\t\t}\n\t\t} else {\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Display form to select shipping mode\n\t *\n\t * @param\tstring\t$page Page\n\t * @param int\t\t$selected Id of shipping mode\n\t * @param string\t$htmlname Name of select html field\n\t * @param int\t\t$addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @return\tvoid\n\t */\n\tfunction formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)\n\t{\n\t\tglobal $langs, $db;", "\t\t$langs->load(\"deliveries\");", "\t\tif ($htmlname != \"none\") {\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setshippingmethod\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->selectShippingMethod($selected, $htmlname, '', $addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t} else {\n\t\t\tif ($selected) {\n\t\t\t\t$code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');\n\t\t\t\tprint $langs->trans(\"SendingMethod\".strtoupper($code));\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Creates HTML last in cycle situation invoices selector\n\t *\n\t * @param string $selected \t\tPreselected ID\n\t * @param int $socid \t\tCompany ID\n\t *\n\t * @return string HTML select\n\t */\n\tfunction selectSituationInvoices($selected = '', $socid = 0)\n\t{\n\t\tglobal $langs;", "\t\t$langs->load('bills');", "\t\t$opt = '<option value =\"\" selected></option>';\n\t\t$sql = 'SELECT rowid, facnumber, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';\n\t\t$sql.= ' ORDER by situation_cycle_ref, situation_counter desc';\n\t\t$resql = $this->db->query($sql);\n\t\tif ($resql && $this->db->num_rows($resql) > 0) {\n\t\t\t// Last seen cycle\n\t\t\t$ref = 0;\n\t\t\twhile ($res = $this->db->fetch_array($resql, MYSQL_NUM)) {\n\t\t\t\t//Same company ?\n\t\t\t\tif ($socid == $res[5]) {\n\t\t\t\t\t//Same cycle ?\n\t\t\t\t\tif ($res[2] != $ref) {\n\t\t\t\t\t\t// Just seen this cycle\n\t\t\t\t\t\t$ref = $res[2];\n\t\t\t\t\t\t//not final ?\n\t\t\t\t\t\tif ($res[4] != 1) {\n\t\t\t\t\t\t\t//Not prov?\n\t\t\t\t\t\t\tif (substr($res[1], 1, 4) != 'PROV') {\n\t\t\t\t\t\t\t\tif ($selected == $res[0]) {\n\t\t\t\t\t\t\t\t\t$opt .= '<option value=\"' . $res[0] . '\" selected>' . $res[1] . '</option>';\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$opt .= '<option value=\"' . $res[0] . '\">' . $res[1] . '</option>';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\tdol_syslog(\"Error sql=\" . $sql . \", error=\" . $this->error, LOG_ERR);\n\t\t}\n\t\tif ($opt == '<option value =\"\" selected></option>')\n\t\t{\n\t\t\t$opt = '<option value =\"0\" selected>' . $langs->trans('NoSituations') . '</option>';\n\t\t}\n\t\treturn $opt;\n\t}", "\t/**\n\t * Creates HTML units selector (code => label)\n\t *\n\t * @param\tstring\t$selected Preselected Unit ID\n\t * @param string\t$htmlname Select name\n\t * @param\tint\t\t$showempty\t\tAdd a nempty line\n\t * \t\t@return\tstring HTML select\n\t */\n\tfunction selectUnits($selected = '', $htmlname = 'units', $showempty=0)\n\t{\n\t\tglobal $langs;", "\t\t$langs->load('products');", "\t\t$return= '<select class=\"flat\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\">';", "\t\t$sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';\n\t\t$sql.= ' WHERE active > 0';", "\t\t$resql = $this->db->query($sql);\n\t\tif($resql && $this->db->num_rows($resql) > 0)\n\t\t{\n\t\t\tif ($showempty) $return .= '<option value=\"none\"></option>';", "\t\t\twhile($res = $this->db->fetch_object($resql))\n\t\t\t{\n\t\t\t\tif ($selected == $res->rowid)\n\t\t\t\t{\n\t\t\t\t\t$return.='<option value=\"'.$res->rowid.'\" selected>'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$return.='<option value=\"'.$res->rowid.'\">'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$return.='</select>';\n\t\t}\n\t\treturn $return;\n\t}", "\t/**\n\t * Return a HTML select list of bank accounts\n\t *\n\t * @param\tstring\t$selected Id account pre-selected\n\t * @param string\t$htmlname Name of select zone\n\t * @param int\t\t$statut Status of searched accounts (0=open, 1=closed, 2=both)\n\t * @param string\t$filtre To filter list\n\t * @param int\t\t$useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @param string\t$moreattrib To add more attribute on select\n\t * @param\tint\t\t$showcurrency\t\tShow currency in label\n\t * \t@return\tvoid\n\t */\n\tfunction select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)\n\t{\n\t\tglobal $langs, $conf;", "\t\t$langs->load(\"admin\");", "\t\t$sql = \"SELECT rowid, label, bank, clos as status, currency_code\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"bank_account\";\n\t\t$sql.= \" WHERE entity IN (\".getEntity('bank_account').\")\";\n\t\tif ($statut != 2) $sql.= \" AND clos = '\".$statut.\"'\";\n\t\tif ($filtre) $sql.=\" AND \".$filtre;\n\t\t$sql.= \" ORDER BY label\";", "\t\tdol_syslog(get_class($this).\"::select_comptes\", LOG_DEBUG);\n\t\t$result = $this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\t$num = $this->db->num_rows($result);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tprint '<select id=\"select'.$htmlname.'\" class=\"flat selectbankaccount\" name=\"'.$htmlname.'\"'.($moreattrib?' '.$moreattrib:'').'>';\n\t\t\t\tif ($useempty == 1 || ($useempty == 2 && $num > 1))\n\t\t\t\t{\n\t\t\t\t\tprint '<option value=\"-1\">&nbsp;</option>';\n\t\t\t\t}", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($result);\n\t\t\t\t\tif ($selected == $obj->rowid)\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">';\n\t\t\t\t\t}\n\t\t\t\t\tprint trim($obj->label);\n\t\t\t\t\tif ($showcurrency) print ' ('.$obj->currency_code.')';\n\t\t\t\t\tif ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans(\"Closed\").')';\n\t\t\t\t\tprint '</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t\tprint \"</select>\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint $langs->trans(\"NoActiveBankAccountDefined\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Display form to select bank account\n\t *\n\t * @param\tstring\t$page Page\n\t * @param int\t\t$selected Id of bank account\n\t * @param string\t$htmlname Name of select html field\n\t * @param int\t\t$addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @return\tvoid\n\t */\n\tfunction formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\") {\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setbankaccount\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->select_comptes($selected, $htmlname, 0, '', $addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t} else {", "\t\t\t$langs->load('banks');", "\t\t\tif ($selected) {\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';\n\t\t\t\t$bankstatic=new Account($this->db);\n\t\t\t\t$bankstatic->fetch($selected);\n\t\t\t\tprint $bankstatic->getNomUrl(1);\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Return list of categories having choosed type\n\t *\n\t * @param\tstring|int\t$type\t\t\t\tType of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.\n\t * @param string\t\t$selected \t\tId of category preselected or 'auto' (autoselect category if there is only one element)\n\t * @param string\t\t$htmlname\t\t\tHTML field name\n\t * @param int\t\t\t$maxlength \tMaximum length for labels\n\t * @param int\t\t\t$excludeafterid \tExclude all categories after this leaf in category tree.\n\t * @param\tint\t\t\t$outputmode\t\t\t0=HTML select string, 1=Array\n\t * @return\tstring\n\t * @see select_categories\n\t */\n\tfunction select_all_categories($type, $selected='', $htmlname=\"parent\", $maxlength=64, $excludeafterid=0, $outputmode=0)\n\t{\n\t\tglobal $conf, $langs;\n\t\t$langs->load(\"categories\");", "\t\tinclude_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';", "\t\t// For backward compatibility\n\t\tif (is_numeric($type))\n\t\t{\n\t\t\tdol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);\n\t\t}", "\t\tif ($type === Categorie::TYPE_BANK_LINE)\n\t\t{\n\t\t\t// TODO Move this into common category feature\n\t\t\t$categids=array();\n\t\t\t$sql = \"SELECT c.label, c.rowid\";\n\t\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"bank_categ as c\";\n\t\t\t$sql.= \" WHERE entity = \".$conf->entity;\n\t\t\t$sql.= \" ORDER BY c.label\";\n\t\t\t$result = $this->db->query($sql);\n\t\t\tif ($result)\n\t\t\t{\n\t\t\t\t$num = $this->db->num_rows($result);\n\t\t\t\t$i = 0;\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$objp = $this->db->fetch_object($result);\n\t\t\t\t\tif ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t\t$this->db->free($result);\n\t\t\t}\n\t\t\telse dol_print_error($this->db);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$cat = new Categorie($this->db);\n\t\t\t$cate_arbo = $cat->get_full_arbo($type, $excludeafterid);\n\t\t}", "\t\t$output = '<select class=\"flat\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';\n\t\t$outarray=array();\n\t\tif (is_array($cate_arbo))\n\t\t{\n\t\t\tif (! count($cate_arbo)) $output.= '<option value=\"-1\" disabled>'.$langs->trans(\"NoCategoriesDefined\").'</option>';\n\t\t\telse\n\t\t\t{\n\t\t\t\t$output.= '<option value=\"-1\">&nbsp;</option>';\n\t\t\t\tforeach($cate_arbo as $key => $value)\n\t\t\t\t{\n\t\t\t\t\tif ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))\n\t\t\t\t\t{\n\t\t\t\t\t\t$add = 'selected ';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$add = '';\n\t\t\t\t\t}\n\t\t\t\t\t$output.= '<option '.$add.'value=\"'.$cate_arbo[$key]['id'].'\">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';", "\t\t\t\t\t$outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$output.= '</select>';\n\t\t$output.= \"\\n\";", "\t\tif ($outputmode) return $outarray;\n\t\treturn $output;\n\t}", "\t/**\n\t * Show a confirmation HTML form or AJAX popup\n\t *\n\t * @param\tstring\t\t$page \t \tUrl of page to call if confirmation is OK\n\t * @param\tstring\t\t$title \t \tTitle\n\t * @param\tstring\t\t$question \t \tQuestion\n\t * @param \tstring\t\t$action \t \tAction\n\t *\t @param\tarray\t\t$formquestion\t \tAn array with forms complementary inputs\n\t * \t @param\tstring\t\t$selectedchoice\t\t\"\" or \"no\" or \"yes\"\n\t * \t @param\tint\t\t\t$useajax\t\t \t0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx\n\t * @param\tint\t\t\t$height \tForce height of box\n\t * @param\tint\t\t\t$width\t\t\t\tForce width of box\n\t * @return \tvoid\n\t * @deprecated\n\t * @see formconfirm()\n\t */\n\tfunction form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice=\"\", $useajax=0, $height=170, $width=500)\n\t{\n\t\tprint $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);\n\t}", "\t/**\n\t * Show a confirmation HTML form or AJAX popup.\n\t * Easiest way to use this is with useajax=1.\n\t * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)\n\t * just after calling this method. For example:\n\t * print '<script type=\"text/javascript\">'.\"\\n\";\n\t * print 'jQuery(document).ready(function() {'.\"\\n\";\n\t * print 'jQuery(\".xxxlink\").click(function(e) { jQuery(\"#aparamid\").val(jQuery(this).attr(\"rel\")); jQuery(\"#dialog-confirm-xxx\").dialog(\"open\"); return false; });'.\"\\n\";\n\t * print '});'.\"\\n\";\n\t * print '</script>'.\"\\n\";\n\t *\n\t * @param \tstring\t\t$page \t \tUrl of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)\n\t * @param\tstring\t\t$title \t \tTitle\n\t * @param\tstring\t\t$question \t \tQuestion\n\t * @param \tstring\t\t$action \t \tAction\n\t *\t @param \tarray\t\t$formquestion\t \tAn array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))\n\t *\t\t\t\t\t\t\t\t\t\t\t\ttype can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', ...\n\t * \t @param \tstring\t\t$selectedchoice \t\"\" or \"no\" or \"yes\"\n\t * \t @param \tint\t\t\t$useajax\t\t \t0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx\n\t * @param \tint\t\t\t$height \tForce height of box\n\t * @param\tint\t\t\t$width\t\t\t\tForce width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.\n\t * @param\tint\t\t\t$disableformtag\t\t1=Disable form tag. Can be used if we are already inside a <form> section.\n\t * @return \tstring \t \t\t\tHTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form\n\t */\n\tfunction formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=200, $width=500, $disableformtag=0)\n\t{\n\t\tglobal $langs,$conf;\n\t\tglobal $useglobalvars;", "\t\t$more='';\n\t\t$formconfirm='';\n\t\t$inputok=array();\n\t\t$inputko=array();", "\t\t// Clean parameters\n\t\t$newselectedchoice=empty($selectedchoice)?\"no\":$selectedchoice;\n\t\tif ($conf->browser->layout == 'phone') $width='95%';", "\t\tif (is_array($formquestion) && ! empty($formquestion))\n\t\t{\n\t\t\t// First add hidden fields and value\n\t\t\tforeach ($formquestion as $key => $input)\n\t\t\t{\n\t\t\t\tif (is_array($input) && ! empty($input))\n\t\t\t\t{\n\t\t\t\t\tif ($input['type'] == 'hidden')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<input type=\"hidden\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\" value=\"'.dol_escape_htmltag($input['value']).'\">'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\t// Now add questions\n\t\t\t$more.='<table class=\"paddingtopbottomonly\" width=\"100%\">'.\"\\n\";\n\t\t\t$more.='<tr><td colspan=\"3\">'.(! empty($formquestion['text'])?$formquestion['text']:'').'</td></tr>'.\"\\n\";\n\t\t\tforeach ($formquestion as $key => $input)\n\t\t\t{\n\t\t\t\tif (is_array($input) && ! empty($input))\n\t\t\t\t{\n\t\t\t\t\t$size=(! empty($input['size'])?' size=\"'.$input['size'].'\"':'');\n\t\t\t\t\t$moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');\n\t\t\t\t\t$morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');", "\t\t\t\t\tif ($input['type'] == 'text')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>'.$input['label'].'</td><td colspan=\"2\" align=\"left\"><input type=\"text\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\"'.$size.' value=\"'.$input['value'].'\"'.$moreattr.' /></td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'password')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>'.$input['label'].'</td><td colspan=\"2\" align=\"left\"><input type=\"password\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\"'.$size.' value=\"'.$input['value'].'\"'.$moreattr.' /></td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'select')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>';\n\t\t\t\t\t\tif (! empty($input['label'])) $more.=$input['label'].'</td><td valign=\"top\" colspan=\"2\" align=\"left\">';\n\t\t\t\t\t\t$more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'checkbox')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr>';\n\t\t\t\t\t\t$more.='<td>'.$input['label'].' </td><td align=\"left\">';\n\t\t\t\t\t\t$more.='<input type=\"checkbox\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\"'.$moreattr;\n\t\t\t\t\t\tif (! is_bool($input['value']) && $input['value'] != 'false') $more.=' checked';\n\t\t\t\t\t\tif (is_bool($input['value']) && $input['value']) $more.=' checked';\n\t\t\t\t\t\tif (isset($input['disabled'])) $more.=' disabled';\n\t\t\t\t\t\t$more.=' /></td>';\n\t\t\t\t\t\t$more.='<td align=\"left\">&nbsp;</td>';\n\t\t\t\t\t\t$more.='</tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'radio')\n\t\t\t\t\t{\n\t\t\t\t\t\t$i=0;\n\t\t\t\t\t\tforeach($input['values'] as $selkey => $selval)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$more.='<tr>';\n\t\t\t\t\t\t\tif ($i==0) $more.='<td class=\"tdtop\">'.$input['label'].'</td>';\n\t\t\t\t\t\t\telse $more.='<td>&nbsp;</td>';\n\t\t\t\t\t\t\t$more.='<td width=\"20\"><input type=\"radio\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\" value=\"'.$selkey.'\"'.$moreattr;\n\t\t\t\t\t\t\tif ($input['disabled']) $more.=' disabled';\n\t\t\t\t\t\t\t$more.=' /></td>';\n\t\t\t\t\t\t\t$more.='<td align=\"left\">';\n\t\t\t\t\t\t\t$more.=$selval;\n\t\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t\t\t$i++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'date')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>'.$input['label'].'</td>';\n\t\t\t\t\t\t$more.='<td colspan=\"2\" align=\"left\">';\n\t\t\t\t\t\t$more.=$this->select_date($input['value'],$input['name'],0,0,0,'',1,0,1);\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'day');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'month');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'year');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'hour');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'min');\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'other')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>';\n\t\t\t\t\t\tif (! empty($input['label'])) $more.=$input['label'].'</td><td colspan=\"2\" align=\"left\">';\n\t\t\t\t\t\t$more.=$input['value'];\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t}", "\t\t\t\t\telse if ($input['type'] == 'onecolumn')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td colspan=\"3\" align=\"left\">';\n\t\t\t\t\t\t$more.=$input['value'];\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$more.='</table>'.\"\\n\";\n\t\t}", "\t\t// JQUI method dialog is broken with jmobile, we use standard HTML.\n\t\t// Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx\n\t\t// See page product/card.php for example\n\t\tif (! empty($conf->dol_use_jmobile)) $useajax=0;\n\t\tif (empty($conf->use_javascript_ajax)) $useajax=0;", "\t\tif ($useajax)\n\t\t{\n\t\t\t$autoOpen=true;\n\t\t\t$dialogconfirm='dialog-confirm';\n\t\t\t$button='';\n\t\t\tif (! is_numeric($useajax))\n\t\t\t{\n\t\t\t\t$button=$useajax;\n\t\t\t\t$useajax=1;\n\t\t\t\t$autoOpen=false;\n\t\t\t\t$dialogconfirm.='-'.$button;\n\t\t\t}\n\t\t\t$pageyes=$page.(preg_match('/\\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';\n\t\t\t$pageno=($useajax == 2 ? $page.(preg_match('/\\?/',$page)?'&':'?').'confirm=no':'');\n\t\t\t// Add input fields into list of fields to read during submit (inputok and inputko)\n\t\t\tif (is_array($formquestion))\n\t\t\t{\n\t\t\t\tforeach ($formquestion as $key => $input)\n\t\t\t\t{\n\t\t\t\t\t//print \"xx \".$key.\" rr \".is_array($input).\"<br>\\n\";\n\t\t\t\t\tif (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);\n\t\t\t\t\tif (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Show JQuery confirm box. Note that global var $useglobalvars is used inside this template\n\t\t\t$formconfirm.= '<div id=\"'.$dialogconfirm.'\" title=\"'.dol_escape_htmltag($title).'\" style=\"display: none;\">';\n\t\t\tif (! empty($more)) {\n\t\t\t\t$formconfirm.= '<div class=\"confirmquestions\">'.$more.'</div>';\n\t\t\t}\n\t\t\t$formconfirm.= ($question ? '<div class=\"confirmmessage\">'.img_help('','').' '.$question . '</div>': '');\n\t\t\t$formconfirm.= '</div>'.\"\\n\";", "\t\t\t$formconfirm.= \"\\n<!-- begin ajax form_confirm page=\".$page.\" -->\\n\";\n\t\t\t$formconfirm.= '<script type=\"text/javascript\">'.\"\\n\";\n\t\t\t$formconfirm.= 'jQuery(document).ready(function() {\n $(function() {\n \t$( \"#'.$dialogconfirm.'\" ).dialog(\n \t{\n autoOpen: '.($autoOpen ? \"true\" : \"false\").',';\n\t\t\t\t\tif ($newselectedchoice == 'no')\n\t\t\t\t\t{\n\t\t\t\t\t\t$formconfirm.='\n\t\t\t\t\t\topen: function() {\n \t\t\t\t$(this).parent().find(\"button.ui-button:eq(2)\").focus();\n\t\t\t\t\t\t},';\n\t\t\t\t\t}\n\t\t\t\t\t$formconfirm.='\n resizable: false,\n height: \"'.$height.'\",\n width: \"'.$width.'\",\n modal: true,\n closeOnEscape: false,\n buttons: {\n \"'.dol_escape_js($langs->transnoentities(\"Yes\")).'\": function() {\n \tvar options=\"\";\n \tvar inputok = '.json_encode($inputok).';\n \tvar pageyes = \"'.dol_escape_js(! empty($pageyes)?$pageyes:'').'\";\n \tif (inputok.length>0) {\n \t\t$.each(inputok, function(i, inputname) {\n \t\t\tvar more = \"\";\n \t\t\tif ($(\"#\" + inputname).attr(\"type\") == \"checkbox\") { more = \":checked\"; }\n \t\t if ($(\"#\" + inputname).attr(\"type\") == \"radio\") { more = \":checked\"; }\n \t\t\tvar inputvalue = $(\"#\" + inputname + more).val();\n \t\t\tif (typeof inputvalue == \"undefined\") { inputvalue=\"\"; }\n \t\t\toptions += \"&\" + inputname + \"=\" + inputvalue;\n \t\t});\n \t}\n \tvar urljump = pageyes + (pageyes.indexOf(\"?\") < 0 ? \"?\" : \"\") + options;\n \t//alert(urljump);\n \t\t\t\tif (pageyes.length > 0) { location.href = urljump; }\n $(this).dialog(\"close\");\n },\n \"'.dol_escape_js($langs->transnoentities(\"No\")).'\": function() {\n \tvar options = \"\";\n \tvar inputko = '.json_encode($inputko).';\n \tvar pageno=\"'.dol_escape_js(! empty($pageno)?$pageno:'').'\";\n \tif (inputko.length>0) {\n \t\t$.each(inputko, function(i, inputname) {\n \t\t\tvar more = \"\";\n \t\t\tif ($(\"#\" + inputname).attr(\"type\") == \"checkbox\") { more = \":checked\"; }\n \t\t\tvar inputvalue = $(\"#\" + inputname + more).val();\n \t\t\tif (typeof inputvalue == \"undefined\") { inputvalue=\"\"; }\n \t\t\toptions += \"&\" + inputname + \"=\" + inputvalue;\n \t\t});\n \t}\n \tvar urljump=pageno + (pageno.indexOf(\"?\") < 0 ? \"?\" : \"\") + options;\n \t//alert(urljump);\n \t\t\t\tif (pageno.length > 0) { location.href = urljump; }\n $(this).dialog(\"close\");\n }\n }\n }\n );", " \tvar button = \"'.$button.'\";\n \tif (button.length > 0) {\n \t$( \"#\" + button ).click(function() {\n \t\t$(\"#'.$dialogconfirm.'\").dialog(\"open\");\n \t\t\t});\n }\n });\n });\n </script>';\n\t\t\t$formconfirm.= \"<!-- end ajax form_confirm -->\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$formconfirm.= \"\\n<!-- begin form_confirm page=\".$page.\" -->\\n\";", "\t\t\tif (empty($disableformtag)) $formconfirm.= '<form method=\"POST\" action=\"'.$page.'\" class=\"notoptoleftroright\">'.\"\\n\";", "\t\t\t$formconfirm.= '<input type=\"hidden\" name=\"action\" value=\"'.$action.'\">'.\"\\n\";\n\t\t\tif (empty($disableformtag)) $formconfirm.= '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">'.\"\\n\";", "\t\t\t$formconfirm.= '<table width=\"100%\" class=\"valid\">'.\"\\n\";", "\t\t\t// Line title\n\t\t\t$formconfirm.= '<tr class=\"validtitre\"><td class=\"validtitre\" colspan=\"3\">'.img_picto('','recent').' '.$title.'</td></tr>'.\"\\n\";", "\t\t\t// Line form fields\n\t\t\tif ($more)\n\t\t\t{\n\t\t\t\t$formconfirm.='<tr class=\"valid\"><td class=\"valid\" colspan=\"3\">'.\"\\n\";\n\t\t\t\t$formconfirm.=$more;\n\t\t\t\t$formconfirm.='</td></tr>'.\"\\n\";\n\t\t\t}", "\t\t\t// Line with question\n\t\t\t$formconfirm.= '<tr class=\"valid\">';\n\t\t\t$formconfirm.= '<td class=\"valid\">'.$question.'</td>';\n\t\t\t$formconfirm.= '<td class=\"valid\">';\n\t\t\t$formconfirm.= $this->selectyesno(\"confirm\",$newselectedchoice);\n\t\t\t$formconfirm.= '</td>';\n\t\t\t$formconfirm.= '<td class=\"valid\" align=\"center\"><input class=\"button valignmiddle\" type=\"submit\" value=\"'.$langs->trans(\"Validate\").'\"></td>';\n\t\t\t$formconfirm.= '</tr>'.\"\\n\";", "\t\t\t$formconfirm.= '</table>'.\"\\n\";", "\t\t\tif (empty($disableformtag)) $formconfirm.= \"</form>\\n\";\n\t\t\t$formconfirm.= '<br>';", "\t\t\t$formconfirm.= \"<!-- end form_confirm -->\\n\";\n\t\t}", "\t\treturn $formconfirm;\n\t}", "\n\t/**\n\t * Show a form to select a project\n\t *\n\t * @param\tint\t\t$page \t\tPage\n\t * @param\tint\t\t$socid \t\tId third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)\n\t * @param int\t\t$selected \t\tId pre-selected project\n\t * @param string\t$htmlname \t\tName of select field\n\t * @param\tint\t\t$discard_closed\t\tDiscard closed projects (0=Keep,1=hide completely except $selected,2=Disable)\n\t * @param\tint\t\t$maxlength\t\t\tMax length\n\t * @param\tint\t\t$forcefocus\t\t\tForce focus on field (works with javascript only)\n\t * @param int $nooutput No print is done. String is returned.\n\t * @return\tstring Return html content\n\t */\n\tfunction form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)\n\t{\n\t\tglobal $langs;", "\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';\n\t\trequire_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';", "\t\t$out='';", "\t\t$formproject=new FormProjets($this->db);", "\t\t$langs->load(\"project\");\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\t$out.=\"\\n\";\n\t\t\t$out.='<form method=\"post\" action=\"'.$page.'\">';\n\t\t\t$out.='<input type=\"hidden\" name=\"action\" value=\"classin\">';\n\t\t\t$out.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);\n\t\t\t$out.='<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\t$out.='</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$projet = new Project($this->db);\n\t\t\t\t$projet->fetch($selected);\n\t\t\t\t//print '<a href=\"'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'\">'.$projet->title.'</a>';\n\t\t\t\t$out.=$projet->getNomUrl(0,'',1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.=\"&nbsp;\";\n\t\t\t}\n\t\t}", "\t\tif (empty($nooutput))\n\t\t{\n\t\t\tprint $out;\n\t\t\treturn '';\n\t\t}\n\t\treturn $out;\n\t}", "\t/**\n\t *\tShow a form to select payment conditions\n\t *\n\t * @param\tint\t\t$page \tPage\n\t * @param string\t$selected \tId condition pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t *\t@param\tint\t\t$addempty\t\tAdd empty entry\n\t * @return\tvoid\n\t */\n\tfunction form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setconditions\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->select_conditions_paiements($selected,$htmlname,-1,$addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->load_cache_conditions_paiements();\n\t\t\t\tprint $this->cache_conditions_paiements[$selected]['label'];\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Show a form to select a delivery delay\n\t *\n\t * @param int\t\t$page \tPage\n\t * @param string\t$selected \tId condition pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t *\t@param\tint\t\t$addempty\t\tAjoute entree vide\n\t * @return\tvoid\n\t */\n\tfunction form_availability($page, $selected='', $htmlname='availability', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setavailability\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->load_cache_availability();\n\t\t\t\tprint $this->cache_availability[$selected]['label'];\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t *\tOutput HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)\n\t * List found into table c_input_reason loaded by loadCacheInputReason\n\t *\n\t * @param string\t$page \tPage\n\t * @param string\t$selected \tId condition pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t *\t@param\tint\t\t$addempty\t\tAdd empty entry\n\t * @return\tvoid\n\t */\n\tfunction formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setdemandreason\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->selectInputReason($selected,$htmlname,-1,$addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->loadCacheInputReason();\n\t\t\t\tforeach ($this->cache_demand_reason as $key => $val)\n\t\t\t\t{\n\t\t\t\t\tif ($val['id'] == $selected)\n\t\t\t\t\t{\n\t\t\t\t\t\tprint $val['label'];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Show a form + html select a date\n\t *\n\t * @param\tstring\t\t$page \tPage\n\t * @param\tstring\t\t$selected \tDate preselected\n\t * @param string\t\t$htmlname \tHtml name of date input fields or 'none'\n\t * @param int\t\t\t$displayhour \tDisplay hour selector\n\t * @param int\t\t\t$displaymin\t\tDisplay minutes selector\n\t * @param\tint\t\t\t$nooutput\t\t1=No print output, return string\n\t * @return\tstring\n\t * @see\t\tselect_date\n\t */\n\tfunction form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)\n\t{\n\t\tglobal $langs;", "\t\t$ret='';", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\t$ret.='<form method=\"post\" action=\"'.$page.'\" name=\"form'.$htmlname.'\">';\n\t\t\t$ret.='<input type=\"hidden\" name=\"action\" value=\"set'.$htmlname.'\">';\n\t\t\t$ret.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$ret.='<table class=\"nobordernopadding\" cellpadding=\"0\" cellspacing=\"0\">';\n\t\t\t$ret.='<tr><td>';\n\t\t\t$ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1);\n\t\t\t$ret.='</td>';\n\t\t\t$ret.='<td align=\"left\"><input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\"></td>';\n\t\t\t$ret.='</tr></table></form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($displayhour) $ret.=dol_print_date($selected,'dayhour');\n\t\t\telse $ret.=dol_print_date($selected,'day');\n\t\t}", "\t\tif (empty($nooutput)) print $ret;\n\t\treturn $ret;\n\t}", "\n\t/**\n\t * Show a select form to choose a user\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param string\t$selected \tId of user preselected\n\t * @param string\t$htmlname \tName of input html field. If 'none', we just output the user link.\n\t * @param array\t$exclude\t\tList of users id to exclude\n\t * @param array\t$include List of users id to include\n\t * @return\tvoid\n\t */\n\tfunction form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')\n\t{\n\t\tglobal $langs;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\" name=\"form'.$htmlname.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"set'.$htmlname.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';\n\t\t\t\t$theuser=new User($this->db);\n\t\t\t\t$theuser->fetch($selected);\n\t\t\t\tprint $theuser->getNomUrl(1);\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\n\t/**\n\t * Show form with payment mode\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param int\t\t$selected \tId mode pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t * @param \tstring\t$filtertype\t\tTo filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))\n\t * @param int $active Active or not, -1 = all\n\t * @return\tvoid\n\t */\n\tfunction form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setmode\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->load_cache_types_paiements();\n\t\t\t\tprint $this->cache_types_paiements[$selected]['label'];\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Show form with multicurrency code\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param string\t$selected \tcode pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t * @return\tvoid\n\t */\n\tfunction form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setmulticurrencycode\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint $this->selectMultiCurrency($selected, $htmlname, 0);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_include_once('/core/lib/company.lib.php');\n\t\t\tprint !empty($selected) ? currency_name($selected,1) : '&nbsp;';\n\t\t}\n\t}", "\t/**\n\t * Show form with multicurrency rate\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param double\t$rate\t \tCurrent rate\n\t * @param string\t$htmlname \tName of select html field\n\t * @param string $currency Currency code to explain the rate\n\t * @return\tvoid\n\t */\n\tfunction form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')\n\t{\n\t\tglobal $langs, $mysoc, $conf;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setmulticurrencyrate\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint '<input type=\"text\" name=\"'.$htmlname.'\" value=\"'.(!empty($rate) ? price($rate) : 1).'\" size=\"10\" /> ';\n\t\t\tprint '<select name=\"calculation_mode\">';\n\t\t\tprint '<option value=\"1\">'.$currency.' > '.$conf->currency.'</option>';\n\t\t\tprint '<option value=\"2\">'.$conf->currency.' > '.$currency.'</option>';\n\t\t\tprint '</select> ';\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (! empty($rate))\n\t\t\t{\n\t\t\t\tprint price($rate, 1, $langs, 1, 0);\n\t\t\t\tif ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint 1;\n\t\t\t}\n\t\t}\n\t}", "\n\t/**\n\t *\tShow a select box with available absolute discounts\n\t *\n\t * @param string\t$page \tPage URL where form is shown\n\t * @param int\t\t$selected \tValue pre-selected\n\t *\t@param string\t$htmlname \tName of SELECT component. If 'none', not changeable. Example 'remise_id'.\n\t *\t@param\tint\t\t$socid\t\t\tThird party id\n\t * \t@param\tfloat\t$amount\t\t\tTotal amount available\n\t * \t@param\tstring\t$filter\t\t\tSQL filter on discounts\n\t * \t@param\tint\t\t$maxvalue\t\tMax value for lines that can be selected\n\t * @param string\t$more More string to add\n\t * @param int $hidelist 1=Hide list\n\t * @return\tvoid\n\t */\n\tfunction form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0)\n\t{\n\t\tglobal $conf,$langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setabsolutediscount\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint '<div class=\"inline-block\">';\n\t\t\tif (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))\n\t\t\t{\n\t\t\t\tif (! $filter || $filter==\"fk_facture_source IS NULL\") print $langs->trans(\"CompanyHasAbsoluteDiscount\",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice\n\t\t\t\telse print $langs->trans(\"CompanyHasCreditNote\",price($amount,0,$langs,0,0,-1,$conf->currency));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (! $filter || $filter==\"fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))\") print $langs->trans(\"CompanyHasAbsoluteDiscount\",price($amount,0,$langs,0,0,-1,$conf->currency));\n\t\t\t\telse print $langs->trans(\"CompanyHasCreditNote\",price($amount,0,$langs,0,0,-1,$conf->currency));\n\t\t\t}\n\t\t\tif (empty($hidelist)) print ': ';\n\t\t\tprint '</div>';\n\t\t\tif (empty($hidelist))\n\t\t\t{\n\t\t\t\tprint '<div class=\"inline-block\" style=\"padding-right: 10px\">';\n\t\t\t\t$newfilter='fk_facture IS NULL AND fk_facture_line IS NULL';\t// Remises disponibles\n\t\t\t\tif ($filter) $newfilter.=' AND ('.$filter.')';\n\t\t\t\t$nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);\n\t\t\t\tif ($nbqualifiedlines > 0)\n\t\t\t\t{\n\t\t\t\t\tprint ' &nbsp; <input type=\"submit\" class=\"button\" value=\"'.dol_escape_htmltag($langs->trans(\"UseLine\")).'\"';\n\t\t\t\t\tif ($filter && $filter != \"fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')\") print ' title=\"'.$langs->trans(\"UseCreditNoteInInvoicePayment\").'\"';\n\t\t\t\t\tprint '>';\n\t\t\t\t}\n\t\t\t\tprint '</div>';\n\t\t\t}\n\t\t\tif ($more)\n\t\t\t{\n\t\t\t\tprint '<div class=\"inline-block\">';\n\t\t\t\tprint $more;\n\t\t\t\tprint '</div>';\n\t\t\t}\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\tprint $selected;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint \"0\";\n\t\t\t}\n\t\t}\n\t}", "\n\t/**\n\t * Show forms to select a contact\n\t *\n\t * @param\tstring\t\t$page \tPage\n\t * @param\tSociete\t\t$societe\t\tFilter on third party\n\t * @param int\t\t\t$selected \tId contact pre-selectionne\n\t * @param string\t\t$htmlname \tName of HTML select. If 'none', we just show contact link.\n\t * @return\tvoid\n\t */\n\tfunction form_contacts($page, $societe, $selected='', $htmlname='contactid')\n\t{\n\t\tglobal $langs, $conf;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"set_contact\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint '<table class=\"nobordernopadding\" cellpadding=\"0\" cellspacing=\"0\">';\n\t\t\tprint '<tr><td>';\n\t\t\t$num=$this->select_contacts($societe->id, $selected, $htmlname);\n\t\t\tif ($num==0)\n\t\t\t{\n\t\t\t\t$addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans(\"AddContact\") : $langs->trans(\"AddContactAddress\"));\n\t\t\t\tprint '<a href=\"'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1\">'.$addcontact.'</a>';\n\t\t\t}\n\t\t\tprint '</td>';\n\t\t\tprint '<td align=\"left\"><input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\"></td>';\n\t\t\tprint '</tr></table></form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';\n\t\t\t\t$contact=new Contact($this->db);\n\t\t\t\t$contact->fetch($selected);\n\t\t\t\tprint $contact->getFullName($langs);\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Output html select to select thirdparty\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param string\t$selected \tId preselected\n\t * @param string\t$htmlname\t\tName of HTML select\n\t * @param string\t$filter optional filters criteras\n\t *\t@param\tint\t\t$showempty\t\tAdd an empty field\n\t * \t@param\tint\t\t$showtype\t\tShow third party type in combolist (customer, prospect or supplier)\n\t * \t@param\tint\t\t$forcecombo\t\tForce to use combo box\n\t * @param\tarray\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @return\tvoid\n\t */\n\tfunction form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array())\n\t{\n\t\tglobal $langs;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"set_thirdparty\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';\n\t\t\t\t$soc = new Societe($this->db);\n\t\t\t\t$soc->fetch($selected);\n\t\t\t\tprint $soc->getNomUrl($langs);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Retourne la liste des devises, dans la langue de l'utilisateur\n\t *\n\t * @param\tstring\t$selected preselected currency code\n\t * @param string\t$htmlname name of HTML select list\n\t * @return\tvoid\n\t */\n\tfunction select_currency($selected='',$htmlname='currency_id')\n\t{\n\t\tprint $this->selectCurrency($selected,$htmlname);\n\t}", "\t/**\n\t * Retourne la liste des devises, dans la langue de l'utilisateur\n\t *\n\t * @param\tstring\t$selected preselected currency code\n\t * @param string\t$htmlname name of HTML select list\n\t * \t@return\tstring\n\t */\n\tfunction selectCurrency($selected='',$htmlname='currency_id')\n\t{\n\t\tglobal $conf,$langs,$user;", "\t\t$langs->loadCacheCurrencies('');", "\t\t$out='';", "\t\tif ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite", "\t\t$out.= '<select class=\"flat maxwidth200onsmartphone minwidth300\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';\n\t\tforeach ($langs->cache_currencies as $code_iso => $currency)\n\t\t{\n\t\t\tif ($selected && $selected == $code_iso)\n\t\t\t{\n\t\t\t\t$out.= '<option value=\"'.$code_iso.'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.= '<option value=\"'.$code_iso.'\">';\n\t\t\t}\n\t\t\t$out.= $currency['label'];\n\t\t\t$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';\n\t\t\t$out.= '</option>';\n\t\t}\n\t\t$out.= '</select>';\n\t\tif ($user->admin) $out.= info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);", "\t\t// Make select dynamic\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t$out .= ajax_combobox($htmlname);", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn array of currencies in user language\n\t *\n\t * @param\tstring\t$selected preselected currency code\n\t * @param string\t$htmlname name of HTML select list\n\t * @param integer\t$useempty 1=Add empty line\n\t * \t@return\tstring\n\t */\n\tfunction selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)\n\t{\n\t\tglobal $db,$conf,$langs,$user;", "\t\t$langs->loadCacheCurrencies(''); // Load ->cache_currencies", "\t\t$TCurrency = array();", "\t\t$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';\n\t\t$sql.= \" WHERE entity IN ('\".getEntity('mutlicurrency').\"')\";\n\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\twhile ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;\n\t\t}", "\t\t$out='';\n\t\t$out.= '<select class=\"flat\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';\n\t\tif ($useempty) $out .= '<option value=\"\"></option>';\n\t\t// If company current currency not in table, we add it into list. Should always be available.\n\t\tif (! in_array($conf->currency, $TCurrency))\n\t\t{\n\t\t\t$TCurrency[$conf->currency] = $conf->currency;\n\t\t}\n\t\tif (count($TCurrency) > 0)\n\t\t{\n\t\t\tforeach ($langs->cache_currencies as $code_iso => $currency)\n\t\t\t{\n\t\t\t\tif (isset($TCurrency[$code_iso]))\n\t\t\t\t{\n\t\t\t\t\tif (!empty($selected) && $selected == $code_iso) $out.= '<option value=\"'.$code_iso.'\" selected=\"selected\">';\n\t\t\t\t\telse $out.= '<option value=\"'.$code_iso.'\">';", "\t\t\t\t\t$out.= $currency['label'];\n\t\t\t\t\t$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';\n\t\t\t\t\t$out.= '</option>';\n\t\t\t\t}\n\t\t\t}", "\t\t}", "\t\t$out.= '</select>';\n\t\t// Make select dynamic\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t$out.= ajax_combobox($htmlname);", "\t\treturn $out;\n\t}", "\t/**\n\t *\tLoad into the cache vat rates of a country\n\t *\n\t *\t@param\tstring\t$country_code\t\tCountry code with quotes (\"'CA'\", or \"'CA,IN,...'\")\n\t *\t@return\tint\t\t\t\t\t\t\tNb of loaded lines, 0 if already loaded, <0 if KO\n\t */\n\tfunction load_cache_vatrates($country_code)\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_vatrates);\n\t\tif ($num > 0) return $num; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$sql = \"SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_tva as t, \".MAIN_DB_PREFIX.\"c_country as c\";\n\t\t$sql.= \" WHERE t.fk_pays = c.rowid\";\n\t\t$sql.= \" AND t.active > 0\";\n\t\t$sql.= \" AND c.code IN (\".$country_code.\")\";\n\t\t$sql.= \" ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC\";", "\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tfor ($i = 0; $i < $num; $i++)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$this->cache_vatrates[$i]['rowid']\t= $obj->rowid;\n\t\t\t\t\t$this->cache_vatrates[$i]['code']\t= $obj->code;\n\t\t\t\t\t$this->cache_vatrates[$i]['txtva']\t= $obj->taux;\n\t\t\t\t\t$this->cache_vatrates[$i]['nprtva']\t= $obj->recuperableonly;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax1']\t = $obj->localtax1;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax1_type']\t= $obj->localtax1_type;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax2']\t = $obj->localtax2;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax2_type']\t= $obj->localtax1_type;", "\t\t\t\t\t$this->cache_vatrates[$i]['label']\t= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or *\n\t\t\t\t\t$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');\t// Must never be used as key, only label\n\t\t\t\t\t$positiverates='';\n\t\t\t\t\tif ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;\n\t\t\t\t\tif ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;\n\t\t\t\t\tif ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;\n\t\t\t\t\tif (empty($positiverates)) $positiverates='0';\n\t\t\t\t\t$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');\t// Must never be used as key, only label\n\t\t\t\t}", "\t\t\t\treturn $num;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$this->error = '<font class=\"error\">'.$langs->trans(\"ErrorNoVATRateDefinedForSellerCountry\",$country_code).'</font>';\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$this->error = '<font class=\"error\">'.$this->db->error().'</font>';\n\t\t\treturn -2;\n\t\t}\n\t}", "\t/**\n\t * Output an HTML select vat rate.\n\t * The name of this function should be selectVat. We keep bad name for compatibility purpose.\n\t *\n\t * @param\tstring\t $htmlname Name of HTML select field\n\t * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.\n\t * @param Societe\t $societe_vendeuse Thirdparty seller\n\t * @param Societe\t $societe_acheteuse Thirdparty buyer\n\t * @param int\t\t $idprod Id product. O if unknown of NA.\n\t * @param int\t\t $info_bits Miscellaneous information on line (1 for NPR)\n\t * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)\n\t * \t\t Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.\n\t * \t\t\t\t\t Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.\n\t * \t\t\t\t\t Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.\n\t * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.\n\t * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.\n\t * \t\t\t\t\t Sinon la TVA proposee par defaut=0. Fin de regle.\n\t * @param\tbool\t $options_only\t\t Return HTML options lines only (for ajax treatment)\n\t * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key\n\t * @return\tstring\n\t */\n\tfunction load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)\n\t{\n\t\tglobal $langs,$conf,$mysoc;", "\t\t$langs->load('errors');", "\t\t$return='';", "\t\t// Define defaultnpr, defaultttx and defaultcode\n\t\t$defaultnpr=($info_bits & 0x01);\n\t\t$defaultnpr=(preg_match('/\\*/',$selectedrate) ? 1 : $defaultnpr);\n\t\t$defaulttx=str_replace('*','',$selectedrate);\n\t\t$defaultcode='';\n\t\tif (preg_match('/\\((.*)\\)/', $defaulttx, $reg))\n\t\t{\n\t\t\t$defaultcode=$reg[1];\n\t\t\t$defaulttx=preg_replace('/\\s*\\(.*\\)/','',$defaulttx);\n\t\t}\n\t\t//var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);", "\t\t// Check parameters\n\t\tif (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)\n\t\t{\n\t\t\tif ($societe_vendeuse->id == $mysoc->id)\n\t\t\t{\n\t\t\t\t$return.= '<font class=\"error\">'.$langs->trans(\"ErrorYourCountryIsNotDefined\").'</div>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$return.= '<font class=\"error\">'.$langs->trans(\"ErrorSupplierCountryIsNotDefined\").'</div>';\n\t\t\t}\n\t\t\treturn $return;\n\t\t}", "\t\t//var_dump($societe_acheteuse);\n\t\t//print \"name=$name, selectedrate=$selectedrate, seller=\".$societe_vendeuse->country_code.\" buyer=\".$societe_acheteuse->country_code.\" buyer is company=\".$societe_acheteuse->isACompany().\" idprod=$idprod, info_bits=$info_bits type=$type\";\n\t\t//exit;", "\t\t// Define list of countries to use to search VAT rates to show\n\t\t// First we defined code_country to use to find list\n\t\tif (is_object($societe_vendeuse))\n\t\t{\n\t\t\t$code_country=\"'\".$societe_vendeuse->country_code.\"'\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$code_country=\"'\".$mysoc->country_code.\"'\"; // Pour compatibilite ascendente\n\t\t}\n\t\tif (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';\n\t\t\tif (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))\n\t\t\t{\n\t\t\t\t// We also add the buyer\n\t\t\t\tif (is_numeric($type))\n\t\t\t\t{\n\t\t\t\t\tif ($type == 1) // We know product is a service\n\t\t\t\t\t{\n\t\t\t\t\t\t$code_country.=\",'\".$societe_acheteuse->country_code.\"'\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (! $idprod) // We don't know type of product\n\t\t\t\t{\n\t\t\t\t\t$code_country.=\",'\".$societe_acheteuse->country_code.\"'\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$prodstatic=new Product($this->db);\n\t\t\t\t\t$prodstatic->fetch($idprod);\n\t\t\t\t\tif ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service\n\t\t\t\t\t{\n\t\t\t\t\t\t$code_country.=\",'\".$societe_acheteuse->country_code.\"'\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t// Now we get list\n\t\t$num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error", "\t\tif ($num > 0)\n\t\t{\n\t\t\t// Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')\n\t\t\tif ($defaulttx < 0 || dol_strlen($defaulttx) == 0)\n\t\t\t{\n\t\t\t\t$tmpthirdparty=new Societe($this->db);\n\t\t\t\t$defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);\n\t\t\t\t$defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);\n\t\t\t\tif (empty($defaulttx)) $defaultnpr=0;\n\t\t\t}", "\t\t\t// Si taux par defaut n'a pu etre determine, on prend dernier de la liste.\n\t\t\t// Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant\n\t\t\tif ($defaulttx < 0 || dol_strlen($defaulttx) == 0)\n\t\t\t{\n\t\t\t\tif (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];\n\t\t\t\telse $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);\n\t\t\t}", "\t\t\t// Disabled if seller is not subject to VAT\n\t\t\t$disabled=false; $title='';\n\t\t\tif (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == \"0\")\n\t\t\t{\n\t\t\t\t$title=' title=\"'.$langs->trans('VATIsNotUsed').'\"';\n\t\t\t\t$disabled=true;\n\t\t\t}", "\t\t\tif (! $options_only) $return.= '<select class=\"flat minwidth75imp\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.($disabled?' disabled':'').$title.'>';", "\t\t\t$selectedfound=false;\n\t\t\tforeach ($this->cache_vatrates as $rate)\n\t\t\t{\n\t\t\t\t// Keep only 0 if seller is not subject to VAT\n\t\t\t\tif ($disabled && $rate['txtva'] != 0) continue;", "\t\t\t\t// Define key to use into select list\n\t\t\t\t$key = $rate['txtva'];\n\t\t\t\t$key.= $rate['nprtva'] ? '*': '';\n\t\t\t\tif ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';\n\t\t\t\tif ($mode < 0) $key = $rate['rowid'];", "\t\t\t\t$return.= '<option value=\"'.$key.'\"';\n\t\t\t\tif (! $selectedfound)\n\t\t\t\t{\n\t\t\t\t\tif ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($defaultcode == $rate['code'])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$return.= ' selected';\n\t\t\t\t\t\t\t$selectedfound=true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)\n\t\t\t \t\t{\n\t\t\t \t\t\t$return.= ' selected';\n\t\t\t \t\t\t$selectedfound=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$return.= '>';\n\t\t\t\t//if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))\n\t\t\t\tif ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))\n\t\t\t\t{\n\t\t\t\t\t$return.= $rate['labelpositiverates'];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$return.= vatrate($rate['label']);\n\t\t\t\t}\n\t\t\t\t//$return.=($rate['code']?' '.$rate['code']:'');\n\t\t\t\t$return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': ''; // We show the * (old behaviour only if new vat code is not used)", "\t\t\t\t$return.= '</option>';\n\t\t\t}", "\t\t\tif (! $options_only) $return.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$return.= $this->error;\n\t\t}", "\t\t$this->num = $num;\n\t\treturn $return;\n\t}", "\n\t/**\n\t *\tShow a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.\n\t * Fields are preselected with :\n\t * \t- set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')\n\t * \t- local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)\n\t * \t- Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)\n\t *\n\t *\t@param\ttimestamp\t$set_time \t\tPre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0).\n\t *\t@param\tstring\t\t$prefix\t\t\tPrefix for fields name\n\t *\t@param\tint\t\t\t$h\t\t\t\t1=Show also hours (-1 has same effect, but hour and minutes are prefilled with 23:59 if $set_time = -1)\n\t *\t@param\tint\t\t\t$m\t\t\t\t1=Show also minutes\n\t *\t@param\tint\t\t\t$empty\t\t\t0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only\n\t *\t@param\tstring\t\t$form_name \t\tNot used\n\t *\t@param\tint\t\t\t$d\t\t\t\t1=Show days, month, years\n\t * \t@param\tint\t\t\t$addnowlink\t\tAdd a link \"Now\"\n\t * \t@param\tint\t\t\t$nooutput\t\tDo not output html string but return it\n\t * \t@param \tint\t\t\t$disabled\t\tDisable input fields\n\t * @param int\t\t\t$fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59\n\t * @param\tstring\t\t$addplusone\t\tAdd a link \"+1 hour\". Value must be name of another select_date field.\n\t * @param datetime $adddateof Add a link \"Date of invoice\" using the following date.\n\t * \t@return\tstring|null\t\t\t\t\t\tNothing or string if nooutput is 1\n\t * @see\tform_date\n\t */\n\tfunction select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name=\"\", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')\n\t{\n\t\tglobal $conf,$langs;", "\t\t$retstring='';", "\t\tif($prefix=='') $prefix='re';\n\t\tif($h == '') $h=0;\n\t\tif($m == '') $m=0;\n\t\t$emptydate=0;\n\t\t$emptyhours=0;\n\t\tif ($empty == 1) { $emptydate=1; $emptyhours=1; }\n\t\tif ($empty == 2) { $emptydate=0; $emptyhours=1; }\n\t\t$orig_set_time=$set_time;", "\t\tif ($set_time === '' && $emptydate == 0)\n\t\t{\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';\n\t\t\t$set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone\n\t\t}", "\t\t// Analysis of the pre-selection date\n\t\tif (preg_match('/^([0-9]+)\\-([0-9]+)\\-([0-9]+)\\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))\n\t\t{\n\t\t\t// Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'\n\t\t\t$syear\t= (! empty($reg[1])?$reg[1]:'');\n\t\t\t$smonth\t= (! empty($reg[2])?$reg[2]:'');\n\t\t\t$sday\t= (! empty($reg[3])?$reg[3]:'');\n\t\t\t$shour\t= (! empty($reg[4])?$reg[4]:'');\n\t\t\t$smin\t= (! empty($reg[5])?$reg[5]:'');\n\t\t}\n\t\telseif (strval($set_time) != '' && $set_time != -1)\n\t\t{\n\t\t\t// set_time est un timestamps (0 possible)\n\t\t\t$syear = dol_print_date($set_time, \"%Y\");\n\t\t\t$smonth = dol_print_date($set_time, \"%m\");\n\t\t\t$sday = dol_print_date($set_time, \"%d\");\n\t\t\tif ($orig_set_time != '')\n\t\t\t{\n\t\t\t\t$shour = dol_print_date($set_time, \"%H\");\n\t\t\t\t$smin = dol_print_date($set_time, \"%M\");\n\t\t\t\t$ssec = dol_print_date($set_time, \"%S\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$shour = '';\n\t\t\t\t$smin = '';\n\t\t\t\t$ssec = '';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Date est '' ou vaut -1\n\t\t\t$syear = '';\n\t\t\t$smonth = '';\n\t\t\t$sday = '';\n\t\t\t$shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;\n\t\t\t$smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;\n\t\t\t$ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;\n\t\t}", "\t\t// You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'\n\t\t$usecalendar='combo';\n\t\tif (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != \"none\")) {\n\t\t\t$usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);\n\t\t}\n\t\t//if (! empty($conf->browser->phone)) $usecalendar='combo';", "\t\tif ($d)\n\t\t{\n\t\t\t// Show date with popup\n\t\t\tif ($usecalendar != 'combo')\n\t\t\t{\n\t\t\t\t$formated_date='';\n\t\t\t\t//print \"e\".$set_time.\" t \".$conf->format_date_short;\n\t\t\t\tif (strval($set_time) != '' && $set_time != -1)\n\t\t\t\t{\n\t\t\t\t\t//$formated_date=dol_print_date($set_time,$conf->format_date_short);\n\t\t\t\t\t$formated_date=dol_print_date($set_time,$langs->trans(\"FormatDateShortInput\")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript\n\t\t\t\t}", "\t\t\t\t// Calendrier popup version eldy\n\t\t\t\tif ($usecalendar == \"eldy\")\n\t\t\t\t{\n\t\t\t\t\t// Zone de saisie manuelle de la date\n\t\t\t\t\t$retstring.='<input id=\"'.$prefix.'\" name=\"'.$prefix.'\" type=\"text\" class=\"maxwidth75\" maxlength=\"11\" value=\"'.$formated_date.'\"';\n\t\t\t\t\t$retstring.=($disabled?' disabled':'');\n\t\t\t\t\t$retstring.=' onChange=\"dpChangeDay(\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\'); \"'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript\n\t\t\t\t\t$retstring.='>';", "\t\t\t\t\t// Icone calendrier\n\t\t\t\t\tif (! $disabled)\n\t\t\t\t\t{\n\t\t\t\t\t\t$retstring.='<button id=\"'.$prefix.'Button\" type=\"button\" class=\"dpInvisibleButtons\"';\n\t\t\t\t\t\t$base=DOL_URL_ROOT.'/core/';\n\t\t\t\t\t\t$retstring.=' onClick=\"showDP(\\''.$base.'\\',\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\',\\''.$langs->defaultlang.'\\');\"';\n\t\t\t\t\t\t$retstring.='>'.img_object($langs->trans(\"SelectDate\"),'calendarday','class=\"datecallink\"').'</button>';\n\t\t\t\t\t}\n\t\t\t\t\telse $retstring.='<button id=\"'.$prefix.'Button\" type=\"button\" class=\"dpInvisibleButtons\">'.img_object($langs->trans(\"Disabled\"),'calendarday','class=\"datecallink\"').'</button>';", "\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'day\" name=\"'.$prefix.'day\" value=\"'.$sday.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'month\" name=\"'.$prefix.'month\" value=\"'.$smonth.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\" value=\"'.$syear.'\">'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telseif ($usecalendar == 'jquery')\n\t\t\t\t{\n\t\t\t\t\tif (! $disabled)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Output javascript for datepicker\n\t\t\t\t\t\t$retstring.=\"<script type='text/javascript'>\";\n\t\t\t\t\t\t$retstring.=\"$(function(){ $('#\".$prefix.\"').datepicker({\n\t\t\t\t\t\t\tdateFormat: '\".$langs->trans(\"FormatDateShortJQueryInput\").\"',\n\t\t\t\t\t\t\tautoclose: true,\n\t\t\t\t\t\t\ttodayHighlight: true,\";\n\t\t\t\t\t\t\tif (! empty($conf->dol_use_jmobile))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$retstring.=\"\n\t\t\t\t\t\t\t\tbeforeShow: function (input, datePicker) {\n\t\t\t\t\t\t\t\t\tinput.disabled = true;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonClose: function (dateText, datePicker) {\n\t\t\t\t\t\t\t\t\tthis.disabled = false;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php\n\t\t\t\t\t\t\tif (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$retstring.=\"\n\t\t\t\t\t\t\t\tshowOn: 'button',\n\t\t\t\t\t\t\t\tbuttonImage: '\".DOL_URL_ROOT.\"/theme/\".$conf->theme.\"/img/object_calendarday.png',\n\t\t\t\t\t\t\t\tbuttonImageOnly: true\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$retstring.=\"\n\t\t\t\t\t\t\t}) });\";\n\t\t\t\t\t\t$retstring.=\"</script>\";\n\t\t\t\t\t}", "\t\t\t\t\t// Zone de saisie manuelle de la date\n\t\t\t\t\t$retstring.='<input id=\"'.$prefix.'\" name=\"'.$prefix.'\" type=\"text\" class=\"maxwidth75\" maxlength=\"11\" value=\"'.$formated_date.'\"';\n\t\t\t\t\t$retstring.=($disabled?' disabled':'');\n\t\t\t\t\t$retstring.=' onChange=\"dpChangeDay(\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\'); \"'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript\n\t\t\t\t\t$retstring.='>';", "\t\t\t\t\t// Icone calendrier\n\t\t\t\t\tif (! $disabled)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Not required. Managed by option buttonImage of jquery\n \t\t$retstring.=img_object($langs->trans(\"SelectDate\"),'calendarday','id=\"'.$prefix.'id\" class=\"datecallink\"');\n \t\t$retstring.=\"<script type='text/javascript'>\";\n \t\t$retstring.=\"jQuery(document).ready(function() {\";\n \t\t$retstring.='\tjQuery(\"#'.$prefix.'id\").click(function() {';\n \t\t$retstring.=\" \tjQuery('#\".$prefix.\"').focus();\";\n \t\t$retstring.=' });';\n \t\t$retstring.='});';\n \t\t$retstring.=\"</script>\";*/\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$retstring.='<button id=\"'.$prefix.'Button\" type=\"button\" class=\"dpInvisibleButtons\">'.img_object($langs->trans(\"Disabled\"),'calendarday','class=\"datecallink\"').'</button>';\n\t\t\t\t\t}", "\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'day\" name=\"'.$prefix.'day\" value=\"'.$sday.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'month\" name=\"'.$prefix.'month\" value=\"'.$smonth.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\" value=\"'.$syear.'\">'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$retstring.=\"Bad value of MAIN_POPUP_CALENDAR\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Show date with combo selects\n\t\t\telse\n\t\t\t{\n\t\t\t\t//$retstring.='<div class=\"inline-block\">';\n\t\t\t\t// Day\n\t\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth50imp\" id=\"'.$prefix.'day\" name=\"'.$prefix.'day\">';", "\t\t\t\tif ($emptydate || $set_time == -1)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"0\" selected>&nbsp;</option>';\n\t\t\t\t}", "\t\t\t\tfor ($day = 1 ; $day <= 31; $day++)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"'.$day.'\"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';\n\t\t\t\t}", "\t\t\t\t$retstring.=\"</select>\";", "\t\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth75imp\" id=\"'.$prefix.'month\" name=\"'.$prefix.'month\">';\n\t\t\t\tif ($emptydate || $set_time == -1)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"0\" selected>&nbsp;</option>';\n\t\t\t\t}", "\t\t\t\t// Month\n\t\t\t\tfor ($month = 1 ; $month <= 12 ; $month++)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"'.$month.'\"'.($month == $smonth?' selected':'').'>';\n\t\t\t\t\t$retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),\"%b\");\n\t\t\t\t\t$retstring.=\"</option>\";\n\t\t\t\t}\n\t\t\t\t$retstring.=\"</select>\";", "\t\t\t\t// Year\n\t\t\t\tif ($emptydate || $set_time == -1)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<input'.($disabled?' disabled':'').' placeholder=\"'.dol_escape_htmltag($langs->trans(\"Year\")).'\" class=\"flat maxwidth50imp valignmiddle\" type=\"number\" min=\"0\" max=\"3000\" maxlength=\"4\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\" value=\"'.$syear.'\">';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth75imp\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\">';", "\t\t\t\t\tfor ($year = $syear - 10; $year < $syear + 10 ; $year++)\n\t\t\t\t\t{\n\t\t\t\t\t\t$retstring.='<option value=\"'.$year.'\"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';\n\t\t\t\t\t}\n\t\t\t\t\t$retstring.=\"</select>\\n\";\n\t\t\t\t}\n\t\t\t\t//$retstring.='</div>';\n\t\t\t}\n\t\t}", "\t\tif ($d && $h) $retstring.=($h==2?'<br>':' ');", "\t\tif ($h)\n\t\t{\n\t\t\t// Show hour\n\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'\" id=\"'.$prefix.'hour\" name=\"'.$prefix.'hour\">';\n\t\t\tif ($emptyhours) $retstring.='<option value=\"-1\">&nbsp;</option>';\n\t\t\tfor ($hour = 0; $hour < 24; $hour++)\n\t\t\t{\n\t\t\t\tif (strlen($hour) < 2) $hour = \"0\" . $hour;\n\t\t\t\t$retstring.='<option value=\"'.$hour.'\"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';\n\t\t\t}\n\t\t\t$retstring.='</select>';\n\t\t\tif ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=\":\";\n\t\t}", "\t\tif ($m)\n\t\t{\n\t\t\t// Show minutes\n\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'\" id=\"'.$prefix.'min\" name=\"'.$prefix.'min\">';\n\t\t\tif ($emptyhours) $retstring.='<option value=\"-1\">&nbsp;</option>';\n\t\t\tfor ($min = 0; $min < 60 ; $min++)\n\t\t\t{\n\t\t\t\tif (strlen($min) < 2) $min = \"0\" . $min;\n\t\t\t\t$retstring.='<option value=\"'.$min.'\"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';\n\t\t\t}\n\t\t\t$retstring.='</select>';", "\t\t\t$retstring.='<input type=\"hidden\" name=\"'.$prefix.'sec\" value=\"'.$ssec.'\">';\n\t\t}", "\t\t// Add a \"Now\" link\n\t\tif ($conf->use_javascript_ajax && $addnowlink)\n\t\t{\n\t\t\t// Script which will be inserted in the onClick of the \"Now\" link\n\t\t\t$reset_scripts = \"\";", "\t\t\t// Generate the date part, depending on the use or not of the javascript calendar\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'\\').val(\\''.dol_print_date(dol_now(),'day').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'day\\').val(\\''.dol_print_date(dol_now(),'%d').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'month\\').val(\\''.dol_print_date(dol_now(),'%m').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'year\\').val(\\''.dol_print_date(dol_now(),'%Y').'\\');';\n\t\t\t/*if ($usecalendar == \"eldy\")\n {\n $base=DOL_URL_ROOT.'/core/';\n $reset_scripts .= 'resetDP(\\''.$base.'\\',\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\',\\''.$langs->defaultlang.'\\');';\n }\n else\n {\n $reset_scripts .= 'this.form.elements[\\''.$prefix.'day\\'].value=formatDate(new Date(), \\'d\\'); ';\n $reset_scripts .= 'this.form.elements[\\''.$prefix.'month\\'].value=formatDate(new Date(), \\'M\\'); ';\n $reset_scripts .= 'this.form.elements[\\''.$prefix.'year\\'].value=formatDate(new Date(), \\'yyyy\\'); ';\n }*/\n\t\t\t// Update the hour part\n\t\t\tif ($h)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t//$reset_scripts .= 'this.form.elements[\\''.$prefix.'hour\\'].value=formatDate(new Date(), \\'HH\\'); ';\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'hour\\').val(\\''.dol_print_date(dol_now(),'%H').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// Update the minute part\n\t\t\tif ($m)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t//$reset_scripts .= 'this.form.elements[\\''.$prefix.'min\\'].value=formatDate(new Date(), \\'mm\\'); ';\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'min\\').val(\\''.dol_print_date(dol_now(),'%M').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// If reset_scripts is not empty, print the link with the reset_scripts in the onClick\n\t\t\tif ($reset_scripts && empty($conf->dol_optimize_smallscreen))\n\t\t\t{\n\t\t\t\t$retstring.=' <button class=\"dpInvisibleButtons datenowlink\" id=\"'.$prefix.'ButtonNow\" type=\"button\" name=\"_useless\" value=\"now\" onClick=\"'.$reset_scripts.'\">';\n\t\t\t\t$retstring.=$langs->trans(\"Now\");\n\t\t\t\t$retstring.='</button> ';\n\t\t\t}\n\t\t}", "\t\t// Add a \"Plus one hour\" link\n\t\tif ($conf->use_javascript_ajax && $addplusone)\n\t\t{\n\t\t\t// Script which will be inserted in the onClick of the \"Add plusone\" link\n\t\t\t$reset_scripts = \"\";", "\t\t\t// Generate the date part, depending on the use or not of the javascript calendar\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'\\').val(\\''.dol_print_date(dol_now(),'day').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'day\\').val(\\''.dol_print_date(dol_now(),'%d').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'month\\').val(\\''.dol_print_date(dol_now(),'%m').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'year\\').val(\\''.dol_print_date(dol_now(),'%Y').'\\');';\n\t\t\t// Update the hour part\n\t\t\tif ($h)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'hour\\').val(\\''.dol_print_date(dol_now(),'%H').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// Update the minute part\n\t\t\tif ($m)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'min\\').val(\\''.dol_print_date(dol_now(),'%M').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// If reset_scripts is not empty, print the link with the reset_scripts in the onClick\n\t\t\tif ($reset_scripts && empty($conf->dol_optimize_smallscreen))\n\t\t\t{\n\t\t\t\t$retstring.=' <button class=\"dpInvisibleButtons datenowlink\" id=\"'.$prefix.'ButtonPlusOne\" type=\"button\" name=\"_useless2\" value=\"plusone\" onClick=\"'.$reset_scripts.'\">';\n\t\t\t\t$retstring.=$langs->trans(\"DateStartPlusOne\");\n\t\t\t\t$retstring.='</button> ';\n\t\t\t}\n\t\t}", "\t\t// Add a \"Plus one hour\" link\n\t\tif ($conf->use_javascript_ajax && $adddateof)\n\t\t{\n\t\t\t$tmparray=dol_getdate($adddateof);\n\t\t\t$retstring.=' - <button class=\"dpInvisibleButtons datenowlink\" id=\"dateofinvoice\" type=\"button\" name=\"_dateofinvoice\" value=\"now\" onclick=\"jQuery(\\'#re\\').val(\\''.dol_print_date($adddateof,'day').'\\');jQuery(\\'#reday\\').val(\\''.$tmparray['mday'].'\\');jQuery(\\'#remonth\\').val(\\''.$tmparray['mon'].'\\');jQuery(\\'#reyear\\').val(\\''.$tmparray['year'].'\\');\">'.$langs->trans(\"DateInvoice\").'</a>';\n\t\t}", "\t\tif (! empty($nooutput)) return $retstring;", "\t\tprint $retstring;\n\t\treturn;\n\t}", "\t/**\n\t *\tFunction to show a form to select a duration on a page\n\t *\n\t *\t@param\tstring\t$prefix \t\tPrefix for input fields\n\t *\t@param int\t$iSecond \t\t Default preselected duration (number of seconds or '')\n\t * \t@param\tint\t$disabled Disable the combo box\n\t * \t@param\tstring\t$typehour\t\tIf 'select' then input hour and input min is a combo,\n\t *\t\t\t\t\t\t if 'text' input hour is in text and input min is a text,\n\t *\t\t\t\t\t\t if 'textselect' input hour is in text and input min is a combo\n\t * @param\tinteger\t$minunderhours\tIf 1, show minutes selection under the hours\n\t * \t@param\tint\t$nooutput\t\t Do not output html string but return it\n\t * @return\tstring|null\n\t */\n\tfunction select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)\n\t{\n\t\tglobal $langs;", "\t\t$retstring='';", "\t\t$hourSelected=0; $minSelected=0;", "\t\t// Hours\n\t\tif ($iSecond != '')\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';", "\t\t\t$hourSelected = convertSecondToTime($iSecond,'allhour');\n\t\t\t$minSelected = convertSecondToTime($iSecond,'min');\n\t\t}", "\t\tif ($typehour=='select' )\n\t\t{\n\t\t\t$retstring.='<select class=\"flat\" name=\"'.$prefix.'hour\"'.($disabled?' disabled':'').'>';\n\t\t\tfor ($hour = 0; $hour < 25; $hour++)\t// For a duration, we allow 24 hours\n\t\t\t{\n\t\t\t\t$retstring.='<option value=\"'.$hour.'\"';\n\t\t\t\tif ($hourSelected == $hour)\n\t\t\t\t{\n\t\t\t\t\t$retstring.=\" selected\";\n\t\t\t\t}\n\t\t\t\t$retstring.=\">\".$hour.\"</option>\";\n\t\t\t}\n\t\t\t$retstring.=\"</select>\";\n\t\t}\n\t\telseif ($typehour=='text' || $typehour=='textselect')\n\t\t{\n\t\t\t$retstring.='<input placeholder=\"'.$langs->trans('HourShort').'\" type=\"number\" min=\"0\" size=\"1\" name=\"'.$prefix.'hour\"'.($disabled?' disabled':'').' class=\"flat maxwidth50 inputhour\" value=\"'.(($hourSelected != '')?((int) $hourSelected):'').'\">';\n\t\t}\n\t\telse return 'BadValueForParameterTypeHour';", "\t\tif ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');\n\t\telse $retstring.='<span class=\"hideonsmartphone\">:</span>';", "\t\t// Minutes\n\t\tif ($minunderhours) $retstring.='<br>';\n\t\telse $retstring.='<span class=\"hideonsmartphone\">&nbsp;</span>';", "\t\tif ($typehour=='select' || $typehour=='textselect')\n\t\t{\n\t\t\t$retstring.='<select class=\"flat\" name=\"'.$prefix.'min\"'.($disabled?' disabled':'').'>';\n\t\t\tfor ($min = 0; $min <= 55; $min=$min+5)\n\t\t\t{\n\t\t\t\t$retstring.='<option value=\"'.$min.'\"';\n\t\t\t\tif ($minSelected == $min) $retstring.=' selected';\n\t\t\t\t$retstring.='>'.$min.'</option>';\n\t\t\t}\n\t\t\t$retstring.=\"</select>\";\n\t\t}\n\t\telseif ($typehour=='text' )\n\t\t{\n\t\t\t$retstring.='<input placeholder=\"'.$langs->trans('MinuteShort').'\" type=\"number\" min=\"0\" size=\"1\" name=\"'.$prefix.'min\"'.($disabled?' disabled':'').' class=\"flat maxwidth50 inputminute\" value=\"'.(($minSelected != '')?((int) $minSelected):'').'\">';\n\t\t}", "\t\tif ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');", "\t\t//$retstring.=\"&nbsp;\";", "\t\tif (! empty($nooutput)) return $retstring;", "\t\tprint $retstring;\n\t\treturn;\n\t}", "\n\t/**\n\t * Generic method to select a component from a combo list.\n\t * This is the generic method that will replace all specific existing methods.\n\t *\n\t * @param \tstring\t\t\t$objectdesc\t\t\tObjectclassname:Objectclasspath\n\t * @param\tstring\t\t\t$htmlname\t\t\tName of HTML select component\n\t * @param\tint\t\t\t\t$preselectedvalue\tPreselected value (ID of element)\n\t * @param\tstring\t\t\t$showempty\t\t\t''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)\n\t * @param\tstring\t\t\t$searchkey\t\t\tSearch criteria\n\t * @param\tstring\t\t\t$placeholder\t\tPlace holder\n\t * @param\tstring\t\t\t$morecss\t\t\tMore CSS\n\t * @param\tstring\t\t\t$moreparams\t\t\tMore params provided to ajax call\n\t * @param\tint\t\t\t\t$forcecombo\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @return\tstring\t\t\t\t\t\t\t\tReturn HTML string\n\t * @see selectForFormsList select_thirdparty\n\t */\n\tfunction selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)\n\t{\n\t\tglobal $conf, $user;", "\t\t$objecttmp = null;", "\t\t$InfoFieldList = explode(\":\", $objectdesc);\n\t\t$classname=$InfoFieldList[0];\n\t\t$classpath=$InfoFieldList[1];\n\t\tif (! empty($classpath))\n\t\t{\n\t\t\tdol_include_once($classpath);\n\t\t\tif ($classname && class_exists($classname))\n\t\t\t{\n\t\t\t\t$objecttmp = new $classname($this->db);\n\t\t\t}\n\t\t}\n\t\tif (! is_object($objecttmp))\n\t\t{\n\t\t\tdol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);\n\t\t\treturn 'Error bad setup of type for field '.join(',', $InfoFieldList);\n\t\t}", "\t\t$prefixforautocompletemode=$objecttmp->element;\n\t\tif ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';\n\t\t$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';\t// For example COMPANY_USE_SEARCH_TO_SELECT", "\t\tdol_syslog(get_class($this).\"::selectForForms\", LOG_DEBUG);", "\t\t$out='';\n\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)\n\t\t{\n\t\t\t$objectdesc=$classname.':'.$classpath;\n\t\t\t$urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';\n\t\t\t//if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';", "\t\t\t// No immediate load of all database\n\t\t\t$urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');\n\t\t\t// Activate the auto complete using ajax call.\n\t\t\t$out.= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());\n\t\t\t$out.= '<style type=\"text/css\">.ui-autocomplete { z-index: 250; }</style>';\n\t\t\tif ($placeholder) $placeholder=' placeholder=\"'.$placeholder.'\"';\n\t\t\t$out.= '<input type=\"text\" class=\"'.$morecss.'\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$preselectedvalue.'\"'.$placeholder.' />';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Immediate load of all database\n\t\t\t$out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Output html form to select an object.\n\t * Note, this function is called by selectForForms or by ajax selectobject.php\n\t *\n\t * @param \tObject\t\t\t$objecttmp\t\t\tObject\n\t * @param\tstring\t\t\t$htmlname\t\t\tName of HTML select component\n\t * @param\tint\t\t\t\t$preselectedvalue\tPreselected value (ID of element)\n\t * @param\tstring\t\t\t$showempty\t\t\t''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)\n\t * @param\tstring\t\t\t$searchkey\t\t\tSearch value\n\t * @param\tstring\t\t\t$placeholder\t\tPlace holder\n\t * @param\tstring\t\t\t$morecss\t\t\tMore CSS\n\t * @param\tstring\t\t\t$moreparams\t\t\tMore params provided to ajax call\n\t * @param\tint\t\t\t\t$forcecombo\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @param\tint\t\t\t\t$outputmode\t\t\t0=HTML select string, 1=Array\n\t * @return\tstring\t\t\t\t\t\t\t\tReturn HTML string\n\t * @see selectForForms\n\t */\n\tfunction selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)\n\t{\n\t\tglobal $conf, $langs, $user;", "\t\t$prefixforautocompletemode=$objecttmp->element;\n\t\tif ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';\n\t\t$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';\t// For example COMPANY_USE_SEARCH_TO_SELECT", "\t\t$fieldstoshow='t.ref';\n\t\tif (! empty($objecttmp->fields))\t// For object that declare it, it is better to use declared fields ( like societe, contact, ...)\n\t\t{\n\t\t\t$tmpfieldstoshow='';\n\t\t\tforeach($objecttmp->fields as $key => $val)\n\t\t\t{\n\t\t\t\tif ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;\n\t\t\t}\n\t\t\tif ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;\n\t\t}", "\t\t$out='';\n\t\t$outarray=array();", "\t\t$num=0;", "\t\t// Search data\n\t\t$sql = \"SELECT t.rowid, \".$fieldstoshow.\" FROM \".MAIN_DB_PREFIX .$objecttmp->table_element.\" as t\";\n\t\tif ($objecttmp->ismultientitymanaged == 2)\n\t\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= \", \".MAIN_DB_PREFIX.\"societe_commerciaux as sc\";\n\t\t$sql.= \" WHERE 1=1\";\n\t\tif(! empty($objecttmp->ismultientitymanaged)) $sql.= \" AND t.entity IN (\".getEntity($objecttmp->table_element).\")\";\n\t\tif ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))\n\t\t{\n\t\t\tif ($objecttmp->element == 'societe') $sql.= \" AND t.rowid = \".$user->societe_id;\n\t\t\t\telse $sql.= \" AND t.fk_soc = \".$user->societe_id;\n\t\t}\n\t\tif ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);\n\t\tif ($objecttmp->ismultientitymanaged == 2)\n\t\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= \" AND t.rowid = sc.fk_soc AND sc.fk_user = \" .$user->id;\n\t\t$sql.=$this->db->order($fieldstoshow,\"ASC\");\n\t\t//$sql.=$this->db->plimit($limit, 0);", "\t\t// Build output string\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tif (! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);\n\t\t\t}", "\t\t\t// Construct $out and $outarray\n\t\t\t$out.= '<select id=\"'.$htmlname.'\" class=\"flat'.($morecss?' '.$morecss:'').'\"'.($moreparams?' '.$moreparams:'').' name=\"'.$htmlname.'\">'.\"\\n\";", "\t\t\t// Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4\n\t\t\t$textifempty='&nbsp;';", "\t\t\t//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';\n\t\t\tif (! empty($conf->global->$confkeyforautocompletemode))\n\t\t\t{\n\t\t\t\tif ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);\n\t\t\t\telse $textifempty.=$langs->trans(\"All\");\n\t\t\t}\n\t\t\tif ($showempty) $out.= '<option value=\"-1\">'.$textifempty.'</option>'.\"\\n\";", "\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$label='';\n\t\t\t\t\t$tmparray=explode(',', $fieldstoshow);\n\t\t\t\t\tforeach($tmparray as $key => $val)\n\t\t\t\t\t{\n\t\t\t\t\t\t$val = preg_replace('/t\\./','',$val);\n\t\t\t\t\t\t$label .= (($label && $obj->$val)?' - ':'').$obj->$val;\n\t\t\t\t\t}\n\t\t\t\t\tif (empty($outputmode))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\" selected>'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\">'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tarray_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));\n\t\t\t\t\t}", "\t\t\t\t\t$i++;\n\t\t\t\t\tif (($i % 10) == 0) $out.=\"\\n\";\n\t\t\t\t}\n\t\t\t}", "\t\t\t$out.= '</select>'.\"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\t$this->result=array('nbofelement'=>$num);", "\t\tif ($outputmode) return $outarray;\n\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn a HTML select string, built from an array of key+value.\n\t * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.\n\t *\n\t *\t@param\tstring\t\t\t$htmlname Name of html select area. Must start with \"multi\" if this is a multiselect\n\t *\t@param\tarray\t\t\t$array Array (key => value)\n\t *\t@param\tstring|string[]\t$id Preselected key or preselected keys for multiselect\n\t *\t@param\tint|string\t\t$show_empty 0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.\n\t *\t@param\tint\t\t\t\t$key_in_label 1 to show key into label with format \"[key] value\"\n\t *\t@param\tint\t\t\t\t$value_as_key 1 to use value as key\n\t *\t@param string\t\t\t$moreparam Add more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t *\t@param int\t\t\t\t$translate\t\t1=Translate and encode value\n\t * \t@param\tint\t\t\t\t$maxlen\t\t\tLength maximum for labels\n\t * \t@param\tint\t\t\t\t$disabled\t\tHtml select box is disabled\n\t * @param\tstring\t\t\t$sort\t\t\t'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order\n\t * @param\tstring\t\t\t$morecss\t\tAdd more class to css styles\n\t * @param\tint\t\t\t\t$addjscombo\t\t Add js combo\n\t * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set\n\t * @param int $disablebademail Check if an email is found into value and if not disable and colorize entry\n\t * @param int $nohtmlescape No html escaping.\n\t * \t@return\tstring\t\t\t\t\t\t\t HTML select string.\n\t * @see multiselectarray\n\t */\n\tstatic function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)\n\t{\n\t\tglobal $conf, $langs;", "\t\t// Do we want a multiselect ?\n\t\t//$jsbeautify = 0;\n\t\t//if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;\n\t\t$jsbeautify = 1;", "\t\tif ($value_as_key) $array=array_combine($array, $array);", "\t\t$out='';", "\t\t// Add code for jquery to use multiselect\n\t\tif ($addjscombo && $jsbeautify)\n\t\t{\n\t\t\t$minLengthToAutocomplete=0;\n\t\t\t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;", "\t\t\t// Enhance with select2\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t$out .= ajax_combobox($htmlname);\n\t\t}", "\t\t$out.='<select id=\"'.preg_replace('/^\\./','',$htmlname).'\" '.($disabled?'disabled ':'').'class=\"flat '.(preg_replace('/^\\./','',$htmlname)).($morecss?' '.$morecss:'').'\"';\n\t\t$out.=' name=\"'.preg_replace('/^\\./','',$htmlname).'\" '.($moreparam?$moreparam:'');\n\t\t$out.='>';", "\t\tif ($show_empty)\n\t\t{\n\t\t\t$textforempty=' ';\n\t\t\tif (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';\t// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.\n\t\t\tif (! is_numeric($show_empty)) $textforempty=$show_empty;\n\t\t\t$out.='<option class=\"optiongrey\" '.($moreparamonempty?$moreparamonempty.' ':'').'value=\"'.($show_empty < 0 ? $show_empty : -1).'\"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'.\"\\n\";\n\t\t}", "\t\tif (is_array($array))\n\t\t{\n\t\t\t// Translate\n\t\t\tif ($translate)\n\t\t\t{\n\t\t\t\tforeach($array as $key => $value)\n\t\t\t\t{\n\t\t\t\t\t$array[$key]=$langs->trans($value);\n\t\t\t\t}\n\t\t\t}", "\t\t\t// Sort\n\t\t\tif ($sort == 'ASC') asort($array);\n\t\t\telseif ($sort == 'DESC') arsort($array);", "\t\t\tforeach($array as $key => $value)\n\t\t\t{\n\t\t\t\t$disabled=''; $style='';\n\t\t\t\tif (! empty($disablebademail))\n\t\t\t\t{\n\t\t\t\t\tif (! preg_match('/&lt;.+@.+&gt;/', $value))\n\t\t\t\t\t{\n\t\t\t\t\t\t//$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);\n\t\t\t\t\t\t$disabled=' disabled';\n\t\t\t\t\t\t$style=' class=\"warning\"';\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tif ($key_in_label)\n\t\t\t\t{\n\t\t\t\t\tif (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));\n\t\t\t\t\telse $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);\n\t\t\t\t\telse $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;\n\t\t\t\t\tif ($value == '' || $value == '-') $selectOptionValue='&nbsp;';\n\t\t\t\t}", "\t\t\t\t$out.='<option value=\"'.$key.'\"';\n\t\t\t\t$out.=$style.$disabled;\n\t\t\t\tif ($id != '' && $id == $key && ! $disabled) $out.=' selected';\t\t// To preselect a value\n\t\t\t\tif ($nohtmlescape) $out.=' data-html=\"'.dol_escape_htmltag($selectOptionValue).'\"';\n\t\t\t\t$out.='>';\n\t\t\t\t//var_dump($selectOptionValue);\n\t\t\t\t$out.=$selectOptionValue;\n\t\t\t\t$out.=\"</option>\\n\";\n\t\t\t}\n\t\t}", "\t\t$out.=\"</select>\";\n\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn a HTML select string, built from an array of key+value but content returned into select come from an Ajax call of an URL.\n\t * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.\n\t *\n\t *\t@param\tstring\t$htmlname \t\tName of html select area\n\t *\t@param\tstring\t$url\t\t\t\t\tUrl. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)\n\t *\t@param\tstring\t$id \t\tPreselected key\n\t *\t@param string\t$moreparam \t\tAdd more parameters onto the select tag\n\t *\t@param string\t$moreparamtourl \t\tAdd more parameters onto the Ajax called URL\n\t * \t@param\tint\t\t$disabled\t\t\t\tHtml select box is disabled\n\t * @param\tint\t\t$minimumInputLength\t\tMinimum Input Length\n\t * @param\tstring\t$morecss\t\t\t\tAdd more class to css styles\n\t * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.\n\t * @param string $placeholder String to use as placeholder\n\t * @param integer $acceptdelayedhtml 1 if caller request to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)\n\t * \t@return\tstring \t\t\t\t\t\tHTML select string\n\t * @see ajax_combobox in ajax.lib.php\n\t */\n\tstatic function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)\n\t{\n\t\tglobal $conf, $langs;\n\t\tglobal $delayedhtmlcontent;", "\t\t// TODO Use an internal dolibarr component instead of select2\n\t\tif (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';", "\t\t$out='<select type=\"text\" class=\"'.$htmlname.($morecss?' '.$morecss:'').'\" '.($moreparam?$moreparam.' ':'').'name=\"'.$htmlname.'\"></select>';", "\t\t$tmpplugin='select2';\n\t\t$outdelayed=\"\\n\".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->\n\t \t<script type=\"text/javascript\">\n\t \t$(document).ready(function () {", " \t '.($callurlonselect ? 'var saveRemoteData = [];':'').'", " $(\".'.$htmlname.'\").select2({\n\t\t\t \tajax: {\n\t\t\t\t \tdir: \"ltr\",\n\t\t\t\t \turl: \"'.$url.'\",\n\t\t\t\t \tdataType: \\'json\\',\n\t\t\t\t \tdelay: 250,\n\t\t\t\t \tdata: function (params) {\n\t\t\t\t \t\treturn {\n\t\t\t\t\t\t \tq: params.term, \t// search term\n\t\t\t\t \t\t\tpage: params.page\n\t\t\t\t \t\t};\n\t\t\t \t\t},\n\t\t\t \t\tprocessResults: function (data) {\n\t\t\t \t\t\t// parse the results into the format expected by Select2.\n\t\t\t \t\t\t// since we are using custom formatting functions we do not need to alter the remote JSON data\n\t\t\t \t\t\t//console.log(data);\n\t\t\t\t\t\t\tsaveRemoteData = data;\n\t\t\t\t \t /* format json result for select2 */\n\t\t\t\t \t result = []\n\t\t\t\t \t $.each( data, function( key, value ) {\n\t\t\t\t \t result.push({id: key, text: value.text});\n });\n\t\t\t \t\t\t//return {results:[{id:\\'none\\', text:\\'aa\\'}, {id:\\'rrr\\', text:\\'Red\\'},{id:\\'bbb\\', text:\\'Search a into projects\\'}], more:false}\n\t\t\t \t\t\t//console.log(result);\n\t\t\t \t\t\treturn {results: result, more: false}\n\t\t\t \t\t},\n\t\t\t \t\tcache: true\n\t\t\t \t},\n\t \t\t\t\tlanguage: select2arrayoflanguage,\n\t\t\t\t\tcontainerCssClass: \\':all:\\',\t\t\t\t\t/* Line to add class of origin SELECT propagated to the new <span class=\"select2-selection...> tag */\n\t\t\t\t placeholder: \"'.dol_escape_js($placeholder).'\",\n\t\t\t \tescapeMarkup: function (markup) { return markup; }, \t// let our custom formatter work\n\t\t\t \tminimumInputLength: '.$minimumInputLength.',\n\t\t\t formatResult: function(result, container, query, escapeMarkup) {\n return escapeMarkup(result.text);\n },\n\t\t\t });", " '.($callurlonselect ? '\n /* Code to execute a GET when we select a value */\n $(\".'.$htmlname.'\").change(function() {\n\t\t\t \tvar selected = $(\".'.$htmlname.'\").val();\n \tconsole.log(\"We select \"+selected)\n\t\t\t $(\".'.$htmlname.'\").val(\"\"); /* reset visible combo value */\n \t\t\t $.each( saveRemoteData, function( key, value ) {\n \t\t\t\t if (key == selected)\n \t\t\t {\n \t\t\t console.log(\"selectArrayAjax - Do a redirect to \"+value.url)\n \t\t\t location.assign(value.url);\n \t\t\t }\n });\n \t\t\t});' : '' ) . '", " \t });\n\t </script>';", "\t\tif ($acceptdelayedhtml)\n\t\t{\n\t\t\t$delayedhtmlcontent.=$outdelayed;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$out.=$outdelayed;\n\t\t}\n\t\treturn $out;\n\t}", "\t/**\n\t *\tShow a multiselect form from an array.\n\t *\n\t *\t@param\tstring\t$htmlname\t\tName of select\n\t *\t@param\tarray\t$array\t\t\tArray with key+value\n\t *\t@param\tarray\t$selected\t\tArray with key+value preselected\n\t *\t@param\tint\t\t$key_in_label 1 pour afficher la key dans la valeur \"[key] value\"\n\t *\t@param\tint\t\t$value_as_key 1 to use value as key\n\t *\t@param string\t$morecss Add more css style\n\t *\t@param int\t\t$translate\t\tTranslate and encode value\n\t * @param\tint\t\t$width\t\t\tForce width of select box. May be used only when using jquery couch. Example: 250, 95%\n\t * @param\tstring\t$moreattrib\t\tAdd more options on select component. Example: 'disabled'\n\t * @param\tstring\t$elemtype\t\tType of element we show ('category', ...)\n\t *\t@return\tstring\t\t\t\t\tHTML multiselect string\n\t * @see selectarray\n\t */\n\tstatic function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='',$elemtype='')\n\t{\n\t\tglobal $conf, $langs;", "\t\t$out = '';", "\t\t// Add code for jquery to use multiselect\n\t\tif (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))\n\t\t{\n\t\t\t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;\n \t\t\t$out.=\"\\n\".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->\n \t\t\t<script type=\"text/javascript\">\n\t \t\t\tfunction formatResult(record) {'.\"\\n\";\n\t\t\t\t\t\tif ($elemtype == 'category')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='\t//return \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> <a href=\"'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\\'+record.id+\\'\">\\'+record.text+\\'</a></span>\\';\n\t\t\t\t\t\t\t\t \treturn \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> \\'+record.text+\\'</span>\\';';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='return record.text;';\n\t\t\t\t\t\t}\n\t\t\t$out.= '\t};\n \t\t\t\tfunction formatSelection(record) {'.\"\\n\";\n\t\t\t\t\t\tif ($elemtype == 'category')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='\t//return \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> <a href=\"'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\\'+record.id+\\'\">\\'+record.text+\\'</a></span>\\';\n\t\t\t\t\t\t\t\t \treturn \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> \\'+record.text+\\'</span>\\';';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='return record.text;';\n\t\t\t\t\t\t}\n\t\t\t$out.= '\t};\n\t \t\t\t$(document).ready(function () {\n \t\t\t\t\t$(\\'#'.$htmlname.'\\').'.$tmpplugin.'({\n \t\t\t\t\t\tdir: \\'ltr\\',\n\t\t\t\t\t\t\t// Specify format function for dropdown item\n\t\t\t\t\t\t\tformatResult: formatResult,\n \t\t\t\t\t \ttemplateResult: formatResult,\t\t/* For 4.0 */\n\t\t\t\t\t\t\t// Specify format function for selected item\n\t\t\t\t\t\t\tformatSelection: formatSelection,\n \t\t\t\t\t \ttemplateResult: formatSelection\t\t/* For 4.0 */\n \t\t\t\t\t});\n \t\t\t\t});\n \t\t\t</script>';\n\t\t}", "\t\t// Try also magic suggest", "\t\t$out .= '<select id=\"'.$htmlname.'\" class=\"multiselect'.($morecss?' '.$morecss:'').'\" multiple name=\"'.$htmlname.'[]\"'.($moreattrib?' '.$moreattrib:'').($width?' style=\"width: '.(preg_match('/%/',$width)?$width:$width.'px').'\"':'').'>'.\"\\n\";\n\t\tif (is_array($array) && ! empty($array))\n\t\t{\n\t\t\tif ($value_as_key) $array=array_combine($array, $array);", "\t\t\tif (! empty($array))\n\t\t\t{\n\t\t\t\tforeach ($array as $key => $value)\n\t\t\t\t{\n\t\t\t\t\t$out.= '<option value=\"'.$key.'\"';\n\t\t\t\t\tif (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= ' selected';\n\t\t\t\t\t}\n\t\t\t\t\t$out.= '>';", "\t\t\t\t\t$newval = ($translate ? $langs->trans($value) : $value);\n\t\t\t\t\t$newval = ($key_in_label ? $key.' - '.$newval : $newval);\n\t\t\t\t\t$out.= dol_htmlentitiesbr($newval);\n\t\t\t\t\t$out.= '</option>'.\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$out.= '</select>'.\"\\n\";", "\t\treturn $out;\n\t}", "\n\t/**\n\t *\tShow a multiselect dropbox from an array.\n\t *\n\t *\t@param\tstring\t$htmlname\t\tName of HTML field\n\t *\t@param\tarray\t$array\t\t\tArray with array of fields we could show. This array may be modified according to setup of user.\n\t * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER[\"PHP_SELF\"]:$contextpage);\n\t *\t@return\tstring\t\t\t\t\tHTML multiselect string\n\t * @see selectarray\n\t */\n\tstatic function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)\n\t{\n\t\tglobal $conf,$langs,$user;", "\t\tif (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';", "\t\t$tmpvar=\"MAIN_SELECTEDFIELDS_\".$varpage;\n\t\tif (! empty($user->conf->$tmpvar))\n\t\t{\n\t\t\t$tmparray=explode(',', $user->conf->$tmpvar);\n\t\t\tforeach($array as $key => $val)\n\t\t\t{\n\t\t\t\t//var_dump($key);\n\t\t\t\t//var_dump($tmparray);\n\t\t\t\tif (in_array($key, $tmparray)) $array[$key]['checked']=1;\n\t\t\t\telse $array[$key]['checked']=0;\n\t\t\t}\n\t\t}\n\t\t//var_dump($array);", "\t\t$lis='';\n\t\t$listcheckedstring='';", "\t\tforeach($array as $key => $val)\n\t\t{\n\t\t /* var_dump($val);\n var_dump(array_key_exists('enabled', $val));\n var_dump(!$val['enabled']);*/\n\t\t if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])\n\t\t {\n\t\t\t unset($array[$key]); // We don't want this field\n\t\t\t continue;\n\t\t }\n\t\t if ($val['label'])\n\t\t {\n\t\t\t $lis.='<li><input type=\"checkbox\" value=\"'.$key.'\"'.(empty($val['checked'])?'':' checked=\"checked\"').'/>'.dol_escape_htmltag($langs->trans($val['label'])).'</li>';\n\t\t\t $listcheckedstring.=(empty($val['checked'])?'':$key.',');\n\t\t }\n\t\t}", "\t\t$out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->", " <dl class=\"dropdown\">\n <dt>\n <a href=\"#\">\n '.img_picto('','list').'\n </a>\n <input type=\"hidden\" class=\"'.$htmlname.'\" name=\"'.$htmlname.'\" value=\"'.$listcheckedstring.'\">\n </dt>\n <dd class=\"dropowndd\">\n <div class=\"multiselectcheckbox'.$htmlname.'\">\n <ul class=\"ul'.$htmlname.'\">\n '.$lis.'\n </ul>\n </div>\n </dd>\n </dl>", " <script type=\"text/javascript\">\n jQuery(document).ready(function () {\n $(\\'.multiselectcheckbox'.$htmlname.' input[type=\"checkbox\"]\\').on(\\'click\\', function () {\n console.log(\"A new field was added/removed\")\n $(\"input:hidden[name=formfilteraction]\").val(\\'listafterchangingselectedfields\\')\n var title = $(this).val() + \",\";\n if ($(this).is(\\':checked\\')) {\n $(\\'.'.$htmlname.'\\').val(title + $(\\'.'.$htmlname.'\\').val());\n }\n else {\n $(\\'.'.$htmlname.'\\').val( $(\\'.'.$htmlname.'\\').val().replace(title, \\'\\') )\n }\n // Now, we submit page\n $(this).parents(\\'form:first\\').submit();\n });\n });\n </script>", " ';\n\t\treturn $out;\n\t}", "\t/**\n\t * \tRender list of categories linked to object with id $id and type $type\n\t *\n\t * \t@param\t\tint\t\t$id\t\t\t\tId of object\n\t * \t@param\t\tstring\t$type\t\t\tType of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.\n\t * @param\t\tint\t\t$rendermode\t\t0=Default, use multiselect. 1=Emulate multiselect (recommended)\n\t * \t@return\t\tstring\t\t\t\t\tString with categories\n\t */\n\tfunction showCategories($id, $type, $rendermode=0)\n\t{\n\t\tglobal $db;", "\t\tinclude_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';", "\t\t$cat = new Categorie($db);\n\t\t$categories = $cat->containing($id, $type);", "\t\tif ($rendermode == 1)\n\t\t{\n\t\t\t$toprint = array();\n\t\t\tforeach($categories as $c)\n\t\t\t{\n\t\t\t\t$ways = $c->print_all_ways(); // $ways[0] = \"ccc2 >> ccc2a >> ccc2a1\" with html formated text\n\t\t\t\tforeach($ways as $way)\n\t\t\t\t{\n\t\t\t\t\t$toprint[] = '<li class=\"select2-search-choice-dolibarr noborderoncategories\"'.($c->color?' style=\"background: #'.$c->color.';\"':' style=\"background: #aaa\"').'>'.img_object('','category').' '.$way.'</li>';\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn '<div class=\"select2-container-multi-dolibarr\" style=\"width: 90%;\"><ul class=\"select2-choices-dolibarr\">'.implode(' ', $toprint).'</ul></div>';\n\t\t}", "\t\tif ($rendermode == 0)\n\t\t{\n\t\t\t$cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);\n\t\t\tforeach($categories as $c) {\n\t\t\t\t$arrayselected[] = $c->id;\n\t\t\t}", "\t\t\treturn $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');\n\t\t}", "\t\treturn 'ErrorBadValueForParameterRenderMode';\t// Should not happened\n\t}", "\n\t/**\n\t * Show linked object block.\n\t *\n\t * @param\tCommonObject\t$object\t\t Object we want to show links to\n\t * @param string $morehtmlright More html to show on right of title\n\t * @return\tint\t\t\t\t\t\t\t <0 if KO, >=0 if OK\n\t */\n\tfunction showLinkedObjectBlock($object, $morehtmlright='')\n\t{\n\t\tglobal $conf,$langs,$hookmanager;\n\t\tglobal $bc;", "\t\t$object->fetchObjectLinked();", "\t\t// Bypass the default method\n\t\t$hookmanager->initHooks(array('commonobject'));\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook", "\t\tif (empty($reshook))\n\t\t{\n\t\t\t$nbofdifferenttypes = count($object->linkedObjects);", "\t\t\tprint '<!-- showLinkedObjectBlock -->';\n\t\t\tprint load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');", "\n\t\t\tprint '<div class=\"div-table-responsive-no-min\">';\n\t\t\tprint '<table class=\"noborder allwidth\">';", "\t\t\tprint '<tr class=\"liste_titre\">';\n\t\t\tprint '<td>'.$langs->trans(\"Type\").'</td>';\n\t\t\tprint '<td>'.$langs->trans(\"Ref\").'</td>';\n\t\t\tprint '<td align=\"center\"></td>';\n\t\t\tprint '<td align=\"center\">'.$langs->trans(\"Date\").'</td>';\n\t\t\tprint '<td align=\"right\">'.$langs->trans(\"AmountHTShort\").'</td>';\n\t\t\tprint '<td align=\"right\">'.$langs->trans(\"Status\").'</td>';\n\t\t\tprint '<td></td>';\n\t\t\tprint '</tr>';", "\t\t\t$nboftypesoutput=0;", "\t\t\tforeach($object->linkedObjects as $objecttype => $objects)\n\t\t\t{\n\t\t\t\t$tplpath = $element = $subelement = $objecttype;", "\t\t\t\tif ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))\n\t\t\t\t{\n\t\t\t\t\t$element = $regs[1];\n\t\t\t\t\t$subelement = $regs[2];\n\t\t\t\t\t$tplpath = $element.'/'.$subelement;\n\t\t\t\t}\n\t\t\t\t$tplname='linkedobjectblock';", "\t\t\t\t// To work with non standard path\n\t\t\t\tif ($objecttype == 'facture') {\n\t\t\t\t\t$tplpath = 'compta/'.$element;\n\t\t\t\t\tif (empty($conf->facture->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'facturerec') {\n\t\t\t\t\t$tplpath = 'compta/facture';\n\t\t\t\t\t$tplname = 'linkedobjectblockForRec';\n\t\t\t\t\tif (empty($conf->facture->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'propal') {\n\t\t\t\t\t$tplpath = 'comm/'.$element;\n\t\t\t\t\tif (empty($conf->propal->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'supplier_proposal') {\n\t\t\t\t\tif (empty($conf->supplier_proposal->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'shipping' || $objecttype == 'shipment') {\n\t\t\t\t\t$tplpath = 'expedition';\n\t\t\t\t\tif (empty($conf->expedition->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'delivery') {\n\t\t\t\t\t$tplpath = 'livraison';\n\t\t\t\t\tif (empty($conf->expedition->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'invoice_supplier') {\n\t\t\t\t\t$tplpath = 'fourn/facture';\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'order_supplier') {\n\t\t\t\t\t$tplpath = 'fourn/commande';\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'expensereport') {\n\t\t\t\t\t$tplpath = 'expensereport';\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'subscription') {\n\t\t\t\t\t$tplpath = 'adherents';\n\t\t\t\t}", "\t\t\t\tglobal $linkedObjectBlock;\n\t\t\t\t$linkedObjectBlock = $objects;", "\n\t\t\t\t// Output template part (modules that overwrite templates must declare this into descriptor)\n\t\t\t\t$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));\n\t\t\t\tforeach($dirtpls as $reldir)\n\t\t\t\t{\n\t\t\t\t\tif ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after\n\t\t\t\t\t{\n\t\t\t\t\t\tglobal $noMoreLinkedObjectBlockAfter;\n\t\t\t\t\t\t$noMoreLinkedObjectBlockAfter=1;\n\t\t\t\t\t}", "\t\t\t\t\t$res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');\n\t\t\t\t\tif ($res)\n\t\t\t\t\t{\n\t\t\t\t\t\t$nboftypesoutput++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (! $nboftypesoutput)\n\t\t\t{\n\t\t\t\tprint '<tr><td class=\"impair opacitymedium\" colspan=\"7\">'.$langs->trans(\"None\").'</td></tr>';\n\t\t\t}", "\t\t\tprint '</table>';\n\t\t\tprint '</div>';", "\t\t\treturn $nbofdifferenttypes;\n\t\t}\n\t}", "\t/**\n\t * Show block with links to link to other objects.\n\t *\n\t * @param\tCommonObject\t$object\t\t\t\tObject we want to show links to\n\t * @param\tarray\t\t\t$restrictlinksto\tRestrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.\n\t * @param\tarray\t\t\t$excludelinksto\t\tDo not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.\n\t * @return\tstring\t\t\t\t\t\t\t\t<0 if KO, >0 if OK\n\t */\n\tfunction showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())\n\t{\n\t\tglobal $conf, $langs, $hookmanager;\n\t\tglobal $bc;", "\t\t$linktoelem='';\n\t\t$linktoelemlist='';", "\t\tif (! is_object($object->thirdparty)) $object->fetch_thirdparty();", "\t\t$possiblelinks=array();\n\t\tif (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)\n\t\t{\n\t\t\t$listofidcompanytoscan=$object->thirdparty->id;\n\t\t\tif (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;\n\t\t\tif (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';\n\t\t\t\t$tmpproject=new Project($this->db);\n\t\t\t\t$tmpproject->fetch($object->fk_project);\n\t\t\t\tif ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;\n\t\t\t\tunset($tmpproject);\n\t\t\t}", "\t\t\t$possiblelinks=array(\n\t\t\t\t'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),\n\t\t\t\t'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),\n\t\t\t\t'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.facnumber as ref, t.ref_client, t.total as total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture').')'),\n\t\t\t\t'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),\n\t\t\t\t'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),\n\t\t\t\t'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),\n\t\t\t\t'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),\n\t\t\t\t'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')\n\t\t\t);\n\t\t}", "\t\tglobal $action;", "\t\t// Can complete the possiblelink array\n\t\t$hookmanager->initHooks(array('commonobject'));\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n\t\tif (empty($reshook))\n\t\t{\n\t\t\tif (is_array($hookmanager->resArray) && count($hookmanager->resArray))\n\t\t\t{\n\t\t\t\t$possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);\n\t\t\t}\n\t\t}\n\t\telse if ($reshook > 0)\n\t\t{\n\t\t\tif (is_array($hookmanager->resArray) && count($hookmanager->resArray))\n\t\t\t{\n\t\t\t\t$possiblelinks=$hookmanager->resArray;\n\t\t\t}\n\t\t}", "\t\tforeach($possiblelinks as $key => $possiblelink)\n\t\t{\n\t\t\t$num = 0;", "\t\t\tif (empty($possiblelink['enabled'])) continue;", "\t\t\tif (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))\n\t\t\t{\n\t\t\t\tprint '<div id=\"'.$key.'list\"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style=\"display:none\"':'').'>';\n\t\t\t\t$sql = $possiblelink['sql'];", "\t\t\t\t$resqllist = $this->db->query($sql);\n\t\t\t\tif ($resqllist)\n\t\t\t\t{\n\t\t\t\t\t$num = $this->db->num_rows($resqllist);\n\t\t\t\t\t$i = 0;", "\t\t\t\t\tprint '<br><form action=\"'.$_SERVER[\"PHP_SELF\"].'\" method=\"POST\" name=\"formlinked'.$key.'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"id\" value=\"'.$object->id.'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"addlink\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"addlink\" value=\"'.$key.'\">';\n\t\t\t\t\tprint '<table class=\"noborder\">';\n\t\t\t\t\tprint '<tr class=\"liste_titre\">';\n\t\t\t\t\tprint '<td class=\"nowrap\"></td>';\n\t\t\t\t\tprint '<td align=\"center\">' . $langs->trans(\"Ref\") . '</td>';\n\t\t\t\t\tprint '<td align=\"left\">' . $langs->trans(\"RefCustomer\") . '</td>';\n\t\t\t\t\tprint '<td align=\"right\">' . $langs->trans(\"AmountHTShort\") . '</td>';\n\t\t\t\t\tprint '<td align=\"left\">' . $langs->trans(\"Company\") . '</td>';\n\t\t\t\t\tprint '</tr>';\n\t\t\t\t\twhile ($i < $num)\n\t\t\t\t\t{\n\t\t\t\t\t\t$objp = $this->db->fetch_object($resqlorderlist);", "\t\t\t\t\t\t$var = ! $var;\n\t\t\t\t\t\tprint '<tr ' . $bc [$var] . '>';\n\t\t\t\t\t\tprint '<td aling=\"left\">';\n\t\t\t\t\t\tprint '<input type=\"radio\" name=\"idtolinkto\" value=' . $objp->rowid . '>';\n\t\t\t\t\t\tprint '</td>';\n\t\t\t\t\t\tprint '<td align=\"center\">' . $objp->ref . '</td>';\n\t\t\t\t\t\tprint '<td>' . $objp->ref_client . '</td>';\n\t\t\t\t\t\tprint '<td align=\"right\">' . price($objp->total_ht) . '</td>';\n\t\t\t\t\t\tprint '<td>' . $objp->name . '</td>';\n\t\t\t\t\t\tprint '</tr>';\n\t\t\t\t\t\t$i++;\n\t\t\t\t\t}\n\t\t\t\t\tprint '</table>';\n\t\t\t\t\tprint '<div class=\"center\"><input type=\"submit\" class=\"button valignmiddle\" value=\"' . $langs->trans('ToLink') . '\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"submit\" class=\"button\" name=\"cancel\" value=\"' . $langs->trans('Cancel') . '\"></div>';", "\t\t\t\t\tprint '</form>';\n\t\t\t\t\t$this->db->free($resqllist);\n\t\t\t\t} else {\n\t\t\t\t\tdol_print_error($this->db);\n\t\t\t\t}\n\t\t\t\tprint '</div>';\n\t\t\t\tif ($num > 0)\n\t\t\t\t{\n\t\t\t\t}", "\t\t\t\t//$linktoelem.=($linktoelem?' &nbsp; ':'');\n\t\t\t\tif ($num > 0) $linktoelemlist.='<li><a href=\"#linkto'.$key.'\" class=\"linkto dropdowncloseonclick\" rel=\"'.$key.'\">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';\n\t\t\t\t//else $linktoelem.=$langs->trans($possiblelink['label']);\n\t\t\t\telse $linktoelemlist.='<li><span class=\"linktodisabled\">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';\n\t\t\t}\n\t\t}", "\t\tif ($linktoelemlist)\n\t\t{\n\t\t\t$linktoelem='\n \t\t<dl class=\"dropdown\" id=\"linktoobjectname\">\n \t\t<dt><a href=\"#linktoobjectname\">'.$langs->trans(\"LinkTo\").'...</a></dt>\n \t\t<dd>\n \t\t<div class=\"multiselectlinkto\">\n \t\t<ul class=\"ulselectedfields\">'.$linktoelemlist.'\n \t\t</ul>\n \t\t</div>\n \t\t</dd>\n \t\t</dl>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$linktoelem='';\n\t\t}", "\t\tprint '<!-- Add js to show linkto box -->\n\t\t\t\t<script type=\"text/javascript\" language=\"javascript\">\n\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\tjQuery(\".linkto\").click(function() {\n\t\t\t\t\t\tconsole.log(\"We choose to show/hide link for rel=\"+jQuery(this).attr(\\'rel\\'));\n\t\t\t\t\t jQuery(\"#\"+jQuery(this).attr(\\'rel\\')+\"list\").toggle();\n\t\t\t\t\t\tjQuery(this).toggle();\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\t</script>\n\t\t';", "\t\treturn $linktoelem;\n\t}", "\t/**\n\t *\tReturn an html string with a select combo box to choose yes or no\n\t *\n\t *\t@param\tstring\t\t$htmlname\t\tName of html select field\n\t *\t@param\tstring\t\t$value\t\t\tPre-selected value\n\t *\t@param\tint\t\t\t$option\t\t\t0 return yes/no, 1 return 1/0\n\t *\t@param\tbool\t\t$disabled\t\ttrue or false\n\t * @param\tint \t$useempty\t\t1=Add empty line\n\t *\t@return\tstring\t\t\t\t\t\tSee option\n\t */\n\tfunction selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty='')\n\t{\n\t\tglobal $langs;", "\t\t$yes=\"yes\"; $no=\"no\";\n\t\tif ($option)\n\t\t{\n\t\t\t$yes=\"1\";\n\t\t\t$no=\"0\";\n\t\t}", "\t\t$disabled = ($disabled ? ' disabled' : '');", "\t\t$resultyesno = '<select class=\"flat\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.$disabled.'>'.\"\\n\";\n\t\tif ($useempty) $resultyesno .= '<option value=\"-1\"'.(($value < 0)?' selected':'').'>&nbsp;</option>'.\"\\n\";\n\t\tif ((\"$value\" == 'yes') || ($value == 1))\n\t\t{\n\t\t\t$resultyesno .= '<option value=\"'.$yes.'\" selected>'.$langs->trans(\"Yes\").'</option>'.\"\\n\";\n\t\t\t$resultyesno .= '<option value=\"'.$no.'\">'.$langs->trans(\"No\").'</option>'.\"\\n\";\n\t\t}\n\t\telse\n\t {\n\t \t\t$selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');\n\t\t\t$resultyesno .= '<option value=\"'.$yes.'\">'.$langs->trans(\"Yes\").'</option>'.\"\\n\";\n\t\t\t$resultyesno .= '<option value=\"'.$no.'\"'.$selected.'>'.$langs->trans(\"No\").'</option>'.\"\\n\";\n\t\t}\n\t\t$resultyesno .= '</select>'.\"\\n\";\n\t\treturn $resultyesno;\n\t}", "", "\t/**\n\t * Return list of export templates\n\t *\n\t * @param\tstring\t$selected Id modele pre-selectionne\n\t * @param string\t$htmlname Name of HTML select\n\t * @param string\t$type Type of searched templates\n\t * @param int\t\t$useempty Affiche valeur vide dans liste\n\t * @return\tvoid\n\t */\n\tfunction select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)\n\t{", "\t\t$sql = \"SELECT rowid, label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"export_model\";\n\t\t$sql.= \" WHERE type = '\".$type.\"'\";\n\t\t$sql.= \" ORDER BY rowid\";\n\t\t$result = $this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\t\tif ($useempty)\n\t\t\t{\n\t\t\t\tprint '<option value=\"-1\">&nbsp;</option>';\n\t\t\t}", "\t\t\t$num = $this->db->num_rows($result);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($result);\n\t\t\t\tif ($selected == $obj->rowid)\n\t\t\t\t{\n\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">';\n\t\t\t\t}\n\t\t\t\tprint $obj->label;\n\t\t\t\tprint '</option>';\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tprint \"</select>\";\n\t\t}\n\t\telse {\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Return a HTML area with the reference of object and a navigation bar for a business object\n\t * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.\n\t *\n\t * @param\tobject\t$object\t\t\tObject to show.\n\t * @param\tstring\t$paramid \t\tName of parameter to use to name the id into the URL next/previous link.\n\t * @param\tstring\t$morehtml \t\tMore html content to output just before the nav bar.\n\t * @param\tint\t\t$shownav\t \tShow Condition (navigation is shown if value is 1).\n\t * @param\tstring\t$fieldid \t\tName of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.\n\t * @param\tstring\t$fieldref \tName of field ref of object (object->ref) to show or 'none' to not show ref.\n\t * @param\tstring\t$morehtmlref \tMore html to show after ref.\n\t * @param\tstring\t$moreparam \tMore param to add in nav link url. Must start with '&...'.\n\t *\t @param\tint\t\t$nodbprefix\t\tDo not include DB prefix to forge table name.\n\t *\t @param\tstring\t$morehtmlleft\tMore html code to show before ref.\n\t *\t @param\tstring\t$morehtmlstatus\tMore html code to show under navigation arrows (status place).\n\t *\t @param\tstring\t$morehtmlright\tMore html code to show after ref.\n\t * \t @return\tstring \t\t\t\tPortion HTML with ref + navigation buttons\n\t */\n\tfunction showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')\n\t{\n\t\tglobal $langs,$conf,$hookmanager;", "\t\t$ret='';\n\t\tif (empty($fieldid)) $fieldid='rowid';\n\t\tif (empty($fieldref)) $fieldref='ref';", "\t\t// Add where from hooks\n\t\tif (is_object($hookmanager))\n\t\t{\n\t\t\t$parameters=array();\n\t\t\t$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object); // Note that $action and $object may have been modified by hook\n\t\t\t$object->next_prev_filter.=$hookmanager->resPrint;\n\t\t}\n\t\t$previous_ref = $next_ref = '';\n\t\tif ($shownav)\n\t\t{\n\t\t\t//print \"paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam\";\n\t\t\t$object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);", "\t\t\t$navurl = $_SERVER[\"PHP_SELF\"];\n\t\t\t// Special case for project/task page\n\t\t\tif ($paramid == 'project_ref')\n\t\t\t{\n\t\t\t\t$navurl = preg_replace('/\\/tasks\\/(task|contact|time|note|document)\\.php/','/tasks.php',$navurl);\n\t\t\t\t$paramid='ref';\n\t\t\t}", "\t\t\t// accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox\n\t\t\t// accesskey is for Mac: CTRL + key for all browsers\n\t\t\t$previous_ref = $object->ref_previous?'<a accesskey=\"p\" href=\"'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'\"><i class=\"fa fa-chevron-left\"></i></a>':'<span class=\"inactive\"><i class=\"fa fa-chevron-left opacitymedium\"></i></span>';\n\t\t\t$next_ref = $object->ref_next?'<a accesskey=\"n\" href=\"'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'\"><i class=\"fa fa-chevron-right\"></i></a>':'<span class=\"inactive\"><i class=\"fa fa-chevron-right opacitymedium\"></i></span>';\n\t\t}", "\t\t//print \"xx\".$previous_ref.\"x\".$next_ref;\n\t\t$ret.='<!-- Start banner content --><div style=\"vertical-align: middle\">';", "\t\t// Right part of banner\n\t\tif ($morehtmlright) $ret.='<div class=\"inline-block floatleft\">'.$morehtmlright.'</div>';", "\t\tif ($previous_ref || $next_ref || $morehtml)\n\t\t{\n\t\t\t$ret.='<div class=\"pagination paginationref\"><ul class=\"right\">';\n\t\t}\n\t\tif ($morehtml)\n\t\t{\n\t\t\t$ret.='<li class=\"noborder litext\">'.$morehtml.'</li>';\n\t\t}\n\t\tif ($shownav && ($previous_ref || $next_ref))\n\t\t{\n\t\t\t$ret.='<li class=\"pagination\">'.$previous_ref.'</li>';\n\t\t\t$ret.='<li class=\"pagination\">'.$next_ref.'</li>';\n\t\t}\n\t\tif ($previous_ref || $next_ref || $morehtml)\n\t\t{\n\t\t\t$ret.='</ul></div>';\n\t\t}\n\t\tif ($morehtmlstatus) $ret.='<div class=\"statusref\">'.$morehtmlstatus.'</div>';", "\t\t// Left part of banner\n\t\tif ($morehtmlleft)\n\t\t{\n\t\t\tif ($conf->browser->layout == 'phone') $ret.='<div class=\"floatleft\">'.$morehtmlleft.'</div>'; // class=\"center\" to have photo in middle\n\t\t\telse $ret.='<div class=\"inline-block floatleft\">'.$morehtmlleft.'</div>';\n\t\t}", "\t\t//if ($conf->browser->layout == 'phone') $ret.='<div class=\"clearboth\"></div>';\n\t\t$ret.='<div class=\"inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'\">';", "\t\t// For thirdparty, contact, user, member, the ref is the id, so we show something else\n\t\tif ($object->element == 'societe')\n\t\t{\n\t\t\t$ret.=dol_htmlentities($object->name);\n\t\t}\n\t\telse if ($object->element == 'member')\n\t\t{\n\t\t\t$fullname=$object->getFullName($langs);\n\t\t\tif ($object->morphy == 'mor') {\n\t\t\t\t$ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');\n\t\t\t} else {\n\t\t\t\t$ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');\n\t\t\t}\n\t\t}\n\t\telse if (in_array($object->element, array('contact', 'user', 'usergroup')))\n\t\t{\n\t\t\t$ret.=dol_htmlentities($object->getFullName($langs));\n\t\t}\n\t\telse if (in_array($object->element, array('action', 'agenda')))\n\t\t{\n\t\t\t$ret.=$object->ref.'<br>'.$object->label;\n\t\t}\n\t\telse if (in_array($object->element, array('adherent_type')))\n\t\t{\n\t\t\t$ret.=$object->label;\n\t\t}\n\t\telse if ($object->element == 'ecm_directories')\n\t\t{\n\t\t\t$ret.='';\n\t\t}\n\t\telse if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);", "\n\t\tif ($morehtmlref)\n\t\t{\n\t\t\t$ret.=' '.$morehtmlref;\n\t\t}\n\t\t$ret.='</div>';", "\t\t$ret.='</div><!-- End banner content -->';", "\t\treturn $ret;\n\t}", "\n\t/**\n\t * \tReturn HTML code to output a barcode\n\t *\n\t * \t@param\tObject\t$object\t\tObject containing data to retrieve file name\n\t * \t\t@param\tint\t\t$width\t\t\tWidth of photo\n\t * \t \t@return string \t\t\t\tHTML code to output barcode\n\t */\n\tfunction showbarcode(&$object,$width=100)\n\t{\n\t\tglobal $conf;", "\t\t//Check if barcode is filled in the card\n\t\tif (empty($object->barcode)) return '';", "\t\t// Complete object if not complete\n\t\tif (empty($object->barcode_type_code) || empty($object->barcode_type_coder))\n\t\t{\n\t\t\t$result = $object->fetch_barcode();\n\t\t\t//Check if fetch_barcode() failed\n\t\t\tif ($result < 1) return '<!-- ErrorFetchBarcode -->';\n\t\t}", "\t\t// Barcode image\n\t\t$url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);\n\t\t$out ='<!-- url barcode = '.$url.' -->';\n\t\t$out.='<img src=\"'.$url.'\">';\n\t\treturn $out;\n\t}", "\t/**\n\t * \tReturn HTML code to output a photo\n\t *\n\t * \t@param\tstring\t\t$modulepart\t\t\tKey to define module concerned ('societe', 'userphoto', 'memberphoto')\n\t * \t@param object\t\t$object\t\t\t\tObject containing data to retrieve file name\n\t * \t\t@param\tint\t\t\t$width\t\t\t\tWidth of photo\n\t * \t\t@param\tint\t\t\t$height\t\t\t\tHeight of photo (auto if 0)\n\t * \t\t@param\tint\t\t\t$caneditfield\t\tAdd edit fields\n\t * \t\t@param\tstring\t\t$cssclass\t\t\tCSS name to use on img for photo\n\t * \t\t@param\tstring\t\t$imagesize\t\t 'mini', 'small' or '' (original)\n\t * @param int $addlinktofullsize Add link to fullsize image\n\t * @param int $cache 1=Accept to use image in cache\n\t * \t \t@return string \t\t\t\t\t\tHTML code to output photo\n\t */\n\tstatic function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0)\n\t{\n\t\tglobal $conf,$langs;", "\t\t$entity = (! empty($object->entity) ? $object->entity : $conf->entity);\n\t\t$id = (! empty($object->id) ? $object->id : $object->rowid);", "\t\t$ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';\n\t\tif ($modulepart=='societe')\n\t\t{\n\t\t\t$dir=$conf->societe->multidir_output[$entity];\n\t\t\tif (! empty($object->logo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');\n\t\t\t\telse $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;\n\t\t\t\t$originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;\n\t\t\t}\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse if ($modulepart=='contact')\n\t\t{\n\t\t\t$dir=$conf->societe->multidir_output[$entity].'/contact';\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;\n\t\t\t\t$originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;\n\t\t\t}\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse if ($modulepart=='userphoto')\n\t\t{\n\t\t\t$dir=$conf->user->dir_output;\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;\n\t\t\t\t$originalfile=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;\n\t\t\t}\n\t\t\tif (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.\".jpg\";\t// For backward compatibility\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse if ($modulepart=='memberphoto')\n\t\t{\n\t\t\t$dir=$conf->adherent->dir_output;\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;\n\t\t\t\t$originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;\n\t\t\t}\n\t\t\tif (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.\".jpg\";\t// For backward compatibility\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Generic case to show photos\n\t\t\t$dir=$conf->$modulepart->dir_output;\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;\n\t\t\t\t$originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;\n\t\t\t}\n\t\t\tif (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.\".jpg\";\t// For backward compatibility\n\t\t\t$email=$object->email;\n\t\t}", "\t\tif ($dir)\n\t\t{\n\t\t\tif ($file && file_exists($dir.\"/\".$file))\n\t\t\t{\n\t\t\t\tif ($addlinktofullsize)\n\t\t\t\t{\n\t\t\t\t\t$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);\n\t\t\t\t\tif ($urladvanced) $ret.='<a href=\"'.$urladvanced.'\">';\n\t\t\t\t\telse $ret.='<a href=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'\">';\n\t\t\t\t}\n\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"Photo\" id=\"photologo'.(preg_replace('/[^a-z]/i','_',$file)).'\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'\">';\n\t\t\t\tif ($addlinktofullsize) $ret.='</a>';\n\t\t\t}\n\t\t\telse if ($altfile && file_exists($dir.\"/\".$altfile))\n\t\t\t{\n\t\t\t\tif ($addlinktofullsize)\n\t\t\t\t{\n\t\t\t\t\t$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);\n\t\t\t\t\tif ($urladvanced) $ret.='<a href=\"'.$urladvanced.'\">';\n\t\t\t\t\telse $ret.='<a href=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'\">';\n\t\t\t\t}\n\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"Photo alt\" id=\"photologo'.(preg_replace('/[^a-z]/i','_',$file)).'\" class=\"'.$cssclass.'\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'\">';\n\t\t\t\tif ($addlinktofullsize) $ret.='</a>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$nophoto='/public/theme/common/nophoto.png';\n\t\t\t\tif (in_array($modulepart,array('userphoto','contact')))\t// For module that are \"physical\" users\n\t\t\t\t{\n\t\t\t\t\t$nophoto='/public/theme/common/user_anonymous.png';\n\t\t\t\t\tif ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';\n\t\t\t\t\tif ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';\n\t\t\t\t}", "\t\t\t\tif (! empty($conf->gravatar->enabled) && $email)\n\t\t\t\t{\n\t\t\t\t\t/**\n\t\t\t\t\t * @see https://gravatar.com/site/implement/images/php/\n\t\t\t\t\t */\n\t\t\t\t\tglobal $dolibarr_main_url_root;\n\t\t\t\t\t$ret.='<!-- Put link to gravatar -->';\n\t\t\t\t\t//$defaultimg=urlencode(dol_buildpath($nophoto,3));\n\t\t\t\t\t$defaultimg='mm';\n\t\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"Gravatar avatar\" title=\"'.$email.' Gravatar avatar\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'\">';\t// gravatar need md5 hash\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"No photo\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"'.DOL_URL_ROOT.$nophoto.'\">';\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ($caneditfield)\n\t\t\t{\n\t\t\t\tif ($object->photo) $ret.=\"<br>\\n\";\n\t\t\t\t$ret.='<table class=\"nobordernopadding centpercent\">';\n\t\t\t\tif ($object->photo) $ret.='<tr><td><input type=\"checkbox\" class=\"flat photodelete\" name=\"deletephoto\" id=\"photodelete\"> '.$langs->trans(\"Delete\").'<br><br></td></tr>';\n\t\t\t\t$ret.='<tr><td class=\"tdoverflow\"><input type=\"file\" class=\"flat maxwidth200onsmartphone\" name=\"photo\" id=\"photoinput\"></td></tr>';\n\t\t\t\t$ret.='</table>';\n\t\t\t}", "\t\t}\n\t\telse dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);", "\t\treturn $ret;\n\t}", "\t/**\n\t *\tReturn select list of groups\n\t *\n\t * @param\tstring\t$selected Id group preselected\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue\n\t * @param string\t$exclude Array list of groups id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param string\t$include Array list of groups id to include\n\t * \t@param\tint\t\t$enableonly\t\tArray list of groups id to be enabled. All other must be disabled\n\t * \t@param\tstring\t$force_entity\t'0' or Ids of environment to force\n\t * @return\tstring\n\t * @see select_dolusers\n\t */\n\tfunction select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0')\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t// Permettre l'exclusion de groupes\n\t\tif (is_array($exclude))\t$excludeGroups = implode(\"','\",$exclude);\n\t\t// Permettre l'inclusion de groupes\n\t\tif (is_array($include))\t$includeGroups = implode(\"','\",$include);", "\t\t$out='';", "\t\t// On recherche les groupes\n\t\t$sql = \"SELECT ug.rowid, ug.nom as name\";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \", e.label\";\n\t\t}\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"usergroup as ug \";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"entity as e ON e.rowid=ug.entity\";\n\t\t\tif ($force_entity) $sql.= \" WHERE ug.entity IN (0,\".$force_entity.\")\";\n\t\t\telse $sql.= \" WHERE ug.entity IS NOT NULL\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$sql.= \" WHERE ug.entity IN (0,\".$conf->entity.\")\";\n\t\t}\n\t\tif (is_array($exclude) && $excludeGroups) $sql.= \" AND ug.rowid NOT IN ('\".$excludeGroups.\"')\";\n\t\tif (is_array($include) && $includeGroups) $sql.= \" AND ug.rowid IN ('\".$includeGroups.\"')\";\n\t\t$sql.= \" ORDER BY ug.nom ASC\";", "\t\tdol_syslog(get_class($this).\"::select_dolgroups\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t// Enhance with select2\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t \t$out .= ajax_combobox($htmlname);", "\t\t\t$out.= '<select class=\"flat minwidth200\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.($disabled?' disabled':'').'>';", "\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tif ($show_empty) $out.= '<option value=\"-1\"'.($selected==-1?' selected':'').'>&nbsp;</option>'.\"\\n\";", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$disableline=0;\n\t\t\t\t\tif (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;", "\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\tif ($disableline) $out.= ' disabled';\n\t\t\t\t\tif ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= ' selected';\n\t\t\t\t\t}\n\t\t\t\t\t$out.= '>';", "\t\t\t\t\t$out.= $obj->name;\n\t\t\t\t\tif (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= \" (\".$obj->label.\")\";\n\t\t\t\t\t}", "\t\t\t\t\t$out.= '</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ($show_empty) $out.= '<option value=\"-1\"'.($selected==-1?' selected':'').'></option>'.\"\\n\";\n\t\t\t\t$out.= '<option value=\"\" disabled>'.$langs->trans(\"NoUserGroupDefined\").'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn HTML to show the search and clear seach button\n\t *\n\t * @return\tstring\n\t */\n\tfunction showFilterButtons()\n\t{\n\t\tglobal $conf, $langs;", "\t\t$out='<div class=\"nowrap\">';\n\t\t$out.='<input type=\"image\" class=\"liste_titre\" name=\"button_search\" src=\"'.img_picto($langs->trans(\"Search\"),'search.png','','',1).'\" value=\"'.dol_escape_htmltag($langs->trans(\"Search\")).'\" title=\"'.dol_escape_htmltag($langs->trans(\"Search\")).'\">';\n\t\t$out.='<input type=\"image\" class=\"liste_titre\" name=\"button_removefilter\" src=\"'.img_picto($langs->trans(\"Search\"),'searchclear.png','','',1).'\" value=\"'.dol_escape_htmltag($langs->trans(\"RemoveFilter\")).'\" title=\"'.dol_escape_htmltag($langs->trans(\"RemoveFilter\")).'\">';\n\t\t$out.='</div>';", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn HTML to show the search and clear seach button\n\t *\n\t * @param string $cssclass CSS class\n\t * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes\n\t * @return\tstring\n\t */\n\tfunction showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)\n\t{\n\t\tglobal $conf, $langs;", "\t\t$out='';\n\t\tif (! empty($conf->use_javascript_ajax)) $out.='<div class=\"inline-block checkallactions\"><input type=\"checkbox\" id=\"checkallactions\" name=\"checkallactions\" class=\"checkallactions\"></div>';\n\t\t$out.='<script type=\"text/javascript\">\n $(document).ready(function() {\n \t$(\"#checkallactions\").click(function() {\n if($(this).is(\\':checked\\')){\n console.log(\"We check all\");\n \t\t$(\".'.$cssclass.'\").prop(\\'checked\\', true);\n }\n else\n {\n console.log(\"We uncheck all\");\n \t\t$(\".'.$cssclass.'\").prop(\\'checked\\', false);\n }'.\"\\n\";\n\t\tif ($calljsfunction) $out.='if (typeof initCheckForSelect == \\'function\\') { initCheckForSelect(0); } else { console.log(\"No function initCheckForSelect found. Call won\\'t be done.\"); }';\n\t\t$out.=' });\n });\n </script>';", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn HTML to show the search and clear seach button\n\t *\n\t * @param\tint \t$addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this\n\t * @param string $cssclass CSS class\n\t * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes\n\t * @return\tstring\n\t */\n\tfunction showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)\n\t{\n\t\t$out.=$this->showFilterButtons();\n\t\tif ($addcheckuncheckall)\n\t\t{\n\t\t\t$out.=$this->showCheckAddButtons($cssclass, $calljsfunction);\n\t\t}\n\t\treturn $out;\n\t}", "\t/**\n\t * Return HTML to show the select categories of expense category\n\t *\n\t * @param\tstring\t$selected preselected category\n\t * @param\tstring\t$htmlname name of HTML select list\n\t * @param\tinteger\t$useempty 1=Add empty line\n\t * @param\tarray\t$excludeid id to exclude\n\t * @param\tstring\t$target htmlname of target select to bind event\n\t * @param\tint\t\t$default_selected default category to select if fk_c_type_fees change = EX_KME\n\t * @param\tarray\t$params param to give\n\t * @return\tstring\n\t */\n\tfunction selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())\n\t{\n\t\tglobal $db, $conf, $langs, $user;", "\t\t$sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';\n\t\t$sql.= ' AND entity IN (0,'.getEntity('').')';\n\t\tif (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';\n\t\t$sql.= ' ORDER BY label';", "\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out = '<select name=\"'.$htmlname.'\" class=\"'.$htmlname.' flat minwidth75imp\">';\n\t\t\tif ($useempty) $out.= '<option value=\"0\">&nbsp;</option>';", "\t\t\twhile ($obj = $db->fetch_object($resql))\n\t\t\t{\n\t\t\t\t$out.= '<option '.($selected == $obj->rowid ? 'selected=\"selected\"' : '').' value=\"'.$obj->rowid.'\">'.$langs->trans($obj->label).'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t\tif (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);", "\t\t\tif (!empty($target))\n\t\t\t{\n\t\t\t\t$sql = \"SELECT c.id FROM \".MAIN_DB_PREFIX.\"c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1\";\n\t\t\t\t$resql = $db->query($sql);\n\t\t\t\tif ($resql)\n\t\t\t\t{\n\t\t\t\t\tif ($db->num_rows($resql) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t$obj = $db->fetch_object($resql);\n\t\t\t\t\t\t$out.= '<script type=\"text/javascript\">\n\t\t\t\t\t\t\t$(function() {\n\t\t\t\t\t\t\t\t$(\"select[name='.$target.']\").on(\"change\", function() {\n\t\t\t\t\t\t\t\t\tvar current_val = $(this).val();\n\t\t\t\t\t\t\t\t\tif (current_val == '.$obj->id.') {';\n\t\t\t\t\t\tif (!empty($default_selected) || !empty($selected)) $out.= '$(\"select[name='.$htmlname.']\").val(\"'.($default_selected > 0 ? $default_selected : $selected).'\");';", "\t\t\t\t\t\t$out.= '\n\t\t\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").change();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});", "\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").change(function() {", "\t\t\t\t\t\t\t\t\tif ($(\"select[name='.$target.']\").val() == '.$obj->id.') {\n\t\t\t\t\t\t\t\t\t\t// get price of kilometer to fill the unit price\n\t\t\t\t\t\t\t\t\t\tvar data = '.json_encode($params).';\n\t\t\t\t\t\t\t\t\t\tdata.fk_c_exp_tax_cat = $(this).val();", "\t\t\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\t\t\t\t\tdataType: \"json\",\n\t\t\t\t\t\t\t\t\t\t\tdata: data,\n\t\t\t\t\t\t\t\t\t\t\turl: \"'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php').'\",\n\t\t\t\t\t\t\t\t\t\t}).done(function( data, textStatus, jqXHR ) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(data);\n\t\t\t\t\t\t\t\t\t\t\tif (typeof data.up != \"undefined\") {\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"input[name=value_unit]\").val(data.up);\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").attr(\"title\", data.title);\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"input[name=value_unit]\").val(\"\");\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").attr(\"title\", \"\");\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t</script>';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Return HTML to show the select ranges of expense range\n\t *\n\t * @param\tstring\t$selected preselected category\n\t * @param\tstring\t$htmlname name of HTML select list\n\t * @param\tinteger\t$useempty 1=Add empty line\n\t * @return\tstring\n\t */\n\tfunction selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)\n\t{\n\t\tglobal $db,$conf,$langs;", "\t\t$sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';\n\t\t$sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';", "\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out = '<select name=\"'.$htmlname.'\" class=\"'.$htmlname.' flat minwidth75imp\">';\n\t\t\tif ($useempty) $out.= '<option value=\"0\"></option>';", "\t\t\twhile ($obj = $db->fetch_object($resql))\n\t\t\t{\n\t\t\t\t$out.= '<option '.($selected == $obj->rowid ? 'selected=\"selected\"' : '').' value=\"'.$obj->rowid.'\">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Return HTML to show a select of expense\n\t *\n\t * @param\tstring\t$selected preselected category\n\t * @param\tstring\t$htmlname name of HTML select list\n\t * @param\tinteger\t$useempty 1=Add empty choice\n\t * @param\tinteger\t$allchoice 1=Add all choice\n\t * @param\tinteger\t$useid 0=use 'code' as key, 1=use 'id' as key\n\t * @return\tstring\n\t */\n\tfunction selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)\n\t{\n\t\tglobal $db,$langs;", "\t\t$sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';\n\t\t$sql.= ' WHERE active = 1';", "\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out = '<select name=\"'.$htmlname.'\" class=\"'.$htmlname.' flat minwidth75imp\">';\n\t\t\tif ($useempty) $out.= '<option value=\"0\"></option>';\n\t\t\tif ($allchoice) $out.= '<option value=\"-1\">'.$langs->trans('AllExpenseReport').'</option>';", "\t\t\t$field = 'code';\n\t\t\tif ($useid) $field = 'id';", "\t\t\twhile ($obj = $db->fetch_object($resql))\n\t\t\t{\n\t\t\t\t$key = $langs->trans($obj->code);\n\t\t\t\t$out.= '<option '.($selected == $obj->{$field} ? 'selected=\"selected\"' : '').' value=\"'.$obj->{$field}.'\">'.($key != $obj->code ? $key : $obj->label).'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}", "\t\treturn $out;\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>\n * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>\n * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>\n * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>\n * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>\n * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@capnetworks.com>\n * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>\n * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>\n * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>\n * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>\n * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>\n * Copyright (C) 2010-2014 Philippe Grand <philippe.grand@atoo-net.com>\n * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>\n * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>\n * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>\n * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>\n * Copyright (C) 2014 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n *\t\\file htdocs/core/class/html.form.class.php\n * \\ingroup core\n *\t\\brief File of class with all html predefined components\n */", "\n/**\n *\tClass to manage generation of HTML components\n *\tOnly common components must be here.\n *\n * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable\n */\nclass Form\n{\n\tvar $db;\n\tvar $error;\n\tvar $num;", "\t// Cache arrays\n\tvar $cache_types_paiements=array();\n\tvar $cache_conditions_paiements=array();\n\tvar $cache_availability=array();\n\tvar $cache_demand_reason=array();\n\tvar $cache_types_fees=array();\n\tvar $cache_vatrates=array();", "\n\t/**\n\t * Constructor\n\t *\n\t * @param\t\tDoliDB\t\t$db Database handler\n\t */\n\tpublic function __construct($db)\n\t{\n\t\t$this->db = $db;\n\t}", "\t/**\n\t * Output key field for an editable field\n\t *\n\t * @param string\t$text\t\t\tText of label or key to translate\n\t * @param string\t$htmlname\t\tName of select field ('edit' prefix will be added)\n\t * @param string\t$preselected Value to show/edit (not used in this function)\n\t * @param\tobject\t$object\t\t\tObject\n\t * @param\tboolean\t$perm\t\t\tPermission to allow button to edit parameter. Set it to 0 to have a not edited field.\n\t * @param\tstring\t$typeofdata\t\tType of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)\n\t * @param\tstring\t$moreparam\t\tMore param to add on a href URL.\n\t * @param int $fieldrequired 1 if we want to show field as mandatory using the \"fieldrequired\" CSS.\n\t * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '\n\t * @return\tstring\t\t\t\t\tHTML edit field\n\t */\n\tfunction editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0)\n\t{\n\t\tglobal $conf,$langs;", "\t\t$ret='';", "\t\t// TODO change for compatibility\n\t\tif (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))\n\t\t{\n\t\t\tif (! empty($perm))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t$ret.= '<div class=\"editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'\" id=\"'.$htmlname.'\">';\n\t\t\t\tif ($fieldrequired) $ret.='<span class=\"fieldrequired\">';\n\t\t\t\t$ret.= $langs->trans($text);\n\t\t\t\tif ($fieldrequired) $ret.='</span>';\n\t\t\t\t$ret.= '</div>'.\"\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ($fieldrequired) $ret.='<span class=\"fieldrequired\">';\n\t\t\t\t$ret.= $langs->trans($text);\n\t\t\t\tif ($fieldrequired) $ret.='</span>';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class=\"nobordernopadding\" width=\"100%\"><tr><td class=\"nowrap\">';\n\t\t\tif ($fieldrequired) $ret.='<span class=\"fieldrequired\">';\n\t\t\t$ret.=$langs->trans($text);\n\t\t\tif ($fieldrequired) $ret.='</span>';\n\t\t\tif (! empty($notabletag)) $ret.=' ';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align=\"right\">';\n\t\t\tif ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href=\"'.$_SERVER[\"PHP_SELF\"].'?action=edit'.$htmlname.'&amp;id='.$object->id.$moreparam.'\">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';\n\t\t\tif (! empty($notabletag) && $notabletag == 1) $ret.=' : ';\n\t\t\tif (! empty($notabletag) && $notabletag == 3) $ret.=' ';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';\n\t\t\tif (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';\n\t\t}", "\t\treturn $ret;\n\t}", "\t/**\n\t * Output value of a field for an editable field\n\t *\n\t * @param\tstring\t$text\t\t\tText of label (not used in this function)\n\t * @param\tstring\t$htmlname\t\tName of select field\n\t * @param\tstring\t$value\t\t\tValue to show/edit\n\t * @param\tobject\t$object\t\t\tObject\n\t * @param\tboolean\t$perm\t\t\tPermission to allow button to edit parameter\n\t * @param\tstring\t$typeofdata\t\tType of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)\n\t * @param\tstring\t$editvalue\t\tWhen in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value\n\t * @param\tobject\t$extObject\t\tExternal object\n\t * @param\tmixed\t$custommsg\t\tString or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')\n\t * @param\tstring\t$moreparam\t\tMore param to add on a href URL\n\t * @param int $notabletag Do no output table tags\n\t * @param\tstring\t$formatfunc\t\tCall a specific function to output field\n\t * @return string\t\t\t\t\tHTML edit field\n\t */\n\tfunction editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='')\n\t{\n\t\tglobal $conf,$langs,$db;", "\t\t$ret='';", "\t\t// Check parameters\n\t\tif (empty($typeofdata)) return 'ErrorBadParameter';", "\t\t// When option to edit inline is activated\n\t\tif (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker\n\t\t{\n\t\t\t$ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (GETPOST('action','aZ09') == 'edit'.$htmlname)\n\t\t\t{\n\t\t\t\t$ret.=\"\\n\";\n\t\t\t\t$ret.='<form method=\"post\" action=\"'.$_SERVER[\"PHP_SELF\"].($moreparam?'?'.$moreparam:'').'\">';\n\t\t\t\t$ret.='<input type=\"hidden\" name=\"action\" value=\"set'.$htmlname.'\">';\n\t\t\t\t$ret.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t\t$ret.='<input type=\"hidden\" name=\"id\" value=\"'.$object->id.'\">';\n\t\t\t\tif (empty($notabletag)) $ret.='<table class=\"nobordernopadding\" cellpadding=\"0\" cellspacing=\"0\">';\n\t\t\t\tif (empty($notabletag)) $ret.='<tr><td>';\n\t\t\t\tif (preg_match('/^(string|email)/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t\t$ret.='<input type=\"text\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" value=\"'.($editvalue?$editvalue:$value).'\"'.($tmp[1]?' size=\"'.$tmp[1].'\"':'').'>';\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^(numeric|amount)/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t\t$valuetoshow=price2num($editvalue?$editvalue:$value);\n\t\t\t\t\t$ret.='<input type=\"text\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" value=\"'.($valuetoshow!=''?price($valuetoshow):'').'\"'.($tmp[1]?' size=\"'.$tmp[1].'\"':'').'>';\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\n\t\t\t\t\t$cols=$tmp[2];\n\t\t\t\t\t$morealt='';\n\t\t\t\t\tif (preg_match('/%/',$cols))\n\t\t\t\t\t{\n\t\t\t\t\t\t$morealt=' style=\"width: '.$cols.'\"';\n\t\t\t\t\t\t$cols='';\n\t\t\t\t\t}\n\t\t\t\t\t$ret.='<textarea id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" wrap=\"soft\" rows=\"'.($tmp[1]?$tmp[1]:'20').'\"'.($cols?' cols=\"'.$cols.'\"':'class=\"quatrevingtpercent\"').$morealt.'\">'.($editvalue?$editvalue:$value).'</textarea>';\n\t\t\t\t}\n\t\t\t\telse if ($typeofdata == 'day' || $typeofdata == 'datepicker')\n\t\t\t\t{\n\t\t\t\t\t$ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1);\n\t\t\t\t}\n\t\t\t\telse if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')\n\t\t\t\t{\n\t\t\t\t\t$ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1);\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^select;/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));\n\t\t\t\t\t foreach($arraydata as $val)\n\t\t\t\t\t {\n\t\t\t\t\t\t $tmp=explode(':',$val);\n\t\t\t\t\t\t $arraylist[$tmp[0]]=$tmp[1];\n\t\t\t\t\t }\n\t\t\t\t\t $ret.=$this->selectarray($htmlname,$arraylist,$value);\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^ckeditor/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmp=explode(':',$typeofdata);\t\t// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols\n\t\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';\n\t\t\t\t\t$doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));\n\t\t\t\t\t$ret.=$doleditor->Create(1);\n\t\t\t\t}\n\t\t\t\tif (empty($notabletag)) $ret.='</td>';", "\t\t\t\tif (empty($notabletag)) $ret.='<td align=\"left\">';\n\t\t\t\t//else $ret.='<div class=\"clearboth\"></div>';\n\t\t\t \t$ret.='<input type=\"submit\" class=\"button'.(empty($notabletag)?'':' ').'\" name=\"modify\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\t \tif (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'.\"\\n\";\n\t\t\t \t$ret.='<input type=\"submit\" class=\"button'.(empty($notabletag)?'':' ').'\" name=\"cancel\" value=\"'.$langs->trans(\"Cancel\").'\">';\n\t\t\t \tif (empty($notabletag)) $ret.='</td>';", "\t\t\t \tif (empty($notabletag)) $ret.='</tr></table>'.\"\\n\";\n\t\t\t\t$ret.='</form>'.\"\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1);\n\t\t\t\telseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');\n\t\t\t\telseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value);\n\t\t\t\telseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');\n\t\t\t\telseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');\n\t\t\t\telse if (preg_match('/^select;/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));\n\t\t\t\t\tforeach($arraydata as $val)\n\t\t\t\t\t{\n\t\t\t\t\t\t$tmp=explode(':',$val);\n\t\t\t\t\t\t$arraylist[$tmp[0]]=$tmp[1];\n\t\t\t\t\t}\n\t\t\t\t\t$ret.=$arraylist[$value];\n\t\t\t\t}\n\t\t\t\telse if (preg_match('/^ckeditor/',$typeofdata))\n\t\t\t\t{\n\t\t\t\t\t$tmpcontent=dol_htmlentitiesbr($value);\n\t\t\t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n\t\t\t\t\t{\n\t\t\t\t\t\t$firstline=preg_replace('/<br>.*/','',$tmpcontent);\n\t\t\t\t\t\t$firstline=preg_replace('/[\\n\\r].*/','',$firstline);\n\t\t\t\t\t\t$tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');\n\t\t\t\t\t}\n\t\t\t\t\t$ret.=$tmpcontent;\n\t\t\t\t}\n\t\t\t\telse $ret.=$value;", "\t\t\t\tif ($formatfunc && method_exists($object, $formatfunc))\n\t\t\t\t{\n\t\t\t\t\t$ret=$object->$formatfunc($ret);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn $ret;\n\t}", "\t/**\n\t * Output edit in place form\n\t *\n\t * @param\tobject\t$object\t\t\tObject\n\t * @param\tstring\t$value\t\t\tValue to show/edit\n\t * @param\tstring\t$htmlname\t\tDIV ID (field name)\n\t * @param\tint\t\t$condition\t\tCondition to edit\n\t * @param\tstring\t$inputType\t\tType of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')\n\t * @param\tstring\t$editvalue\t\tWhen in edit mode, use this value as $value instead of value\n\t * @param\tobject\t$extObject\t\tExternal object\n\t * @param\tmixed\t$custommsg\t\tString or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')\n\t * @return\tstring \t\t \tHTML edit in place\n\t */\n\tprivate function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)\n\t{\n\t\tglobal $conf;", "\t\t$out='';", "\t\t// Check parameters\n\t\tif ($inputType == 'textarea') $value = dol_nl2br($value);\n\t\telse if (preg_match('/^numeric/',$inputType)) $value = price($value);\n\t\telse if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');", "\t\tif ($condition)\n\t\t{\n\t\t\t$element\t\t= false;\n\t\t\t$table_element\t= false;\n\t\t\t$fk_element\t\t= false;\n\t\t\t$loadmethod\t\t= false;\n\t\t\t$savemethod\t\t= false;\n\t\t\t$ext_element\t= false;\n\t\t\t$button_only\t= false;\n\t\t\t$inputOption = '';", "\t\t\tif (is_object($object))\n\t\t\t{\n\t\t\t\t$element = $object->element;\n\t\t\t\t$table_element = $object->table_element;\n\t\t\t\t$fk_element = $object->id;\n\t\t\t}", "\t\t\tif (is_object($extObject))\n\t\t\t{\n\t\t\t\t$ext_element = $extObject->element;\n\t\t\t}", "\t\t\tif (preg_match('/^(string|email|numeric)/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0];\n\t\t\t\tif (! empty($tmp[1])) $inputOption=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $savemethod=$tmp[2];\n\t\t\t\t$out.= '<input id=\"width_'.$htmlname.'\" value=\"'.$inputOption.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t}\n\t\t\telse if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0];\n\t\t\t\tif (! empty($tmp[1])) $inputOption=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $savemethod=$tmp[2];", "\t\t\t\t$out.= '<input id=\"timestamp\" type=\"hidden\"/>'.\"\\n\"; // Use for timestamp format\n\t\t\t}\n\t\t\telse if (preg_match('/^(select|autocomplete)/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0]; $loadmethod=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $savemethod=$tmp[2];\n\t\t\t\tif (! empty($tmp[3])) $button_only=true;\n\t\t\t}\n\t\t\telse if (preg_match('/^textarea/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0];\n\t\t\t\t$rows=(empty($tmp[1])?'8':$tmp[1]);\n\t\t\t\t$cols=(empty($tmp[2])?'80':$tmp[2]);\n\t\t\t}\n\t\t\telse if (preg_match('/^ckeditor/',$inputType))\n\t\t\t{\n\t\t\t\t$tmp=explode(':',$inputType);\n\t\t\t\t$inputType=$tmp[0]; $toolbar=$tmp[1];\n\t\t\t\tif (! empty($tmp[2])) $width=$tmp[2];\n\t\t\t\tif (! empty($tmp[3])) $heigth=$tmp[3];\n\t\t\t\tif (! empty($tmp[4])) $savemethod=$tmp[4];", "\t\t\t\tif (! empty($conf->fckeditor->enabled))\n\t\t\t\t{\n\t\t\t\t\t$out.= '<input id=\"ckeditor_toolbar\" value=\"'.$toolbar.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$inputType = 'textarea';\n\t\t\t\t}\n\t\t\t}", "\t\t\t$out.= '<input id=\"element_'.$htmlname.'\" value=\"'.$element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t$out.= '<input id=\"table_element_'.$htmlname.'\" value=\"'.$table_element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t$out.= '<input id=\"fk_element_'.$htmlname.'\" value=\"'.$fk_element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t$out.= '<input id=\"loadmethod_'.$htmlname.'\" value=\"'.$loadmethod.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\tif (! empty($savemethod))\t$out.= '<input id=\"savemethod_'.$htmlname.'\" value=\"'.$savemethod.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\tif (! empty($ext_element))\t$out.= '<input id=\"ext_element_'.$htmlname.'\" value=\"'.$ext_element.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\tif (! empty($custommsg))\n\t\t\t{\n\t\t\t\tif (is_array($custommsg))\n\t\t\t\t{\n\t\t\t\t\tif (!empty($custommsg['success']))\n\t\t\t\t\t\t$out.= '<input id=\"successmsg_'.$htmlname.'\" value=\"'.$custommsg['success'].'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t\tif (!empty($custommsg['error']))\n\t\t\t\t\t\t$out.= '<input id=\"errormsg_'.$htmlname.'\" value=\"'.$custommsg['error'].'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t$out.= '<input id=\"successmsg_'.$htmlname.'\" value=\"'.$custommsg.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t}\n\t\t\tif ($inputType == 'textarea') {\n\t\t\t\t$out.= '<input id=\"textarea_'.$htmlname.'_rows\" value=\"'.$rows.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t\t$out.= '<input id=\"textarea_'.$htmlname.'_cols\" value=\"'.$cols.'\" type=\"hidden\"/>'.\"\\n\";\n\t\t\t}\n\t\t\t$out.= '<span id=\"viewval_'.$htmlname.'\" class=\"viewval_'.$inputType.($button_only ? ' inactive' : ' active').'\">'.$value.'</span>'.\"\\n\";\n\t\t\t$out.= '<span id=\"editval_'.$htmlname.'\" class=\"editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject\">'.(! empty($editvalue) ? $editvalue : $value).'</span>'.\"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$out = $value;\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t *\tShow a text and picto with tooltip on text or picto.\n\t * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip\n\t *\n\t *\t@param\tstring\t\t$text\t\t\t\tText to show\n\t *\t@param\tstring\t\t$htmltext\t\t\tHTML content of tooltip. Must be HTML/UTF8 encoded.\n\t *\t@param\tint\t\t\t$tooltipon\t\t\t1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2\n\t *\t@param\tint\t\t\t$direction\t\t\t-1=image is before, 0=no image, 1=image is after\n\t *\t@param\tstring\t\t$img\t\t\t\tHtml code for image (use img_xxx() function to get it)\n\t *\t@param\tstring\t\t$extracss\t\t\tAdd a CSS style to td tags\n\t *\t@param\tint\t\t\t$notabs\t\t\t\t0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span\n\t *\t@param\tstring\t\t$incbefore\t\t\tInclude code before the text\n\t *\t@param\tint\t\t\t$noencodehtmltext\tDo not encode into html entity the htmltext\n\t * @param string $tooltiptrigger\t\t''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)\n\t * @param\tint\t\t\t$forcenowrap\t\tForce no wrap between text and picto (works with notabs=2 only)\n\t *\t@return\tstring\t\t\t\t\t\t\tCode html du tooltip (texte+picto)\n\t *\t@see\tUse function textwithpicto if you can.\n\t * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip\n\t */\n\tfunction textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)\n\t{\n\t\tglobal $conf;", "\t\tif ($incbefore) $text = $incbefore.$text;\n\t\tif (! $htmltext) return $text;", "\t\t$tag='td';\n\t\tif ($notabs == 2) $tag='div';\n\t\tif ($notabs == 3) $tag='span';\n\t\t// Sanitize tooltip\n\t\t$htmltext=str_replace(\"\\\\\",\"\\\\\\\\\",$htmltext);\n\t\t$htmltext=str_replace(\"\\r\",\"\",$htmltext);\n\t\t$htmltext=str_replace(\"\\n\",\"\",$htmltext);", "\t\t$extrastyle='';\n\t\tif ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }\n\t\tif ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }", "\t\t$classfortooltip='classfortooltip';", "\t\t$s='';$textfordialog='';", "\t\tif ($tooltiptrigger == '')\n\t\t{\n\t\t\t$htmltext=str_replace('\"',\"&quot;\",$htmltext);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$classfortooltip='classfortooltiponclick';\n\t\t\t$textfordialog.='<div style=\"display: none;\" id=\"idfortooltiponclick_'.$tooltiptrigger.'\" class=\"classfortooltiponclicktext\">'.$htmltext.'</div>';\n\t\t}\n\t\tif ($tooltipon == 2 || $tooltipon == 3)\n\t\t{\n\t\t\t$paramfortooltipimg=' class=\"'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'\" style=\"padding: 0px;'.($extrastyle?' '.$extrastyle:'').'\"';\n\t\t\tif ($tooltiptrigger == '') $paramfortooltipimg.=' title=\"'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'\"'; // Attribut to put on img tag to store tooltip\n\t\t\telse $paramfortooltipimg.=' dolid=\"'.$tooltiptrigger.'\"';\n\t\t}\n\t\telse $paramfortooltipimg =($extracss?' class=\"'.$extracss.'\"':'').($extrastyle?' style=\"'.$extrastyle.'\"':''); // Attribut to put on td text tag\n\t\tif ($tooltipon == 1 || $tooltipon == 3)\n\t\t{\n\t\t\t$paramfortooltiptd=' class=\"'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'\" style=\"padding: 0px;'.($extrastyle?' '.$extrastyle:'').'\" ';\n\t\t\tif ($tooltiptrigger == '') $paramfortooltiptd.=' title=\"'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'\"'; // Attribut to put on td tag to store tooltip\n\t\t\telse $paramfortooltiptd.=' dolid=\"'.$tooltiptrigger.'\"';\n\t\t}\n\t\telse $paramfortooltiptd =($extracss?' class=\"'.$extracss.'\"':'').($extrastyle?' style=\"'.$extrastyle.'\"':''); // Attribut to put on td text tag\n\t\tif (empty($notabs)) $s.='<table class=\"nobordernopadding\" summary=\"\"><tr style=\"height: auto;\">';\n\t\telseif ($notabs == 2) $s.='<div class=\"inline-block'.($forcenowrap?' nowrap':'').'\">';\n\t\t// Define value if value is before\n\t\tif ($direction < 0) {\n\t\t\t$s.='<'.$tag.$paramfortooltipimg;\n\t\t\tif ($tag == 'td') {\n\t\t\t\t$s .= ' valign=\"top\" width=\"14\"';\n\t\t\t}\n\t\t\t$s.= '>'.$textfordialog.$img.'</'.$tag.'>';\n\t\t}\n\t\t// Use another method to help avoid having a space in value in order to use this value with jquery\n\t\t// Define label\n\t\tif ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';\n\t\t// Define value if value is after\n\t\tif ($direction > 0) {\n\t\t\t$s.='<'.$tag.$paramfortooltipimg;\n\t\t\tif ($tag == 'td') $s .= ' valign=\"middle\" width=\"14\"';\n\t\t\t$s.= '>'.$textfordialog.$img.'</'.$tag.'>';\n\t\t}\n\t\tif (empty($notabs)) $s.='</tr></table>';\n\t\telseif ($notabs == 2) $s.='</div>';", "\t\treturn $s;\n\t}", "\t/**\n\t *\tShow a text with a picto and a tooltip on picto\n\t *\n\t *\t@param\tstring\t$text\t\t\t\tText to show\n\t *\t@param string\t$htmltext\t \tContent of tooltip\n\t *\t@param\tint\t\t$direction\t\t\t1=Icon is after text, -1=Icon is before text, 0=no icon\n\t * \t@param\tstring\t$type\t\t\t\tType of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath\n\t * @param string\t$extracss Add a CSS style to td, div or span tag\n\t * @param int\t\t$noencodehtmltext Do not encode into html entity the htmltext\n\t * @param\tint\t\t$notabs\t\t\t\t0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span\n\t * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)\n\t * @param\tint\t\t$forcenowrap\t\tForce no wrap between text and picto (works with notabs=2 only)\n\t * \t@return\tstring\t\t\t\t\t\tHTML code of text, picto, tooltip\n\t */\n\tfunction textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)\n\t{\n\t\tglobal $conf, $langs;", "\t\t$alt = '';\n\t\tif ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv(\"ClickToShowHelp\");", "\t\t//For backwards compatibility\n\t\tif ($type == '0') $type = 'info';\n\t\telseif ($type == '1') $type = 'help';", "\t\t// If info or help with no javascript, show only text\n\t\tif (empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\tif ($type == 'info' || $type == 'help')\treturn $text;\n\t\t\telse\n\t\t\t{\n\t\t\t\t$alt = $htmltext;\n\t\t\t\t$htmltext = '';\n\t\t\t}\n\t\t}", "\t\t// If info or help with smartphone, show only text (tooltip hover can't works)\n\t\tif (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))\n\t\t{\n\t\t\tif ($type == 'info' || $type == 'help') return $text;\n\t\t}\n\t\t// If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)\n\t\tif (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))\n\t\t{\n\t\t\tif ($type == 'info' || $type == 'help') return $text;\n\t\t}", "\t\tif ($type == 'info') $img = img_help(0, $alt);\n\t\telseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);\n\t\telseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');\n\t\telseif ($type == 'admin') $img = img_picto($alt, 'star');\n\t\telseif ($type == 'warning') $img = img_warning($alt);\n\t\telse $img = img_picto($alt, $type);", "\t\treturn $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);\n\t}", "\t/**\n\t * Generate select HTML to choose massaction\n\t *\n\t * @param\tstring\t$selected\t\tValue auto selected when at least one record is selected. Not a preselected value. Use '0' by default.\n\t * @param\tint\t\t$arrayofaction\tarray('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.\n\t * @param int $alwaysvisible 1=select button always visible\n\t * @return\tstring\t\t\t\t\tSelect list\n\t */\n\tfunction selectMassAction($selected, $arrayofaction, $alwaysvisible=0)\n\t{\n\t\tglobal $conf,$langs,$hookmanager;", "\t\tif (count($arrayofaction) == 0) return;", "\t\t$disabled=0;\n\t\t$ret='<div class=\"centpercent center\">';\n\t\t$ret.='<select class=\"flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect\" name=\"massaction\"'.($disabled?' disabled=\"disabled\"':'').'>';", "\t\t// Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters); // Note that $action and $object may have been modified by hook\n\t\tif (empty($reshook))\n\t\t{\n\t\t\t$ret.='<option value=\"0\"'.($disabled?' disabled=\"disabled\"':'').'>-- '.$langs->trans(\"SelectAction\").' --</option>';\n\t\t\tforeach($arrayofaction as $code => $label)\n\t\t\t{\n\t\t\t\t$ret.='<option value=\"'.$code.'\"'.($disabled?' disabled=\"disabled\"':'').'>'.$label.'</option>';\n\t\t\t}\n\t\t}\n\t\t$ret.=$hookmanager->resPrint;", "\t\t$ret.='</select>';\n\t\t// Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button\n\t\t$ret.='<input type=\"submit\" name=\"confirmmassactioninvisible\" style=\"display: none\" tabindex=\"-1\">';\t// Hidden button BEFORE so it is the one used when we submit with ENTER.\n\t\t$ret.='<input type=\"submit\" disabled name=\"confirmmassaction\" class=\"button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed\" value=\"'.dol_escape_htmltag($langs->trans(\"Confirm\")).'\">';\n\t\t$ret.='</div>';", "\t\tif (! empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\t$ret.='<!-- JS CODE TO ENABLE mass action select -->\n \t\t<script type=\"text/javascript\">\n \t\tfunction initCheckForSelect(mode)\t/* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */\n \t\t{\n \t\t\tatleastoneselected=0;\n \t \t\tjQuery(\".checkforselect\").each(function( index ) {\n \t \t\t\t\t/* console.log( index + \": \" + $( this ).text() ); */\n \t \t\t\t\tif ($(this).is(\\':checked\\')) atleastoneselected++;\n \t \t\t\t});\n\t\t\t\t\tconsole.log(\"initCheckForSelect mode=\"+mode+\" atleastoneselected=\"+atleastoneselected);\n \t \t\t\tif (atleastoneselected || '.$alwaysvisible.')\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massaction\").show();\n \t\t\t '.($selected ? 'if (atleastoneselected) { jQuery(\".massactionselect\").val(\"'.$selected.'\"); jQuery(\".massactionconfirmed\").prop(\\'disabled\\', false); }' : '').'\n \t\t\t '.($selected ? 'if (! atleastoneselected) { jQuery(\".massactionselect\").val(\"0\"); jQuery(\".massactionconfirmed\").prop(\\'disabled\\', true); } ' : '').'\n \t \t\t\t}\n \t \t\t\telse\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massaction\").hide();\n \t }\n \t\t}", " \tjQuery(document).ready(function () {\n \t\tinitCheckForSelect(0);\n \t\tjQuery(\".checkforselect\").click(function() {\n \t\t\tinitCheckForSelect(1);\n \t \t\t});\n \t \t\tjQuery(\".massactionselect\").change(function() {\n \t\t\tvar massaction = $( this ).val();\n \t\t\tvar urlform = $( this ).closest(\"form\").attr(\"action\").replace(\"#show_files\",\"\");\n \t\t\tif (massaction == \"builddoc\")\n {\n urlform = urlform + \"#show_files\";\n \t }\n \t\t\t$( this ).closest(\"form\").attr(\"action\", urlform);\n console.log(\"we select a mass action \"+massaction+\" - \"+urlform);\n \t /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */\n \t\t\tif ($(this).val() != \\'0\\')\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massactionconfirmed\").prop(\\'disabled\\', false);\n \t \t\t\t}\n \t \t\t\telse\n \t \t\t\t{\n \t \t\t\t\tjQuery(\".massactionconfirmed\").prop(\\'disabled\\', true);\n \t \t\t\t}\n \t });\n \t});\n \t\t</script>\n \t';\n\t\t}", "\t\treturn $ret;\n\t}", "\t/**\n\t * Return combo list of activated countries, into language of user\n\t *\n\t * @param\tstring\t$selected Id or Code or Label of preselected country\n\t * @param string\t$htmlname Name of html select object\n\t * @param string\t$htmloption Options html on select object\n\t * @param\tinteger\t$maxlength\t\tMax length for labels (0=no limit)\n\t * @param\tstring\t$morecss\t\tMore css class\n\t * @param\tstring\t$usecodeaskey\t'code3'=Use code on 3 alpha as key, 'code2\"=Use code on 2 alpha as key\n\t * @return string \t\tHTML string with select\n\t */\n\tfunction select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300',$usecodeaskey='')\n\t{\n\t\tglobal $conf,$langs;", "\t\t$langs->load(\"dict\");", "\t\t$out='';\n\t\t$countryArray=array();\n\t\t$favorite=array();\n\t\t$label=array();\n\t\t$atleastonefavorite=0;", "\t\t$sql = \"SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_country\";\n\t\t$sql.= \" WHERE active > 0\";\n\t\t//$sql.= \" ORDER BY code ASC\";", "\t\tdol_syslog(get_class($this).\"::select_country\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out.= '<select id=\"select'.$htmlname.'\" class=\"flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\" '.$htmloption.'>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\t$foundselected=false;", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$countryArray[$i]['rowid'] \t\t= $obj->rowid;\n\t\t\t\t\t$countryArray[$i]['code_iso'] \t= $obj->code_iso;\n\t\t\t\t\t$countryArray[$i]['code_iso3'] \t= $obj->code_iso3;\n\t\t\t\t\t$countryArray[$i]['label']\t\t= ($obj->code_iso && $langs->transnoentitiesnoconv(\"Country\".$obj->code_iso)!=\"Country\".$obj->code_iso?$langs->transnoentitiesnoconv(\"Country\".$obj->code_iso):($obj->label!='-'?$obj->label:''));\n\t\t\t\t\t$countryArray[$i]['favorite'] = $obj->favorite;\n\t\t\t\t\t$favorite[$i]\t\t\t\t\t= $obj->favorite;\n\t\t\t\t\t$label[$i] = dol_string_unaccent($countryArray[$i]['label']);\n\t\t\t\t\t$i++;\n\t\t\t\t}", "\t\t\t\tarray_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);", "\t\t\t\tforeach ($countryArray as $row)\n\t\t\t\t{\n\t\t\t\t\tif ($row['favorite'] && $row['code_iso']) $atleastonefavorite++;\n\t\t\t\t\tif (empty($row['favorite']) && $atleastonefavorite)\n\t\t\t\t\t{\n\t\t\t\t\t\t$atleastonefavorite=0;\n\t\t\t\t\t\t$out.= '<option a value=\"\" disabled class=\"selectoptiondisabledwhite\">----------------------</option>';\n\t\t\t\t\t}\n\t\t\t\t\tif ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )\n\t\t\t\t\t{\n\t\t\t\t\t\t$foundselected=true;\n\t\t\t\t\t\t$out.= '<option b value=\"'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'\" selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option c value=\"'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'\">';\n\t\t\t\t\t}\n\t\t\t\t\tif ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');\n\t\t\t\t\telse $out.= '&nbsp;';\n\t\t\t\t\tif ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';\n\t\t\t\t\t$out.= '</option>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\t// Make select dynamic\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t$out .= ajax_combobox('select'.$htmlname);", "\t\treturn $out;\n\t}", "\t/**\n\t * Return select list of incoterms\n\t *\n\t * @param\tstring\t$selected \t\tId or Code of preselected incoterm\n\t * @param\tstring\t$location_incoterms Value of input location\n\t * @param\tstring\t$page \t\t\tDefined the form action\n\t * @param string\t$htmlname \t\tName of html select object\n\t * @param string\t$htmloption \t\tOptions html on select object\n\t * \t@param\tint\t\t$forcecombo\t\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @param\tarray\t$events\t\t\t\t\tEvent options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @return string \t\t\t\tHTML string with select and input\n\t */\n\tfunction select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())\n\t{\n\t\tglobal $conf,$langs;", "\t\t$langs->load(\"dict\");", "\t\t$out='';\n\t\t$incotermArray=array();", "\t\t$sql = \"SELECT rowid, code\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_incoterms\";\n\t\t$sql.= \" WHERE active > 0\";\n\t\t$sql.= \" ORDER BY code ASC\";", "\t\tdol_syslog(get_class($this).\"::select_incoterm\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tif ($conf->use_javascript_ajax && ! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, $events);\n\t\t\t}", "\t\t\tif (!empty($page))\n\t\t\t{\n\t\t\t\t$out .= '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\t\t$out .= '<input type=\"hidden\" name=\"action\" value=\"set_incoterms\">';\n\t\t\t\t$out .= '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t}", "\t\t\t$out.= '<select id=\"'.$htmlname.'\" class=\"flat selectincoterm minwidth100imp noenlargeonsmartphone\" name=\"'.$htmlname.'\" '.$htmloption.'>';\n\t\t\t$out.= '<option value=\"0\">&nbsp;</option>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\t$foundselected=false;", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$incotermArray[$i]['rowid'] = $obj->rowid;\n\t\t\t\t\t$incotermArray[$i]['code'] = $obj->code;\n\t\t\t\t\t$i++;\n\t\t\t\t}", "\t\t\t\tforeach ($incotermArray as $row)\n\t\t\t\t{\n\t\t\t\t\tif ($selected && ($selected == $row['rowid'] || $selected == $row['code']))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$row['rowid'].'\" selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$row['rowid'].'\">';\n\t\t\t\t\t}", "\t\t\t\t\tif ($row['code']) $out.= $row['code'];", "\t\t\t\t\t$out.= '</option>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '</select>';", "\t\t\t$out .= '<input id=\"location_incoterms\" class=\"maxwidth100onsmartphone\" name=\"location_incoterms\" value=\"'.$location_incoterms.'\">';", "\t\t\tif (!empty($page))\n\t\t\t{\n\t\t\t\t$out .= '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\"></form>';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn list of types of lines (product or service)\n\t * \tExample: 0=product, 1=service, 9=other (for external module)\n\t *\n\t *\t@param string\t$selected Preselected type\n\t *\t@param string\t$htmlname Name of field in html form\n\t * \t@param\tint\t\t$showempty\t\tAdd an empty field\n\t * \t@param\tint\t\t$hidetext\t\tDo not show label 'Type' before combo box (used only if there is at least 2 choices to select)\n\t * \t@param\tinteger\t$forceall\t\t1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service')\n\t * @return\tvoid\n\t */\n\tfunction select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)\n\t{\n\t\tglobal $db,$langs,$user,$conf;", "\t\t// If product & services are enabled or both disabled.\n\t\tif ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))\n\t\t|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )\n\t\t{\n\t\t\tif (empty($hidetext)) print $langs->trans(\"Type\").': ';\n\t\t\tprint '<select class=\"flat\" id=\"select_'.$htmlname.'\" name=\"'.$htmlname.'\">';\n\t\t\tif ($showempty)\n\t\t\t{\n\t\t\t\tprint '<option value=\"-1\"';\n\t\t\t\tif ($selected == -1) print ' selected';\n\t\t\t\tprint '>&nbsp;</option>';\n\t\t\t}", "\t\t\tprint '<option value=\"0\"';\n\t\t\tif (0 == $selected) print ' selected';\n\t\t\tprint '>'.$langs->trans(\"Product\");", "\t\t\tprint '<option value=\"1\"';\n\t\t\tif (1 == $selected) print ' selected';\n\t\t\tprint '>'.$langs->trans(\"Service\");", "\t\t\tprint '</select>';\n\t\t\t//if ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t\t}\n\t\tif (empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled))\n\t\t{\n\t\t\tprint $langs->trans(\"Service\");\n\t\t\tprint '<input type=\"hidden\" name=\"'.$htmlname.'\" value=\"1\">';\n\t\t}\n\t\tif (empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled))\n\t\t{\n\t\t\tprint $langs->trans(\"Product\");\n\t\t\tprint '<input type=\"hidden\" name=\"'.$htmlname.'\" value=\"0\">';\n\t\t}\n\t\tif ($forceall < 0)\t// This should happened only for contracts when both predefined product and service are disabled.\n\t\t{\n\t\t\tprint '<input type=\"hidden\" name=\"'.$htmlname.'\" value=\"1\">';\t// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1\n\t\t}\n\t}", "\t/**\n\t *\tLoad into cache cache_types_fees, array of types of fees\n\t *\n\t *\t@return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_types_fees()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_types_fees);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$langs->load(\"trips\");", "\t\t$sql = \"SELECT c.code, c.label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_type_fees as c\";\n\t\t$sql.= \" WHERE active > 0\";", "\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;", "\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));\n\t\t\t\t$this->cache_types_fees[$obj->code] = $label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\tasort($this->cache_types_fees);", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of types of notes\n\t *\n\t *\t@param\tstring\t\t$selected\t\tPreselected type\n\t *\t@param string\t\t$htmlname\t\tName of field in form\n\t * \t@param\tint\t\t\t$showempty\t\tAdd an empty field\n\t * \t@return\tvoid\n\t */\n\tfunction select_type_fees($selected='',$htmlname='type',$showempty=0)\n\t{\n\t\tglobal $user, $langs;", "\t\tdol_syslog(__METHOD__.\" selected=\".$selected.\", htmlname=\".$htmlname, LOG_DEBUG);", "\t\t$this->load_cache_types_fees();", "\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\tif ($showempty)\n\t\t{\n\t\t\tprint '<option value=\"-1\"';\n\t\t\tif ($selected == -1) print ' selected';\n\t\t\tprint '>&nbsp;</option>';\n\t\t}", "\t\tforeach($this->cache_types_fees as $key => $value)\n\t\t{\n\t\t\tprint '<option value=\"'.$key.'\"';\n\t\t\tif ($key == $selected) print ' selected';\n\t\t\tprint '>';\n\t\t\tprint $value;\n\t\t\tprint '</option>';\n\t\t}", "\t\tprint '</select>';\n\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\n\t/**\n\t * Return HTML code to select a company.\n\t *\n\t * @param\t\tint\t\t\t$selected\t\t\t\tPreselected products\n\t * @param\t\tstring\t\t$htmlname\t\t\t\tName of HTML select field (must be unique in page)\n\t * @param\t\tint\t\t\t$filter\t\t\t\t\tFilter on thirdparty\n\t * @param\t\tint\t\t\t$limit\t\t\t\t\tLimit on number of returned lines\n\t * @param\t\tarray\t\t$ajaxoptions\t\t\tOptions for ajax_autocompleter\n\t * \t@param\t\tint\t\t\t$forcecombo\t\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @return\t\tstring\t\t\t\t\t\t\t\tReturn select box for thirdparty.\n\t * @deprecated\t3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)\n\t */\n\tfunction select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)\n\t{\n \t\treturn $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);\n\t}", "\t/**\n\t * Output html form to select a third party\n\t *\n\t *\t@param\tstring\t$selected \t\tPreselected type\n\t *\t@param string\t$htmlname \t\tName of field in form\n\t * @param string\t$filter \t\toptional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')\n\t *\t@param\tstring\t$showempty\t\t\t\tAdd an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')\n\t * \t@param\tint\t\t$showtype\t\t\t\tShow third party type in combolist (customer, prospect or supplier)\n\t * \t@param\tint\t\t$forcecombo\t\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @param\tarray\t$events\t\t\t\t\tAjax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t *\t@param\tint\t\t$limit\t\t\t\t\tMaximum number of elements\n\t * @param\tstring\t$morecss\t\t\t\tAdd more css styles to the SELECT component\n\t *\t@param string\t$moreparam \t\tAdd more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t *\t@param\tstring\t$selected_input_value\tValue of preselected input text (for use with ajax)\n\t * @param\tint\t\t$hidelabel\t\t\t\tHide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)\n\t * @param\tarray\t$ajaxoptions\t\t\tOptions for ajax_autocompleter\n\t * \t@return\tstring\t\t\t\t\t\t\tHTML string with select box for thirdparty.\n\t */\n\tfunction select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array())\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t$out='';", "\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)\n\t\t{\n\t\t\t// No immediate load of all database\n\t\t\t$placeholder='';\n\t\t\tif ($selected && empty($selected_input_value))\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';\n\t\t\t\t$societetmp = new Societe($this->db);\n\t\t\t\t$societetmp->fetch($selected);\n\t\t\t\t$selected_input_value=$societetmp->name;\n\t\t\t\tunset($societetmp);\n\t\t\t}\n\t\t\t// mode 1\n\t\t\t$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');\n\t\t\t$out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);\n\t\t\t$out.='<style type=\"text/css\">.ui-autocomplete { z-index: 250; }</style>';\n\t\t\tif (empty($hidelabel)) print $langs->trans(\"RefOrLabel\").' : ';\n\t\t\telse if ($hidelabel > 1) {\n\t\t\t\t$placeholder=' placeholder=\"'.$langs->trans(\"RefOrLabel\").'\"';\n\t\t\t\tif ($hidelabel == 2) {\n\t\t\t\t\t$out.= img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '<input type=\"text\" class=\"'.$morecss.'\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$selected_input_value.'\"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';\n\t\t\tif ($hidelabel == 3) {\n\t\t\t\t$out.= img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Immediate load of all database\n\t\t\t$out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Output html form to select a third party.\n\t * Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.\n\t *\n\t *\t@param\tstring\t$selected Preselected type\n\t *\t@param string\t$htmlname Name of field in form", "\t * @param string\t$filter Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')", "\t *\t@param\tstring\t$showempty\t\tAdd an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')\n\t * \t@param\tint\t\t$showtype\t\tShow third party type in combolist (customer, prospect or supplier)\n\t * \t@param\tint\t\t$forcecombo\t\tForce to use standard HTML select component without beautification\n\t * @param\tarray\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @param\tstring\t$filterkey\t\tFilter on key value\n\t * @param\tint\t\t$outputmode\t\t0=HTML select string, 1=Array\n\t * @param\tint\t\t$limit\t\t\tLimit number of answers\n\t * @param\tstring\t$morecss\t\tAdd more css styles to the SELECT component\n\t *\t@param string\t$moreparam Add more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t * \t@return\tstring\t\t\t\t\tHTML string with\n\t */\n\tfunction select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='')\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t$out='';\n\t\t$num=0;\n\t\t$outarray=array();", "\n\t\t// Clean $filter that may contains sql conditions so sql code\n\t\tif (function_exists('test_sql_and_script_inject')) $filter = test_sql_and_script_inject($filter, 3);", "\n\t\t// On recherche les societes\n\t\t$sql = \"SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"societe as s\";\n\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= \", \".MAIN_DB_PREFIX.\"societe_commerciaux as sc\";\n\t\t$sql.= \" WHERE s.entity IN (\".getEntity('societe').\")\";\n\t\tif (! empty($user->societe_id)) $sql.= \" AND s.rowid = \".$user->societe_id;\n\t\tif ($filter) $sql.= \" AND (\".$filter.\")\";\n\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= \" AND s.rowid = sc.fk_soc AND sc.fk_user = \" .$user->id;\n\t\tif (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= \" AND s.status <> 0\";\n\t\t// Add criteria\n\t\tif ($filterkey && $filterkey != '')\n\t\t{\n\t\t\t$sql.=\" AND (\";\n\t\t\t$prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';\t// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on\n\t\t\t// For natural search\n\t\t\t$scrit = explode(' ', $filterkey);\n\t\t\t$i=0;\n\t\t\tif (count($scrit) > 1) $sql.=\"(\";\n\t\t\tforeach ($scrit as $crit) {\n\t\t\t\tif ($i > 0) $sql.=\" AND \";\n\t\t\t\t$sql.=\"(s.nom LIKE '\".$this->db->escape($prefix.$crit).\"%')\";\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tif (count($scrit) > 1) $sql.=\")\";\n\t\t\tif (! empty($conf->barcode->enabled))\n\t\t\t{\n\t\t\t\t$sql .= \" OR s.barcode LIKE '\".$this->db->escape($filterkey).\"%'\";\n\t\t\t}\n\t\t\t$sql.=\")\";\n\t\t}\n\t\t$sql.=$this->db->order(\"nom\",\"ASC\");\n\t\t$sql.=$this->db->plimit($limit, 0);", "\t\t// Build output string\n\t\tdol_syslog(get_class($this).\"::select_thirdparty_list\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t \tif (! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);\n\t\t\t}", "\t\t\t// Construct $out and $outarray\n\t\t\t$out.= '<select id=\"'.$htmlname.'\" class=\"flat'.($morecss?' '.$morecss:'').'\"'.($moreparam?' '.$moreparam:'').' name=\"'.$htmlname.'\">'.\"\\n\";", "\t\t\t$textifempty='';\n\t\t\t// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.\n\t\t\t//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';\n\t\t\tif (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))\n\t\t\t{\n\t\t\t\tif ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);\n\t\t\t\telse $textifempty.=$langs->trans(\"All\");\n\t\t\t}\n\t\t\tif ($showempty) $out.= '<option value=\"-1\">'.$textifempty.'</option>'.\"\\n\";", "\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$label='';\n\t\t\t\t\tif ($conf->global->SOCIETE_ADD_REF_IN_LIST) {\n\t\t\t\t\t\tif (($obj->client) && (!empty($obj->code_client))) {\n\t\t\t\t\t\t\t$label = $obj->code_client. ' - ';\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {\n\t\t\t\t\t\t\t$label .= $obj->code_fournisseur. ' - ';\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$label.=' '.$obj->name;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$label=$obj->name;\n\t\t\t\t\t}", "\t\t\t\t\tif(!empty($obj->name_alias)) {\n\t\t\t\t\t\t$label.=' ('.$obj->name_alias.')';\n\t\t\t\t\t}", "\t\t\t\t\tif ($showtype)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($obj->client || $obj->fournisseur) $label.=' (';\n\t\t\t\t\t\tif ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans(\"Customer\");\n\t\t\t\t\t\tif ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans(\"Prospect\");\n\t\t\t\t\t\tif ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans(\"Supplier\");\n\t\t\t\t\t\tif ($obj->client || $obj->fournisseur) $label.=')';\n\t\t\t\t\t}", "\t\t\t\t\tif (empty($outputmode))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($selected > 0 && $selected == $obj->rowid)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\" selected>'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\">'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tarray_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));\n\t\t\t\t\t}", "\t\t\t\t\t$i++;\n\t\t\t\t\tif (($i % 10) == 0) $out.=\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t$out.= '</select>'.\"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\t$this->result=array('nbofthirdparties'=>$num);", "\t\tif ($outputmode) return $outarray;\n\t\treturn $out;\n\t}", "\n\t/**\n\t * \tReturn HTML combo list of absolute discounts\n\t *\n\t * \t@param\tstring\t$selected Id remise fixe pre-selectionnee\n\t * \t@param string\t$htmlname Nom champ formulaire\n\t * \t@param string\t$filter Criteres optionnels de filtre\n\t * \t\t@param\tint\t\t$socid\t\t\tId of thirdparty\n\t * \t\t@param\tint\t\t$maxvalue\t\tMax value for lines that can be selected\n\t * \t\t@return\tint\t\t\t\t\t\tReturn number of qualifed lines in list\n\t */\n\tfunction select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)\n\t{\n\t\tglobal $langs,$conf;", "\t\t// On recherche les remises\n\t\t$sql = \"SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,\";\n\t\t$sql.= \" re.description, re.fk_facture_source\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"societe_remise_except as re\";\n\t\t$sql.= \" WHERE re.fk_soc = \".(int) $socid;\n\t\t$sql.= \" AND re.entity = \" . $conf->entity;\n\t\tif ($filter) $sql.= \" AND \".$filter;\n\t\t$sql.= \" ORDER BY re.description ASC\";", "\t\tdol_syslog(get_class($this).\"::select_remises\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tprint '<select class=\"flat maxwidthonsmartphone\" name=\"'.$htmlname.'\">';\n\t\t\t$num = $this->db->num_rows($resql);", "\t\t\t$qualifiedlines=$num;", "\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tprint '<option value=\"0\">&nbsp;</option>';\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$desc=dol_trunc($obj->description,40);\n\t\t\t\t\tif (preg_match('/\\(CREDIT_NOTE\\)/', $desc)) $desc=preg_replace('/\\(CREDIT_NOTE\\)/', $langs->trans(\"CreditNote\"), $desc);\n\t\t\t\t\tif (preg_match('/\\(DEPOSIT\\)/', $desc)) $desc=preg_replace('/\\(DEPOSIT\\)/', $langs->trans(\"Deposit\"), $desc);\n\t\t\t\t\tif (preg_match('/\\(EXCESS RECEIVED\\)/', $desc)) $desc=preg_replace('/\\(EXCESS RECEIVED\\)/', $langs->trans(\"ExcessReceived\"), $desc);", "\t\t\t\t\t$selectstring='';\n\t\t\t\t\tif ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';", "\t\t\t\t\t$disabled='';\n\t\t\t\t\tif ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)\n\t\t\t\t\t{\n\t\t\t\t\t\t$qualifiedlines--;\n\t\t\t\t\t\t$disabled=' disabled';\n\t\t\t\t\t}", "\t\t\t\t\tif (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))\n\t\t\t\t\t{\n\t\t\t\t\t\t$tmpfac = new Facture($this->db);\n\t\t\t\t\t\tif ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;\n\t\t\t\t\t}", "\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans(\"HT\").' - '.price($obj->amount_ttc).' '.$langs->trans(\"TTC\").')</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tprint '</select>';\n\t\t\treturn $qualifiedlines;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of all contacts (for a third party or all)\n\t *\n\t *\t@param\tint\t\t$socid \tId ot third party or 0 for all\n\t *\t@param string\t$selected \tId contact pre-selectionne\n\t *\t@param string\t$htmlname \t Name of HTML field ('none' for a not editable field)\n\t *\t@param int\t\t$showempty 0=no empty value, 1=add an empty value\n\t *\t@param string\t$exclude List of contacts id to exclude\n\t *\t@param\tstring\t$limitto\t\tDisable answers that are not id in this array list\n\t *\t@param\tinteger\t$showfunction Add function into label\n\t *\t@param\tstring\t$moreclass\t\tAdd more class to class style\n\t *\t@param\tinteger\t$showsoc\t Add company into label\n\t * \t@param\tint\t\t$forcecombo\t\tForce to use combo box\n\t * @param\tarray\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @param\tbool\t$options_only\tReturn options only (for ajax treatment)\n\t * @param\tstring\t$moreparam\t\tAdd more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t * @param\tstring\t$htmlid\t\t\tHtml id to use instead of htmlname\n\t *\t@return\tint\t\t\t\t\t\t<0 if KO, Nb of contact in list if OK\n\t * @deprected\t\t\t\t\t\tYou can use selectcontacts directly (warning order of param was changed)\n\t */\n\tfunction select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')\n\t{\n\t\tprint $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);\n\t\treturn $this->num;\n\t}", "\t/**\n\t *\tReturn HTML code of the SELECT of list of all contacts (for a third party or all).\n\t * This also set the number of contacts found into $this->num\n\t *\n\t *\t@param\tint\t\t\t$socid \tId ot third party or 0 for all\n\t *\t@param array|int\t$selected \tArray of ID of pre-selected contact id\n\t *\t@param string\t\t$htmlname \t Name of HTML field ('none' for a not editable field)\n\t *\t@param int\t\t\t$showempty \t0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit)\n\t *\t@param string\t\t$exclude List of contacts id to exclude\n\t *\t@param\tstring\t\t$limitto\t\tDisable answers that are not id in this array list\n\t *\t@param\tinteger\t\t$showfunction Add function into label\n\t *\t@param\tstring\t\t$moreclass\t\tAdd more class to class style\n\t *\t@param\tbool\t\t$options_only\tReturn options only (for ajax treatment)\n\t *\t@param\tinteger\t\t$showsoc\t Add company into label\n\t * \t@param\tint\t\t\t$forcecombo\t\tForce to use combo box\n\t * @param\tarray\t\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @param\tstring\t\t$moreparam\t\tAdd more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t * @param\tstring\t\t$htmlid\t\t\tHtml id to use instead of htmlname\n\t *\t@return\t int\t\t\t\t\t\t<0 if KO, Nb of contact in list if OK\n\t */\n\tfunction selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='')\n\t{\n\t\tglobal $conf,$langs;", "\t\t$langs->load('companies');", "\t\tif (empty($htmlid)) $htmlid = $htmlname;\n $out='';", "\t\t// On recherche les societes\n\t\t$sql = \"SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste\";\n\t\tif ($showsoc > 0) $sql.= \" , s.nom as company\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"socpeople as sp\";\n\t\tif ($showsoc > 0) $sql.= \" LEFT OUTER JOIN \".MAIN_DB_PREFIX .\"societe as s ON s.rowid=sp.fk_soc\";\n\t\t$sql.= \" WHERE sp.entity IN (\".getEntity('societe').\")\";\n\t\tif ($socid > 0) $sql.= \" AND sp.fk_soc=\".$socid;\n\t\tif (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= \" AND sp.statut <> 0\";\n\t\t$sql.= \" ORDER BY sp.lastname ASC\";", "\t\tdol_syslog(get_class($this).\"::select_contacts\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num=$this->db->num_rows($resql);", "\t\t\tif ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);\n\t\t\t}", "\t\t\tif ($htmlname != 'none' || $options_only) $out.= '<select class=\"flat'.($moreclass?' '.$moreclass:'').'\" id=\"'.$htmlid.'\" name=\"'.$htmlname.'\" '.(!empty($moreparam) ? $moreparam : '').'>';\n\t\t\tif ($showempty == 1) $out.= '<option value=\"0\"'.($selected=='0'?' selected':'').'>&nbsp;</option>';\n\t\t\tif ($showempty == 2) $out.= '<option value=\"0\"'.($selected=='0'?' selected':'').'>'.$langs->trans(\"Internal\").'</option>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';\n\t\t\t\t$contactstatic=new Contact($this->db);", "\t\t\t\tif (!is_array($selected)) $selected = array($selected);\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t\t$contactstatic->id=$obj->rowid;\n\t\t\t\t\t$contactstatic->lastname=$obj->lastname;\n\t\t\t\t\t$contactstatic->firstname=$obj->firstname;\n\t\t\t\t\tif ($obj->statut == 1){\n\t\t\t\t\tif ($htmlname != 'none')\n\t\t\t\t\t{\n\t\t\t\t\t\t$disabled=0;\n\t\t\t\t\t\tif (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;\n\t\t\t\t\t\tif (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;\n\t\t\t\t\t\tif (!empty($selected) && in_array($obj->rowid, $selected))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\t\tif ($disabled) $out.= ' disabled';\n\t\t\t\t\t\t\t$out.= ' selected>';\n\t\t\t\t\t\t\t$out.= $contactstatic->getFullName($langs);\n\t\t\t\t\t\t\tif ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';\n\t\t\t\t\t\t\tif (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';\n\t\t\t\t\t\t\t$out.= '</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\t\tif ($disabled) $out.= ' disabled';\n\t\t\t\t\t\t\t$out.= '>';\n\t\t\t\t\t\t\t$out.= $contactstatic->getFullName($langs);\n\t\t\t\t\t\t\tif ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';\n\t\t\t\t\t\t\tif (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';\n\t\t\t\t\t\t\t$out.= '</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (in_array($obj->rowid, $selected))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= $contactstatic->getFullName($langs);\n\t\t\t\t\t\t\tif ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';\n\t\t\t\t\t\t\tif (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.= '<option value=\"-1\"'.($showempty==2?'':' selected').' disabled>'.$langs->trans($socid?\"NoContactDefinedForThirdParty\":\"NoContactDefined\").'</option>';\n\t\t\t}\n\t\t\tif ($htmlname != 'none' || $options_only)\n\t\t\t{\n\t\t\t\t$out.= '</select>';\n\t\t\t}", "\t\t\t$this->num = $num;\n\t\t\treturn $out;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn select list of users\n\t *\n\t * @param\tstring\t$selected Id user preselected\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue\n\t * @param array\t$exclude Array list of users id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param array\t$include Array list of users id to include\n\t * \t@param\tint\t\t$enableonly\t\tArray list of users id to be enabled. All other must be disabled\n\t * @param\tstring\t$force_entity\t'0' or Ids of environment to force\n\t * \t@return\tvoid\n\t * @deprecated\t\tUse select_dolusers instead\n\t * @see select_dolusers()\n\t */\n\tfunction select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')\n\t{\n\t\tprint $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);\n\t}", "\t/**\n\t *\tReturn select list of users\n\t *\n\t * @param\tstring\t$selected User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=list with no empty value, 1=add also an empty value into list\n\t * @param array\t$exclude Array list of users id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param array|string\t$include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me\n\t * \t@param\tarray\t$enableonly\t\tArray list of users id to be enabled. If defined, it means that others will be disabled\n\t * @param\tstring\t$force_entity\t'0' or Ids of environment to force\n\t * @param\tint\t\t$maxlength\t\tMaximum length of string into list (0=no limit)\n\t * @param\tint\t\t$showstatus\t\t0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status\n\t * @param\tstring\t$morefilter\t\tAdd more filters into sql request (Example: 'employee = 1')\n\t * @param\tinteger\t$show_every\t\t0=default list, 1=add also a value \"Everybody\" at beginning of list\n\t * @param\tstring\t$enableonlytext\tIf option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.\n\t * @param\tstring\t$morecss\t\tMore css\n\t * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).\n\t * \t@return\tstring\t\t\t\t\tHTML select string\n\t * @see select_dolgroups\n\t */\n\tfunction select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0)\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t// If no preselected user defined, we take current user\n\t\tif ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;", "\t\t$excludeUsers=null;\n\t\t$includeUsers=null;", "\t\t// Permettre l'exclusion d'utilisateurs\n\t\tif (is_array($exclude))\t$excludeUsers = implode(\",\",$exclude);\n\t\t// Permettre l'inclusion d'utilisateurs\n\t\tif (is_array($include))\t$includeUsers = implode(\",\",$include);\n\t\telse if ($include == 'hierarchy')\n\t\t{\n\t\t\t// Build list includeUsers to have only hierarchy\n\t\t\t$includeUsers = implode(\",\",$user->getAllChildIds(0));\n\t\t}\n\t\telse if ($include == 'hierarchyme')\n\t\t{\n\t\t\t// Build list includeUsers to have only hierarchy and current user\n\t\t\t$includeUsers = implode(\",\",$user->getAllChildIds(1));\n\t\t}", "\t\t$out='';", "\t\t// Forge request to select users\n\t\t$sql = \"SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity\";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \", e.label\";\n\t\t}\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX .\"user as u\";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX .\"entity as e ON e.rowid=u.entity\";\n\t\t\tif ($force_entity) $sql.= \" WHERE u.entity IN (0,\".$force_entity.\")\";\n\t\t\telse $sql.= \" WHERE u.entity IS NOT NULL\";\n\t\t}\n\t\telse\n\t {\n\t\t\tif (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))\n\t\t\t{\n\t\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"usergroup_user as ug\";\n\t\t\t\t$sql.= \" ON ug.fk_user = u.rowid\";\n\t\t\t\t$sql.= \" WHERE ug.entity = \".$conf->entity;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$sql.= \" WHERE u.entity IN (0,\".$conf->entity.\")\";\n\t\t\t}\n\t\t}\n\t\tif (! empty($user->societe_id)) $sql.= \" AND u.fk_soc = \".$user->societe_id;\n\t\tif (is_array($exclude) && $excludeUsers) $sql.= \" AND u.rowid NOT IN (\".$excludeUsers.\")\";\n\t\tif ($includeUsers) $sql.= \" AND u.rowid IN (\".$includeUsers.\")\";\n\t\tif (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= \" AND u.statut <> 0\";\n\t\tif (! empty($morefilter)) $sql.=\" \".$morefilter;", "\t\tif(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){\n\t\t\t$sql.= \" ORDER BY u.firstname ASC\";\n\t\t}else{\n\t\t\t$sql.= \" ORDER BY u.lastname ASC\";\n\t\t}", "\t\tdol_syslog(get_class($this).\"::select_dolusers\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t \t\t// Enhance with select2\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname);", "\t\t\t\t// do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined\n\t\t\t\t$out.= '<select class=\"flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.($disabled?' disabled':'').'>';\n\t\t\t\tif ($show_empty) $out.= '<option value=\"-1\"'.((empty($selected) || $selected==-1)?' selected':'').'>&nbsp;</option>'.\"\\n\";\n\t\t\t\tif ($show_every) $out.= '<option value=\"-2\"'.(($selected==-2)?' selected':'').'>-- '.$langs->trans(\"Everybody\").' --</option>'.\"\\n\";", "\t\t\t\t$userstatic=new User($this->db);", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t\t$userstatic->id=$obj->rowid;\n\t\t\t\t\t$userstatic->lastname=$obj->lastname;\n\t\t\t\t\t$userstatic->firstname=$obj->firstname;", "\t\t\t\t\t$disableline='';\n\t\t\t\t\tif (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');", "\t\t\t\t\tif ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\tif ($disableline) $out.= ' disabled';\n\t\t\t\t\t\t$out.= ' selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\t\tif ($disableline) $out.= ' disabled';\n\t\t\t\t\t\t$out.= '>';\n\t\t\t\t\t}", "\t\t\t\t\t$fullNameMode = 0; //Lastname + firstname\n\t\t\t\t\tif(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){\n\t\t\t\t\t\t$fullNameMode = 1; //firstname + lastname\n\t\t\t\t\t}\n\t\t\t\t\t$out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);", "\t\t\t\t\t// Complete name with more info\n\t\t\t\t\t$moreinfo=0;\n\t\t\t\t\tif (! empty($conf->global->MAIN_SHOW_LOGIN))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= ($moreinfo?' - ':' (').$obj->login;\n\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t}\n\t\t\t\t\tif ($showstatus >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($obj->statut == 1 && $showstatus == 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ($obj->statut == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (! $obj->entity)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').$langs->trans(\"AllEntities\");\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans(\"EntityNameNotDefined\"));\n\t\t\t\t\t\t\t$moreinfo++;\n\t\t\t\t\t \t}\n\t\t\t\t\t}\n\t\t\t\t\t$out.=($moreinfo?')':'');\n\t\t\t\t\tif ($disableline && $disableline != '1')\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.=' - '.$disableline;\t// This is text from $enableonlytext parameter\n\t\t\t\t\t}\n\t\t\t\t\t$out.= '</option>';", "\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.= '<select class=\"flat\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\" disabled>';\n\t\t\t\t$out.= '<option value=\"\">'.$langs->trans(\"None\").'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn select list of users. Selected users are stored into session.\n\t * List of users are provided into $_SESSION['assignedtouser'].\n\t *\n\t * @param string\t$action Value for $action\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=list without the empty value, 1=add empty value\n\t * @param array\t$exclude Array list of users id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param array\t$include Array list of users id to include or 'hierarchy' to have only supervised users\n\t * \t@param\tarray\t$enableonly\t\tArray list of users id to be enabled. All other must be disabled\n\t * @param\tint\t\t$force_entity\t'0' or Ids of environment to force\n\t * @param\tint\t\t$maxlength\t\tMaximum length of string into list (0=no limit)\n\t * @param\tint\t\t$showstatus\t\t0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status\n\t * @param\tstring\t$morefilter\t\tAdd more filters into sql request\n\t * @param\tint\t\t$showproperties\t\tShow properties of each attendees\n\t * @param\tarray\t$listofuserid\t\tArray with properties of each user\n\t * @param\tarray\t$listofcontactid\tArray with properties of each contact\n\t * @param\tarray\t$listofotherid\t\tArray with properties of each other contact\n\t * \t@return\tstring\t\t\t\t\tHTML select string\n\t * @see select_dolgroups\n\t */\n\tfunction select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())\n\t{\n\t\tglobal $conf, $user, $langs;", "\t\t$userstatic=new User($this->db);\n\t\t$out='';", "\t\t// Method with no ajax\n\t\t//$out.='<form method=\"POST\" action=\"'.$_SERVER[\"PHP_SELF\"].'\">';\n\t\tif ($action == 'view')\n\t\t{\n\t\t\t$out.='';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$out.='<input type=\"hidden\" class=\"removedassignedhidden\" name=\"removedassigned\" value=\"\">';\n\t\t\t$out.='<script type=\"text/javascript\" language=\"javascript\">jQuery(document).ready(function () { jQuery(\".removedassigned\").click(function() { jQuery(\".removedassignedhidden\").val(jQuery(this).val()); });})</script>';\n\t\t\t$out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);\n\t\t\t$out.=' <input type=\"submit\" class=\"button valignmiddle\" name=\"'.$action.'assignedtouser\" value=\"'.dol_escape_htmltag($langs->trans(\"Add\")).'\">';\n\t\t\t$out.='<br>';\n\t\t}\n\t\t$assignedtouser=array();\n\t\tif (!empty($_SESSION['assignedtouser']))\n\t\t{\n\t\t\t$assignedtouser=json_decode($_SESSION['assignedtouser'], true);\n\t\t}\n\t\t$nbassignetouser=count($assignedtouser);", "\t\tif ($nbassignetouser && $action != 'view') $out.='<br>';\n\t\tif ($nbassignetouser) $out.='<ul class=\"attendees\">';\n\t\t$i=0; $ownerid=0;\n\t\tforeach($assignedtouser as $key => $value)\n\t\t{\n\t\t\tif ($value['id'] == $ownerid) continue;", "\t\t\t$out.='<li>';\n\t\t\t$userstatic->fetch($value['id']);\n\t\t\t$out.= $userstatic->getNomUrl(-1);\n\t\t\tif ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans(\"Owner\").')'; }\n\t\t\tif ($nbassignetouser > 1 && $action != 'view') $out.=' <input type=\"image\" style=\"border: 0px;\" src=\"'.img_picto($langs->trans(\"Remove\"), 'delete', '', 0, 1).'\" value=\"'.$userstatic->id.'\" class=\"removedassigned\" id=\"removedassigned_'.$userstatic->id.'\" name=\"removedassigned_'.$userstatic->id.'\">';\n\t\t\t// Show my availability\n\t\t\tif ($showproperties)\n\t\t\t{\n\t\t\t\tif ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))\n\t\t\t\t{\n\t\t\t\t\t$out.='<div class=\"myavailability inline-block\">';\n\t\t\t\t\t$out.='&nbsp;-&nbsp;<span class=\"opacitymedium\">'.$langs->trans(\"Availability\").':</span> <input id=\"transparency\" class=\"marginleftonly marginrightonly\" '.($action == 'view'?'disabled':'').' type=\"checkbox\" name=\"transparency\"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans(\"Busy\");\n\t\t\t\t\t$out.='</div>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t//$out.=' '.($value['mandatory']?$langs->trans(\"Mandatory\"):$langs->trans(\"Optional\"));\n\t\t\t//$out.=' '.($value['transparency']?$langs->trans(\"Busy\"):$langs->trans(\"NotBusy\"));", "\t\t\t$out.='</li>';\n\t\t\t$i++;\n\t\t}\n\t\tif ($nbassignetouser) $out.='</ul>';", "\t\t//$out.='</form>';\n\t\treturn $out;\n\t}", "\n\t/**\n\t * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list\n\t *\n\t * @param\t\tint\t\t\t$selected\t\t\t\tPreselected products\n\t * @param\t\tstring\t\t$htmlname\t\t\t\tName of HTML select field (must be unique in page)\n\t * @param\t\tint\t\t\t$filtertype\t\t\t\tFilter on product type (''=nofilter, 0=product, 1=service)\n\t * @param\t\tint\t\t\t$limit\t\t\t\t\tLimit on number of returned lines\n\t * @param\t\tint\t\t\t$price_level\t\t\tLevel of price to show\n\t * @param\t\tint\t\t\t$status\t\t\t\t\t-1=Return all products, 0=Products not on sell, 1=Products on sell\n\t * @param\t\tint\t\t\t$finished\t\t\t\t2=all, 1=finished, 0=raw material\n\t * @param\t\tstring\t\t$selected_input_value\tValue of preselected input text (for use with ajax)\n\t * @param\t\tint\t\t\t$hidelabel\t\t\t\tHide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)\n\t * @param\t\tarray\t\t$ajaxoptions\t\t\tOptions for ajax_autocompleter\n\t * @param int\t\t\t$socid\t\t\t\t\tThirdparty Id (to get also price dedicated to this customer)\n\t * @param\t\tstring\t\t$showempty\t\t\t\t'' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.\n\t * \t@param\t\tint\t\t\t$forcecombo\t\t\t\tForce to use combo box\n\t * @param string $morecss Add more css on select\n\t * @param int $hidepriceinlabel 1=Hide prices in label\n\t * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseopen' = select products from open warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseclosed' = select products from closed warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseinternal' = select products from warehouses for internal correct/transfer only\n\t * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])\n\t * @return\t\tvoid\n\t */\n\tfunction select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())\n\t{\n\t\tglobal $langs,$conf;", "\t\t$price_level = (! empty($price_level) ? $price_level : 0);", "\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))\n\t\t{\n\t\t\t$placeholder='';", "\t\t\tif ($selected && empty($selected_input_value))\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\n\t\t\t\t$producttmpselect = new Product($this->db);\n\t\t\t\t$producttmpselect->fetch($selected);\n\t\t\t\t$selected_input_value=$producttmpselect->ref;\n\t\t\t\tunset($producttmpselect);\n\t\t\t}\n\t\t\t// mode=1 means customers products\n\t\t\t$urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;\n\t\t\t//Price by customer\n\t\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {\n\t\t\t\t$urloption.='&socid='.$socid;\n\t\t\t}\n\t\t\tprint ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);", "\t\t\tif (!empty($conf->variants->enabled)) {\n\t\t\t\t?>\n\t\t\t\t<script>", "\t\t\t\t\tselected = <?php echo json_encode($selected_combinations) ?>;\n\t\t\t\t\tcombvalues = {};", "\t\t\t\t\tjQuery(document).ready(function () {", "\t\t\t\t\t\tjQuery(\"input[name='prod_entry_mode']\").change(function () {\n\t\t\t\t\t\t\tif (jQuery(this).val() == 'free') {\n\t\t\t\t\t\t\t\tjQuery('div#attributes_box').empty();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});", "\t\t\t\t\t\tjQuery(\"input#<?php echo $htmlname ?>\").change(function () {", "\t\t\t\t\t\t\tif (!jQuery(this).val()) {\n\t\t\t\t\t\t\t\tjQuery('div#attributes_box').empty();\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\tjQuery.getJSON(\"<?php echo dol_buildpath('/variants/ajax/getCombinations.php', 2) ?>\", {\n\t\t\t\t\t\t\t\tid: jQuery(this).val()\n\t\t\t\t\t\t\t}, function (data) {\n\t\t\t\t\t\t\t\tjQuery('div#attributes_box').empty();", "\t\t\t\t\t\t\t\tjQuery.each(data, function (key, val) {", "\t\t\t\t\t\t\t\t\tcombvalues[val.id] = val.values;", "\t\t\t\t\t\t\t\t\tvar span = jQuery(document.createElement('div')).css({\n\t\t\t\t\t\t\t\t\t\t'display': 'table-row'\n\t\t\t\t\t\t\t\t\t});", "\t\t\t\t\t\t\t\t\tspan.append(\n\t\t\t\t\t\t\t\t\t\tjQuery(document.createElement('div')).text(val.label).css({\n\t\t\t\t\t\t\t\t\t\t\t'font-weight': 'bold',\n\t\t\t\t\t\t\t\t\t\t\t'display': 'table-cell',\n\t\t\t\t\t\t\t\t\t\t\t'text-align': 'right'\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t);", "\t\t\t\t\t\t\t\t\tvar html = jQuery(document.createElement('select')).attr('name', 'combinations[' + val.id + ']').css({\n\t\t\t\t\t\t\t\t\t\t'margin-left': '15px',\n\t\t\t\t\t\t\t\t\t\t'white-space': 'pre'\n\t\t\t\t\t\t\t\t\t}).append(\n\t\t\t\t\t\t\t\t\t\tjQuery(document.createElement('option')).val('')\n\t\t\t\t\t\t\t\t\t);", "\t\t\t\t\t\t\t\t\tjQuery.each(combvalues[val.id], function (key, val) {\n\t\t\t\t\t\t\t\t\t\tvar tag = jQuery(document.createElement('option')).val(val.id).html(val.value);", "\t\t\t\t\t\t\t\t\t\tif (selected[val.fk_product_attribute] == val.id) {\n\t\t\t\t\t\t\t\t\t\t\ttag.attr('selected', 'selected');\n\t\t\t\t\t\t\t\t\t\t}", "\t\t\t\t\t\t\t\t\t\thtml.append(tag);\n\t\t\t\t\t\t\t\t\t});", "\t\t\t\t\t\t\t\t\tspan.append(html);\n\t\t\t\t\t\t\t\t\tjQuery('div#attributes_box').append(span);\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t});", "\t\t\t\t\t\t<?php if ($selected): ?>\n\t\t\t\t\t\tjQuery(\"input#<?php echo $htmlname ?>\").change();\n\t\t\t\t\t\t<?php endif ?>\n\t\t\t\t\t});\n\t\t\t\t</script>\n <?php\n\t\t\t}\n\t\t\tif (empty($hidelabel)) print $langs->trans(\"RefOrLabel\").' : ';\n\t\t\telse if ($hidelabel > 1) {\n\t\t\t\t$placeholder=' placeholder=\"'.$langs->trans(\"RefOrLabel\").'\"';\n\t\t\t\tif ($hidelabel == 2) {\n\t\t\t\t\tprint img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t\t}\n\t\t\t}\n\t\t\tprint '<input type=\"text\" class=\"minwidth100\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$selected_input_value.'\"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';\n\t\t\tif ($hidelabel == 3) {\n\t\t\t\tprint img_picto($langs->trans(\"Search\"), 'search');\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprint $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of products for a customer\n\t *\n\t *\t@param int\t\t$selected Preselected product\n\t *\t@param string\t$htmlname Name of select html\n\t * @param\t\tstring\t$filtertype Filter on product type (''=nofilter, 0=product, 1=service)\n\t *\t@param int\t\t$limit Limit on number of returned lines\n\t *\t@param int\t\t$price_level Level of price to show\n\t * \t@param string\t$filterkey Filter on product\n\t *\t@param\t\tint\t\t$status -1=Return all products, 0=Products not on sell, 1=Products on sell\n\t * @param int\t\t$finished Filter on finished field: 2=No filter\n\t * @param int\t\t$outputmode 0=HTML select string, 1=Array\n\t * @param int\t\t$socid \t\t Thirdparty Id (to get also price dedicated to this customer)\n\t * @param\t\tstring\t$showempty\t\t '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.\n\t * \t@param\t\tint\t\t$forcecombo\t\t Force to use combo box\n\t * @param string $morecss Add more css on select\n\t * @param int $hidepriceinlabel 1=Hide prices in label\n\t * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseopen' = select products from open warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseclosed' = select products from closed warehouses,\n\t *\t\t\t\t\t\t\t\t\t\t 'warehouseinternal' = select products from warehouses for internal correct/transfer only\n\t * @return array \t\t\t\t Array of keys for json\n\t */\n\tfunction select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')\n\t{\n\t\tglobal $langs,$conf,$user,$db;", "\t\t$out='';\n\t\t$outarray=array();", "\t\t$warehouseStatusArray = array();\n\t\tif (! empty($warehouseStatus))\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';\n\t\t\tif (preg_match('/warehouseclosed/', $warehouseStatus))\n\t\t\t{\n\t\t\t\t$warehouseStatusArray[] = Entrepot::STATUS_CLOSED;\n\t\t\t}\n\t\t\tif (preg_match('/warehouseopen/', $warehouseStatus))\n\t\t\t{\n\t\t\t\t$warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;\n\t\t\t}\n\t\t\tif (preg_match('/warehouseinternal/', $warehouseStatus))\n\t\t\t{\n\t\t\t\t$warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;\n\t\t\t}\n\t\t}", "\t\t$selectFields = \" p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression\";\n\t\t(count($warehouseStatusArray)) ? $selectFieldsGrouped = \", sum(ps.reel) as stock\" : $selectFieldsGrouped = \", p.stock\";", "\t\t$sql = \"SELECT \";\n\t\t$sql.= $selectFields . $selectFieldsGrouped;\n\t\t//Price by customer\n\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))\n\t\t{\n\t\t\t$sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';\n\t\t\t$sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';\n\t\t\t$selectFields.= \", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx\";\n\t\t}", "\t\t// Multilang : we add translation\n\t\tif (! empty($conf->global->MAIN_MULTILANGS))\n\t\t{\n\t\t\t$sql.= \", pl.label as label_translated\";\n\t\t\t$selectFields.= \", label_translated\";\n\t\t}\n\t\t// Price by quantity\n\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))\n\t\t{\n\t\t\t$sql.= \", (SELECT pp.rowid FROM \".MAIN_DB_PREFIX.\"product_price as pp WHERE pp.fk_product = p.rowid\";\n\t\t\tif ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= \" AND price_level=\".$price_level;\n\t\t\t$sql.= \" ORDER BY date_price\";\n\t\t\t$sql.= \" DESC LIMIT 1) as price_rowid\";\n\t\t\t$sql.= \", (SELECT pp.price_by_qty FROM \".MAIN_DB_PREFIX.\"product_price as pp WHERE pp.fk_product = p.rowid\";\t// price_by_qty is 1 if some prices by qty exists in subtable\n\t\t\tif ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= \" AND price_level=\".$price_level;\n\t\t\t$sql.= \" ORDER BY date_price\";\n\t\t\t$sql.= \" DESC LIMIT 1) as price_by_qty\";\n\t\t\t$selectFields.= \", price_rowid, price_by_qty\";\n\t\t}\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product as p\";\n\t\tif (count($warehouseStatusArray))\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_stock as ps on ps.fk_product = p.rowid\";\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"entrepot as e on ps.fk_entrepot = e.rowid\";\n\t\t}", "\t\t//Price by customer\n\t\tif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {\n\t\t\t$sql.=\" LEFT JOIN \".MAIN_DB_PREFIX.\"product_customer_price as pcp ON pcp.fk_soc=\".$socid.\" AND pcp.fk_product=p.rowid\";\n\t\t}\n\t\t// Multilang : we add translation\n\t\tif (! empty($conf->global->MAIN_MULTILANGS))\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='\". $langs->getDefaultLang() .\"'\";\n\t\t}", "\t\tif (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {\n\t\t\t$sql .= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_attribute_combination pac ON pac.fk_product_child = p.rowid\";\n\t\t}", "\t\t$sql.= ' WHERE p.entity IN ('.getEntity('product').')';\n\t\tif (count($warehouseStatusArray))\n\t\t{\n\t\t\t$sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';\n\t\t}", "\t\tif (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {\n\t\t\t$sql .= \" AND pac.rowid IS NULL\";\n\t\t}", "\t\tif ($finished == 0)\n\t\t{\n\t\t\t$sql.= \" AND p.finished = \".$finished;\n\t\t}\n\t\telseif ($finished == 1)\n\t\t{\n\t\t\t$sql.= \" AND p.finished = \".$finished;\n\t\t\tif ($status >= 0) $sql.= \" AND p.tosell = \".$status;\n\t\t}\n\t\telseif ($status >= 0)\n\t\t{\n\t\t\t$sql.= \" AND p.tosell = \".$status;\n\t\t}\n\t\tif (strval($filtertype) != '') $sql.=\" AND p.fk_product_type=\".$filtertype;\n\t\t// Add criteria on ref/label\n\t\tif ($filterkey != '')\n\t\t{\n\t\t\t$sql.=' AND (';\n\t\t\t$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';\t// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on\n\t\t\t// For natural search\n\t\t\t$scrit = explode(' ', $filterkey);\n\t\t\t$i=0;\n\t\t\tif (count($scrit) > 1) $sql.=\"(\";\n\t\t\tforeach ($scrit as $crit)\n\t\t\t{\n\t\t\t\tif ($i > 0) $sql.=\" AND \";\n\t\t\t\t$sql.=\"(p.ref LIKE '\".$db->escape($prefix.$crit).\"%' OR p.label LIKE '\".$db->escape($prefix.$crit).\"%'\";\n\t\t\t\tif (! empty($conf->global->MAIN_MULTILANGS)) $sql.=\" OR pl.label LIKE '\".$db->escape($prefix.$crit).\"%'\";\n\t\t\t\t$sql.=\")\";\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tif (count($scrit) > 1) $sql.=\")\";\n\t\t \tif (! empty($conf->barcode->enabled)) $sql.= \" OR p.barcode LIKE '\".$db->escape($prefix.$filterkey).\"%'\";\n\t\t\t$sql.=')';\n\t\t}\n\t\tif (count($warehouseStatusArray))\n\t\t{\n\t\t\t$sql.= ' GROUP BY'.$selectFields;\n\t\t}\n\t\t$sql.= $db->order(\"p.ref\");\n\t\t$sql.= $db->plimit($limit, 0);", "\t\t// Build output string\n\t\tdol_syslog(get_class($this).\"::select_produits_list search product\", LOG_DEBUG);\n\t\t$result=$this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';\n\t\t\t$num = $this->db->num_rows($result);", "\t\t\t$events=null;", "\t\t\tif (! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);\n\t\t\t}", "\t\t\t$out.='<select class=\"flat'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';", "\t\t\t$textifempty='';\n\t\t\t// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.\n\t\t\t//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';\n\t\t\tif (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))\n\t\t\t{\n\t\t\t\tif ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);\n\t\t\t\telse $textifempty.=$langs->trans(\"All\");\n\t\t\t}\n\t\t\tif ($showempty) $out.='<option value=\"0\" selected>'.$textifempty.'</option>';", "\t\t\t$i = 0;\n\t\t\twhile ($num && $i < $num)\n\t\t\t{\n\t\t\t\t$opt = '';\n\t\t\t\t$optJson = array();\n\t\t\t\t$objp = $this->db->fetch_object($result);", "\t\t\t\tif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)\n\t\t\t\t{ // Price by quantity will return many prices for the same product\n\t\t\t\t\t$sql = \"SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type\";\n\t\t\t\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product_price_by_qty\";\n\t\t\t\t\t$sql.= \" WHERE fk_product_price=\".$objp->price_rowid;\n\t\t\t\t\t$sql.= \" ORDER BY quantity ASC\";", "\t\t\t\t\tdol_syslog(get_class($this).\"::select_produits_list search price by qty\", LOG_DEBUG);\n\t\t\t\t\t$result2 = $this->db->query($sql);\n\t\t\t\t\tif ($result2)\n\t\t\t\t\t{\n\t\t\t\t\t\t$nb_prices = $this->db->num_rows($result2);\n\t\t\t\t\t\t$j = 0;\n\t\t\t\t\t\twhile ($nb_prices && $j < $nb_prices) {\n\t\t\t\t\t\t\t$objp2 = $this->db->fetch_object($result2);", "\t\t\t\t\t\t\t$objp->price_by_qty_rowid = $objp2->rowid;\n\t\t\t\t\t\t\t$objp->price_by_qty_price_base_type = $objp2->price_base_type;\n\t\t\t\t\t\t\t$objp->price_by_qty_quantity = $objp2->quantity;\n\t\t\t\t\t\t\t$objp->price_by_qty_unitprice = $objp2->unitprice;\n\t\t\t\t\t\t\t$objp->price_by_qty_remise_percent = $objp2->remise_percent;\n\t\t\t\t\t\t\t// For backward compatibility\n\t\t\t\t\t\t\t$objp->quantity = $objp2->quantity;\n\t\t\t\t\t\t\t$objp->price = $objp2->price;\n\t\t\t\t\t\t\t$objp->unitprice = $objp2->unitprice;\n\t\t\t\t\t\t\t$objp->remise_percent = $objp2->remise_percent;\n\t\t\t\t\t\t\t$objp->remise = $objp2->remise;", "\t\t\t\t\t\t\t$this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);", "\t\t\t\t\t\t\t$j++;", "\t\t\t\t\t\t\t// Add new entry\n\t\t\t\t\t\t\t// \"key\" value of json key array is used by jQuery automatically as selected value\n\t\t\t\t\t\t\t// \"label\" value of json key array is used by jQuery automatically as text for combo box\n\t\t\t\t\t\t\t$out.=$opt;\n\t\t\t\t\t\t\tarray_push($outarray, $optJson);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {\n\t\t\t\t\t\t$price_product = new Product($this->db);\n\t\t\t\t\t\t$price_product->fetch($objp->rowid, '', '', 1);\n\t\t\t\t\t\t$priceparser = new PriceParser($this->db);\n\t\t\t\t\t\t$price_result = $priceparser->parseProduct($price_product);\n\t\t\t\t\t\tif ($price_result >= 0) {\n\t\t\t\t\t\t\t$objp->price = $price_result;\n\t\t\t\t\t\t\t$objp->unitprice = $price_result;\n\t\t\t\t\t\t\t//Calculate the VAT\n\t\t\t\t\t\t\t$objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));\n\t\t\t\t\t\t\t$objp->price_ttc = price2num($objp->price_ttc,'MU');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t$this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);\n\t\t\t\t\t// Add new entry\n\t\t\t\t\t// \"key\" value of json key array is used by jQuery automatically as selected value\n\t\t\t\t\t// \"label\" value of json key array is used by jQuery automatically as text for combo box\n\t\t\t\t\t$out.=$opt;\n\t\t\t\t\tarray_push($outarray, $optJson);\n\t\t\t\t}", "\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$out.='</select>';", "\t\t\t$this->db->free($result);", "\t\t\tif (empty($outputmode)) return $out;\n\t\t\treturn $outarray;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}\n\t}", "\t/**\n\t * constructProductListOption\n\t *\n\t * @param \tresultset\t$objp\t\t\t Resultset of fetch\n\t * @param \tstring\t\t$opt\t\t\t Option (var used for returned value in string option format)\n\t * @param \tstring\t\t$optJson\t\t Option (var used for returned value in json format)\n\t * @param \tint\t\t\t$price_level\t Price level\n\t * @param \tstring\t\t$selected\t\t Preselected value\n\t * @param int $hidepriceinlabel Hide price in label\n\t * @return\tvoid\n\t */\n\tprivate function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)\n\t{\n\t\tglobal $langs,$conf,$user,$db;", "\t\t$outkey='';\n\t\t$outval='';\n\t\t$outref='';\n\t\t$outlabel='';\n\t\t$outdesc='';\n\t\t$outbarcode='';\n\t\t$outtype='';\n\t\t$outprice_ht='';\n\t\t$outprice_ttc='';\n\t\t$outpricebasetype='';\n\t\t$outtva_tx='';\n\t\t$outqty=1;\n\t\t$outdiscount=0;", "\t\t$maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);", "\t\t$label=$objp->label;\n\t\tif (! empty($objp->label_translated)) $label=$objp->label_translated;\n\t\tif (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);", "\t\t$outkey=$objp->rowid;\n\t\t$outref=$objp->ref;\n\t\t$outlabel=$objp->label;\n\t\t$outdesc=$objp->description;\n\t\t$outbarcode=$objp->barcode;", "\t\t$outtype=$objp->fk_product_type;\n\t\t$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';\n\t\t$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';", "\t\t$opt = '<option value=\"'.$objp->rowid.'\"';\n\t\t$opt.= ($objp->rowid == $selected)?' selected':'';\n\t\tif (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)\n\t\t{\n\t\t\t$opt.= ' pbq=\"'.$objp->price_by_qty_rowid.'\" data-pbq=\"'.$objp->price_by_qty_rowid.'\" data-pbqqty=\"'.$objp->price_by_qty_quantity.'\" data-pbqpercent=\"'.$objp->price_by_qty_remise_percent.'\"';\n\t\t}\n\t\tif (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))\n\t\t{\n\t\t\tif ($objp->stock > 0) $opt.= ' class=\"product_line_stock_ok\"';\n\t\t\telse if ($objp->stock <= 0) $opt.= ' class=\"product_line_stock_too_low\"';\n\t\t}\n\t\t$opt.= '>';\n\t\t$opt.= $objp->ref;\n\t\tif ($outbarcode) $opt.=' ('.$outbarcode.')';\n\t\t$opt.=' - '.dol_trunc($label,$maxlengtharticle);", "\t\t$objRef = $objp->ref;\n\t\tif (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);\n\t\t$outval.=$objRef;\n\t\tif ($outbarcode) $outval.=' ('.$outbarcode.')';\n\t\t$outval.=' - '.dol_trunc($label,$maxlengtharticle);", "\t\t$found=0;", "\t\t// Multiprice\n\t\tif (empty($hidepriceinlabel) && $price_level >= 1 && $conf->global->PRODUIT_MULTIPRICES)\t\t// If we need a particular price level (from 1 to 6)\n\t\t{\n\t\t\t$sql = \"SELECT price, price_ttc, price_base_type, tva_tx\";\n\t\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product_price\";\n\t\t\t$sql.= \" WHERE fk_product='\".$objp->rowid.\"'\";\n\t\t\t$sql.= \" AND entity IN (\".getEntity('productprice').\")\";\n\t\t\t$sql.= \" AND price_level=\".$price_level;\n\t\t\t$sql.= \" ORDER BY date_price DESC, rowid DESC\"; // Warning DESC must be both on date_price and rowid.\n\t\t\t$sql.= \" LIMIT 1\";", "\t\t\tdol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);\n\t\t\t$result2 = $this->db->query($sql);\n\t\t\tif ($result2)\n\t\t\t{\n\t\t\t\t$objp2 = $this->db->fetch_object($result2);\n\t\t\t\tif ($objp2)\n\t\t\t\t{\n\t\t\t\t\t$found=1;\n\t\t\t\t\tif ($objp2->price_base_type == 'HT')\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"HT\");\n\t\t\t\t\t\t$outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"HT\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"TTC\");\n\t\t\t\t\t\t$outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"TTC\");\n\t\t\t\t\t}\n\t\t\t\t\t$outprice_ht=price($objp2->price);\n\t\t\t\t\t$outprice_ttc=price($objp2->price_ttc);\n\t\t\t\t\t$outpricebasetype=$objp2->price_base_type;\n\t\t\t\t\t$outtva_tx=$objp2->tva_tx;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdol_print_error($this->db);\n\t\t\t}\n\t\t}", "\t\t// Price by quantity\n\t\tif (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))\n\t\t{\n\t\t\t$found = 1;\n\t\t\t$outqty=$objp->quantity;\n\t\t\t$outdiscount=$objp->remise_percent;\n\t\t\tif ($objp->quantity == 1)\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t$outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t$opt.= $langs->trans(\"Unit\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t$outval.=$langs->transnoentities(\"Unit\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t$opt.= $langs->trans(\"Units\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t$outval.=$langs->transnoentities(\"Units\");\n\t\t\t}", "\t\t\t$outprice_ht=price($objp->unitprice);\n\t\t\t$outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));\n\t\t\t$outpricebasetype=$objp->price_base_type;\n\t\t\t$outtva_tx=$objp->tva_tx;\n\t\t}\n\t\tif (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)\n\t\t{\n\t\t\t$opt.=\" (\".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\".$langs->trans(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t$outval.=\" (\".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency).\"/\".$langs->transnoentities(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t}\n\t\tif (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)\n\t\t{\n\t\t\t$opt.=\" - \".$langs->trans(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t\t$outval.=\" - \".$langs->transnoentities(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t}", "\t\t// Price by customer\n\t\tif (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))\n\t\t{\n\t\t\tif (!empty($objp->idprodcustprice))\n\t\t\t{\n\t\t\t\t$found = 1;", "\t\t\t\tif ($objp->custprice_base_type == 'HT')\n\t\t\t\t{\n\t\t\t\t\t$opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"HT\");\n\t\t\t\t\t$outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"HT\");\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"TTC\");\n\t\t\t\t\t$outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"TTC\");\n\t\t\t\t}", "\t\t\t\t$outprice_ht=price($objp->custprice);\n\t\t\t\t$outprice_ttc=price($objp->custprice_ttc);\n\t\t\t\t$outpricebasetype=$objp->custprice_base_type;\n\t\t\t\t$outtva_tx=$objp->custtva_tx;\n\t\t\t}\n\t\t}", "\t\t// If level no defined or multiprice not found, we used the default price\n\t\tif (empty($hidepriceinlabel) && ! $found)\n\t\t{\n\t\t\tif ($objp->price_base_type == 'HT')\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"HT\");\n\t\t\t\t$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"HT\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans(\"TTC\");\n\t\t\t\t$outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities(\"TTC\");\n\t\t\t}\n\t\t\t$outprice_ht=price($objp->price);\n\t\t\t$outprice_ttc=price($objp->price_ttc);\n\t\t\t$outpricebasetype=$objp->price_base_type;\n\t\t\t$outtva_tx=$objp->tva_tx;\n\t\t}", "\t\tif (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)\n\t\t{\n\t\t\t$opt.= ' - '.$langs->trans(\"Stock\").':'.$objp->stock;", "\t\t\tif ($objp->stock > 0) {\n\t\t\t\t$outval.= ' - <span class=\"product_line_stock_ok\">'.$langs->transnoentities(\"Stock\").':'.$objp->stock.'</span>';\n\t\t\t}elseif ($objp->stock <= 0) {\n\t\t\t\t$outval.= ' - <span class=\"product_line_stock_too_low\">'.$langs->transnoentities(\"Stock\").':'.$objp->stock.'</span>';\n\t\t\t}\n\t\t}", "\t\tif ($outdurationvalue && $outdurationunit)\n\t\t{\n\t\t\t$da=array(\"h\"=>$langs->trans(\"Hour\"),\"d\"=>$langs->trans(\"Day\"),\"w\"=>$langs->trans(\"Week\"),\"m\"=>$langs->trans(\"Month\"),\"y\"=>$langs->trans(\"Year\"));\n\t\t\tif (isset($da[$outdurationunit]))\n\t\t\t{\n\t\t\t\t$key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');\n\t\t\t\t$opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);\n\t\t\t\t$outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);\n\t\t\t}\n\t\t}", "\t\t$opt.= \"</option>\\n\";\n\t\t$optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);\n\t}", "\t/**\n\t *\tReturn list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)\n\t *\n\t *\t@param\tint\t\t$socid\t\t\tId third party\n\t *\t@param string\t$selected Preselected product\n\t *\t@param string\t$htmlname Name of HTML Select\n\t * @param\tstring\t$filtertype Filter on product type (''=nofilter, 0=product, 1=service)\n\t *\t@param string\t$filtre\t\t\tFor a SQL filter\n\t *\t@param\tarray\t$ajaxoptions\tOptions for ajax_autocompleter\n\t * @param\tint\t\t$hidelabel\t\tHide label (0=no, 1=yes)\n\t * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices\n\t *\t@return\tvoid\n\t */\n\tfunction select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)\n\t{\n\t\tglobal $langs,$conf;\n\t\tglobal $price_level, $status, $finished;", "\t\t$selected_input_value='';\n\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))\n\t\t{\n\t\t\tif ($selected > 0)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\n\t\t\t\t$producttmpselect = new Product($this->db);\n\t\t\t\t$producttmpselect->fetch($selected);\n\t\t\t\t$selected_input_value=$producttmpselect->ref;\n\t\t\t\tunset($producttmpselect);\n\t\t\t}", "\t\t\t// mode=2 means suppliers products\n\t\t\t$urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;\n\t\t\tprint ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);\n\t\t\tprint ($hidelabel?'':$langs->trans(\"RefOrLabel\").' : ').'<input type=\"text\" size=\"20\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$selected_input_value.'\">';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprint $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of suppliers products\n\t *\n\t *\t@param\tint\t\t$socid \t\tId societe fournisseur (0 pour aucun filtre)\n\t *\t@param int\t\t$selected Produit pre-selectionne\n\t *\t@param string\t$htmlname Nom de la zone select\n\t * @param\tstring\t$filtertype Filter on product type (''=nofilter, 0=product, 1=service)\n\t *\t@param string\t$filtre Pour filtre sql\n\t *\t@param string\t$filterkey Filtre des produits\n\t * @param int\t\t$statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)\n\t * @param int\t\t$outputmode 0=HTML select string, 1=Array\n\t * @param int $limit Limit of line number\n\t * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices\n\t * @return array \t\tArray of keys for json\n\t */\n\tfunction select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)\n\t{\n\t\tglobal $langs,$conf,$db;", "\t\t$out='';\n\t\t$outarray=array();", "\t\t$langs->load('stocks');", "\t\t$sql = \"SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,\";\n\t\t$sql.= \" pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,\";\n\t\t$sql.= \" pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,\";\n\t\t$sql.= \" pfp.supplier_reputation\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product as p\";\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_fournisseur_price as pfp ON p.rowid = pfp.fk_product\";\n\t\tif ($socid) $sql.= \" AND pfp.fk_soc = \".$socid;\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"societe as s ON pfp.fk_soc = s.rowid\";\n\t\t$sql.= \" WHERE p.entity IN (\".getEntity('product').\")\";\n\t\t$sql.= \" AND p.tobuy = 1\";\n\t\tif (strval($filtertype) != '') $sql.=\" AND p.fk_product_type=\".$this->db->escape($filtertype);\n\t\tif (! empty($filtre)) $sql.=\" \".$filtre;\n\t\t// Add criteria on ref/label\n\t\tif ($filterkey != '')\n\t\t{\n\t\t\t$sql.=' AND (';\n\t\t\t$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';\t// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on\n\t\t\t// For natural search\n\t\t\t$scrit = explode(' ', $filterkey);\n\t\t\t$i=0;\n\t\t\tif (count($scrit) > 1) $sql.=\"(\";\n\t\t\tforeach ($scrit as $crit)\n\t\t\t{\n\t\t\t\tif ($i > 0) $sql.=\" AND \";\n\t\t\t\t$sql.=\"(pfp.ref_fourn LIKE '\".$this->db->escape($prefix.$crit).\"%' OR p.ref LIKE '\".$this->db->escape($prefix.$crit).\"%' OR p.label LIKE '\".$this->db->escape($prefix.$crit).\"%')\";\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tif (count($scrit) > 1) $sql.=\")\";\n\t\t\tif (! empty($conf->barcode->enabled)) $sql.= \" OR p.barcode LIKE '\".$this->db->escape($prefix.$filterkey).\"%'\";\n\t\t\t$sql.=')';\n\t\t}\n\t\t$sql.= \" ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC\";\n\t\t$sql.= $db->plimit($limit, 0);", "\t\t// Build output string", "\t\tdol_syslog(get_class($this).\"::select_produits_fournisseurs_list\", LOG_DEBUG);\n\t\t$result=$this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';", "\t\t\t$num = $this->db->num_rows($result);", "\t\t\t//$out.='<select class=\"flat\" id=\"select'.$htmlname.'\" name=\"'.$htmlname.'\">';\t// remove select to have id same with combo and ajax\n\t\t\t$out.='<select class=\"flat maxwidthonsmartphone\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\">';\n\t\t\tif (! $selected) $out.='<option value=\"0\" selected>&nbsp;</option>';\n\t\t\telse $out.='<option value=\"0\">&nbsp;</option>';", "\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$objp = $this->db->fetch_object($result);", "\t\t\t\t$outkey=$objp->idprodfournprice; // id in table of price\n\t\t\t\tif (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product", "\t\t\t\t$outref=$objp->ref;\n\t\t\t\t$outval='';\n\t\t\t\t$outqty=1;\n\t\t\t\t$outdiscount=0;\n\t\t\t\t$outtype=$objp->fk_product_type;\n\t\t\t\t$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';\n\t\t\t\t$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';", "\t\t\t\t$opt = '<option value=\"'.$outkey.'\"';\n\t\t\t\tif ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';\n\t\t\t\tif (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';\n\t\t\t\t$opt.= '>';", "\t\t\t\t$objRef = $objp->ref;\n\t\t\t\tif ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);\n\t\t\t\t$objRefFourn = $objp->ref_fourn;\n\t\t\t\tif ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);\n\t\t\t\t$label = $objp->label;\n\t\t\t\tif ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);", "\t\t\t\t$opt.=$objp->ref;\n\t\t\t\tif (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))\n\t\t\t\t\t$opt.=' ('.$objp->ref_fourn.')';\n\t\t\t\t$opt.=' - ';\n\t\t\t\t$outval.=$objRef;\n\t\t\t\tif (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))\n\t\t\t\t\t$outval.=' ('.$objRefFourn.')';\n\t\t\t\t$outval.=' - ';\n\t\t\t\t$opt.=dol_trunc($label, 72).' - ';\n\t\t\t\t$outval.=dol_trunc($label, 72).' - ';", "\t\t\t\tif (! empty($objp->idprodfournprice))\n\t\t\t\t{\n\t\t\t\t\t$outqty=$objp->quantity;\n\t\t\t\t\t$outdiscount=$objp->remise_percent;\n\t\t\t\t\tif (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {\n\t\t\t\t\t\t$prod_supplier = new ProductFournisseur($this->db);\n\t\t\t\t\t\t$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;\n\t\t\t\t\t\t$prod_supplier->id = $objp->fk_product;\n\t\t\t\t\t\t$prod_supplier->fourn_qty = $objp->quantity;\n\t\t\t\t\t\t$prod_supplier->fourn_tva_tx = $objp->tva_tx;\n\t\t\t\t\t\t$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;\n\t\t\t\t\t\t$priceparser = new PriceParser($this->db);\n\t\t\t\t\t\t$price_result = $priceparser->parseProductSupplier($prod_supplier);\n\t\t\t\t\t\tif ($price_result >= 0) {\n\t\t\t\t\t\t\t$objp->fprice = $price_result;\n\t\t\t\t\t\t\tif ($objp->quantity >= 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$objp->unitprice = $objp->fprice / $objp->quantity;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->quantity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t\t\t$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t\t\t$opt.= $langs->trans(\"Unit\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t\t$outval.=$langs->transnoentities(\"Unit\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t\t\t$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency).\"/\".$objp->quantity;\n\t\t\t\t\t\t$opt.= ' '.$langs->trans(\"Units\");\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t\t$outval.= ' '.$langs->transnoentities(\"Units\");\n\t\t\t\t\t}", "\t\t\t\t\tif ($objp->quantity >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.=\" (\".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\".$langs->trans(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t\t$outval.=\" (\".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency).\"/\".$langs->transnoentities(\"Unit\").\")\";\t// Do not use strtolower because it breaks utf8 encoding\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->remise_percent >= 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.=\" - \".$langs->trans(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t\t\t\t\t$outval.=\" - \".$langs->transnoentities(\"Discount\").\" : \".vatrate($objp->remise_percent).' %';\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->duration)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt .= \" - \".$objp->duration;\n\t\t\t\t\t\t$outval.=\" - \".$objp->duration;\n\t\t\t\t\t}\n\t\t\t\t\tif (! $socid)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt .= \" - \".dol_trunc($objp->name,8);\n\t\t\t\t\t\t$outval.=\" - \".dol_trunc($objp->name,8);\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->supplier_reputation)\n\t\t\t\t\t{\n\t\t\t\t\t\t//TODO dictionary\n\t\t\t\t\t\t$reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));", "\t\t\t\t\t\t$opt .= \" - \".$reputations[$objp->supplier_reputation];\n\t\t\t\t\t\t$outval.=\" - \".$reputations[$objp->supplier_reputation];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t\t$outval.=$langs->transnoentities(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t}\n\t\t\t\t\telse // No supplier price defined for product, even on other suppliers\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t\t$outval.=$langs->transnoentities(\"NoPriceDefinedForThisSupplier\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$opt .= \"</option>\\n\";", "\n\t\t\t\t// Add new entry\n\t\t\t\t// \"key\" value of json key array is used by jQuery automatically as selected value\n\t\t\t\t// \"label\" value of json key array is used by jQuery automatically as text for combo box\n\t\t\t\t$out.=$opt;\n\t\t\t\tarray_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));\n\t\t\t\t// Exemple of var_dump $outarray\n\t\t\t\t// array(1) {[0]=>array(6) {[key\"]=>string(1) \"2\" [\"value\"]=>string(3) \"ppp\"\n\t\t\t\t// [\"label\"]=>string(76) \"ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)\"\n\t\t\t\t// \t [\"qty\"]=>string(1) \"1\" [\"discount\"]=>string(1) \"0\" [\"disabled\"]=>bool(false)\n\t\t\t\t//}\n\t\t\t\t//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));\n\t\t\t\t//$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');\n\t\t\t\t//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));", "\t\t\t\t$i++;\n\t\t\t}\n\t\t\t$out.='</select>';", "\t\t\t$this->db->free($result);", "\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t$out.=ajax_combobox($htmlname);", "\t\t\tif (empty($outputmode)) return $out;\n\t\t\treturn $outarray;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of suppliers prices for a product\n\t *\n\t * @param\t int\t\t$productid \tId of product\n\t * @param string\t$htmlname \tName of HTML field\n\t * @param int\t\t$selected_supplier Pre-selected supplier if more than 1 result\n\t * @return\t void\n\t */\n\tfunction select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')\n\t{\n\t\tglobal $langs,$conf;", "\t\t$langs->load('stocks');", "\t\t$sql = \"SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,\";\n\t\t$sql.= \" pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,\";\n\t\t$sql.= \" pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"product as p\";\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"product_fournisseur_price as pfp ON p.rowid = pfp.fk_product\";\n\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"societe as s ON pfp.fk_soc = s.rowid\";\n\t\t$sql.= \" WHERE pfp.entity IN (\".getEntity('productprice').\")\";\n\t\t$sql.= \" AND p.tobuy = 1\";\n\t\t$sql.= \" AND s.fournisseur = 1\";\n\t\t$sql.= \" AND p.rowid = \".$productid;\n\t\t$sql.= \" ORDER BY s.nom, pfp.ref_fourn DESC\";", "\t\tdol_syslog(get_class($this).\"::select_product_fourn_price\", LOG_DEBUG);\n\t\t$result=$this->db->query($sql);", "\t\tif ($result)\n\t\t{\n\t\t\t$num = $this->db->num_rows($result);", "\t\t\t$form = '<select class=\"flat\" name=\"'.$htmlname.'\">';", "\t\t\tif (! $num)\n\t\t\t{\n\t\t\t\t$form.= '<option value=\"0\">-- '.$langs->trans(\"NoSupplierPriceDefinedForThisProduct\").' --</option>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';\n\t\t\t\t$form.= '<option value=\"0\">&nbsp;</option>';", "\t\t\t\t$i = 0;\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$objp = $this->db->fetch_object($result);", "\t\t\t\t\t$opt = '<option value=\"'.$objp->idprodfournprice.'\"';\n\t\t\t\t\t//if there is only one supplier, preselect it\n\t\t\t\t\tif($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {\n\t\t\t\t\t\t$opt .= ' selected';\n\t\t\t\t\t}\n\t\t\t\t\t$opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';", "\t\t\t\t\tif (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {\n\t\t\t\t\t\t$prod_supplier = new ProductFournisseur($this->db);\n\t\t\t\t\t\t$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;\n\t\t\t\t\t\t$prod_supplier->id = $productid;\n\t\t\t\t\t\t$prod_supplier->fourn_qty = $objp->quantity;\n\t\t\t\t\t\t$prod_supplier->fourn_tva_tx = $objp->tva_tx;\n\t\t\t\t\t\t$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;\n\t\t\t\t\t\t$priceparser = new PriceParser($this->db);\n\t\t\t\t\t\t$price_result = $priceparser->parseProductSupplier($prod_supplier);\n\t\t\t\t\t\tif ($price_result >= 0) {\n\t\t\t\t\t\t\t$objp->fprice = $price_result;\n\t\t\t\t\t\t\tif ($objp->quantity >= 1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$objp->unitprice = $objp->fprice / $objp->quantity;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->quantity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency).\"/\";\n\t\t\t\t\t}", "\t\t\t\t\t$opt.= $objp->quantity.' ';", "\t\t\t\t\tif ($objp->quantity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"Unit\");\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.= $langs->trans(\"Units\");\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->quantity > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$opt.=\" - \";\n\t\t\t\t\t\t$opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency).\"/\".$langs->trans(\"Unit\");\n\t\t\t\t\t}\n\t\t\t\t\tif ($objp->duration) $opt .= \" - \".$objp->duration;\n\t\t\t\t\t$opt .= \"</option>\\n\";", "\t\t\t\t\t$form.= $opt;\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}", "\t\t\t$form.= '</select>';\n\t\t\t$this->db->free($result);\n\t\t\treturn $form;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Return list of delivery address\n\t *\n\t * @param string\t$selected \tId contact pre-selectionn\n\t * @param int\t\t$socid\t\t\t\tId of company\n\t * @param string\t$htmlname \tName of HTML field\n\t * @param int\t\t$showempty \tAdd an empty field\n\t * @return\tinteger|null\n\t */\n\tfunction select_address($selected, $socid, $htmlname='address_id',$showempty=0)\n\t{\n\t\t// On recherche les utilisateurs\n\t\t$sql = \"SELECT a.rowid, a.label\";\n\t\t$sql .= \" FROM \".MAIN_DB_PREFIX .\"societe_address as a\";\n\t\t$sql .= \" WHERE a.fk_soc = \".$socid;\n\t\t$sql .= \" ORDER BY a.label ASC\";", "\t\tdol_syslog(get_class($this).\"::select_address\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\t\tif ($showempty) print '<option value=\"0\">&nbsp;</option>';\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t\tif ($selected && $selected == $obj->rowid)\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>'.$obj->label.'</option>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">'.$obj->label.'</option>';\n\t\t\t\t\t}\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tprint '</select>';\n\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\n\t/**\n\t * Load into cache list of payment terms\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_conditions_paiements()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_conditions_paiements);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$sql = \"SELECT rowid, code, libelle as label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.'c_payment_term';\n\t\t$sql.= \" WHERE entity = \" . getEntity('c_payment_term');\n\t\t$sql.= \" AND active > 0\";\n\t\t$sql.= \" ORDER BY sortorder\";", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->trans(\"PaymentConditionShort\".$obj->code)!=(\"PaymentConditionShort\".$obj->code)?$langs->trans(\"PaymentConditionShort\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;\n\t\t\t\t$this->cache_conditions_paiements[$obj->rowid]['label']=$label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t//$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);\t\t// We use the field sortorder of table", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t * Charge dans cache la liste des délais de livraison possibles\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_availability()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_availability);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$langs->load('propal');", "\t\t$sql = \"SELECT rowid, code, label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.'c_availability';\n\t\t$sql.= \" WHERE active > 0\";", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->trans(\"AvailabilityType\".$obj->code)!=(\"AvailabilityType\".$obj->code)?$langs->trans(\"AvailabilityType\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$this->cache_availability[$obj->rowid]['code'] =$obj->code;\n\t\t\t\t$this->cache_availability[$obj->rowid]['label']=$label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t * Retourne la liste des types de delais de livraison possibles\n\t *\n\t * @param\tint\t\t$selected Id du type de delais pre-selectionne\n\t * @param string\t$htmlname Nom de la zone select\n\t * @param string\t$filtertype To add a filter\n\t *\t\t@param\tint\t\t$addempty\t\tAdd empty entry\n\t *\t\t@return\tvoid\n\t */\n\tfunction selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)\n\t{\n\t\tglobal $langs,$user;", "\t\t$this->load_cache_availability();", "\t\tdol_syslog(__METHOD__.\" selected=\".$selected.\", htmlname=\".$htmlname, LOG_DEBUG);", "\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\tif ($addempty) print '<option value=\"0\">&nbsp;</option>';\n\t\tforeach($this->cache_availability as $id => $arrayavailability)\n\t\t{\n\t\t\tif ($selected == $id)\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\">';\n\t\t\t}\n\t\t\tprint $arrayavailability['label'];\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\t/**\n\t * Load into cache cache_demand_reason, array of input reasons\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction loadCacheInputReason()\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_demand_reason);\n\t\tif ($num > 0) return 0; // Cache already loaded", "\t\t$sql = \"SELECT rowid, code, label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.'c_input_reason';\n\t\t$sql.= \" WHERE active > 0\";", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\t$tmparray=array();\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->trans(\"DemandReasonType\".$obj->code)!=(\"DemandReasonType\".$obj->code)?$langs->trans(\"DemandReasonType\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$tmparray[$obj->rowid]['id'] =$obj->rowid;\n\t\t\t\t$tmparray[$obj->rowid]['code'] =$obj->code;\n\t\t\t\t$tmparray[$obj->rowid]['label']=$label;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);", "\t\t\tunset($tmparray);\n\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\t/**\n\t *\tReturn list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)\n\t * List found into table c_input_reason loaded by loadCacheInputReason\n\t *\n\t * @param\tint\t\t$selected Id or code of type origin to select by default\n\t * @param string\t$htmlname Nom de la zone select\n\t * @param string\t$exclude To exclude a code value (Example: SRC_PROP)\n\t *\t@param\tint\t\t$addempty\t\t Add an empty entry\n\t *\t@return\tvoid\n\t */\n\tfunction selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)\n\t{\n\t\tglobal $langs,$user;", "\t\t$this->loadCacheInputReason();", "\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\tif ($addempty) print '<option value=\"0\"'.(empty($selected)?' selected':'').'>&nbsp;</option>';\n\t\tforeach($this->cache_demand_reason as $id => $arraydemandreason)\n\t\t{\n\t\t\tif ($arraydemandreason['code']==$exclude) continue;", "\t\t\tif ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$arraydemandreason['id'].'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$arraydemandreason['id'].'\">';\n\t\t\t}\n\t\t\tprint $arraydemandreason['label'];\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\t/**\n\t * Charge dans cache la liste des types de paiements possibles\n\t *\n\t * @return int Nb of lines loaded, <0 if KO\n\t */\n\tfunction load_cache_types_paiements()\n\t{\n\t\tglobal $langs;", "\t\t$num=count($this->cache_types_paiements);\n\t\tif ($num > 0) return $num; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$this->cache_types_paiements = array();", "\t\t$sql = \"SELECT id, code, libelle as label, type, active\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_paiement\";\n\t\t$sql.= \" WHERE entity IN (\".getEntity('c_paiement').\")\";\n\t\t//if ($active >= 0) $sql.= \" AND active = \".$active;", "\t\t$resql = $this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($resql);", "\t\t\t\t// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut\n\t\t\t\t$label=($langs->transnoentitiesnoconv(\"PaymentTypeShort\".$obj->code)!=(\"PaymentTypeShort\".$obj->code)?$langs->transnoentitiesnoconv(\"PaymentTypeShort\".$obj->code):($obj->label!='-'?$obj->label:''));\n\t\t\t\t$this->cache_types_paiements[$obj->id]['id'] =$obj->id;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['code'] =$obj->code;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['label']=$label;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['type'] =$obj->type;\n\t\t\t\t$this->cache_types_paiements[$obj->id]['active'] =$obj->active;\n\t\t\t\t$i++;\n\t\t\t}", "\t\t\t$this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);", "\t\t\treturn $num;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t\treturn -1;\n\t\t}\n\t}", "\n\t/**\n\t * Return list of payment modes.\n\t * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.\n\t * See instead to force the default value by the caller.\n\t *\n\t * @param\tint\t\t$selected\t\tId of payment term to preselect by default\n\t * @param\tstring\t$htmlname\t\tNom de la zone select\n\t * @param\tint\t\t$filtertype\t\tNot used\n\t *\t\t@param\tint\t\t$addempty\t\tAdd an empty entry\n\t * \t\t@param\tint\t\t$noinfoadmin\t\t0=Add admin info, 1=Disable admin info\n\t * \t\t@param\tstring\t$morecss\t\t\tAdd more CSS on select tag\n\t *\t\t@return\tvoid\n\t */\n\tfunction select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')\n\t{\n\t\tglobal $langs, $user, $conf;", "\t\tdol_syslog(__METHOD__.\" selected=\".$selected.\", htmlname=\".$htmlname, LOG_DEBUG);", "\t\t$this->load_cache_conditions_paiements();", "\t\t// Set default value if not already set by caller\n\t\tif (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;", "\t\tprint '<select id=\"'.$htmlname.'\" class=\"flat selectpaymentterms'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\">';\n\t\tif ($addempty) print '<option value=\"0\">&nbsp;</option>';\n\t\tforeach($this->cache_conditions_paiements as $id => $arrayconditions)\n\t\t{\n\t\t\tif ($selected == $id)\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint '<option value=\"'.$id.'\">';\n\t\t\t}\n\t\t\tprint $arrayconditions['label'];\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\n\t/**\n\t * Return list of payment methods\n\t *\n\t * @param\tstring\t$selected Id du mode de paiement pre-selectionne\n\t * @param string\t$htmlname Nom de la zone select\n\t * @param string\t$filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))\n\t * @param int\t\t$format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code\n\t * @param int\t\t$empty\t\t\t1=peut etre vide, 0 sinon\n\t * \t\t@param\tint\t\t$noadmininfo\t0=Add admin info, 1=Disable admin info\n\t * @param int\t\t$maxlength Max length of label\n\t * @param int $active Active or not, -1 = all\n\t * @param string $morecss Add more CSS on select tag\n\t * \t\t@return\tvoid\n\t */\n\tfunction select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')\n\t{\n\t\tglobal $langs,$user;", "\t\tdol_syslog(__METHOD__.\" \".$selected.\", \".$htmlname.\", \".$filtertype.\", \".$format, LOG_DEBUG);", "\t\t$filterarray=array();\n\t\tif ($filtertype == 'CRDT') \t$filterarray=array(0,2,3);\n\t\telseif ($filtertype == 'DBIT') \t$filterarray=array(1,2,3);\n\t\telseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);", "\t\t$this->load_cache_types_paiements();", "\t\tprint '<select id=\"select'.$htmlname.'\" class=\"flat selectpaymenttypes'.($morecss?' '.$morecss:'').'\" name=\"'.$htmlname.'\">';\n\t\tif ($empty) print '<option value=\"\">&nbsp;</option>';\n\t\tforeach($this->cache_types_paiements as $id => $arraytypes)\n\t\t{\n\t\t\t// If not good status\n\t\t\tif ($active >= 0 && $arraytypes['active'] != $active) continue;", "\t\t\t// On passe si on a demande de filtrer sur des modes de paiments particuliers\n\t\t\tif (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;", "\t\t\t// We discard empty line if showempty is on because an empty line has already been output.\n\t\t\tif ($empty && empty($arraytypes['code'])) continue;", "\t\t\tif ($format == 0) print '<option value=\"'.$id.'\"';\n\t\t\tif ($format == 1) print '<option value=\"'.$arraytypes['code'].'\"';\n\t\t\tif ($format == 2) print '<option value=\"'.$arraytypes['code'].'\"';\n\t\t\tif ($format == 3) print '<option value=\"'.$id.'\"';\n\t\t\t// Si selected est text, on compare avec code, sinon avec id\n\t\t\tif (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';\n\t\t\telseif ($selected == $id) print ' selected';\n\t\t\tprint '>';\n\t\t\tif ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);\n\t\t\tif ($format == 1) $value=$arraytypes['code'];\n\t\t\tif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);\n\t\t\tif ($format == 3) $value=$arraytypes['code'];\n\t\t\tprint $value?$value:'&nbsp;';\n\t\t\tprint '</option>';\n\t\t}\n\t\tprint '</select>';\n\t\tif ($user->admin && ! $noadmininfo) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t}", "\n\t/**\n\t * Selection HT or TTC\n\t *\n\t * @param\tstring\t$selected Id pre-selectionne\n\t * @param string\t$htmlname Nom de la zone select\n\t * \t@return\tstring\t\t\t\t\tCode of HTML select to chose tax or not\n\t */\n\tfunction selectPriceBaseType($selected='',$htmlname='price_base_type')\n\t{\n\t\tglobal $langs;", "\t\t$return='';", "\t\t$return.= '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\t$options = array(\n\t\t\t'HT'=>$langs->trans(\"HT\"),\n\t\t\t'TTC'=>$langs->trans(\"TTC\")\n\t\t);\n\t\tforeach($options as $id => $value)\n\t\t{\n\t\t\tif ($selected == $id)\n\t\t\t{\n\t\t\t\t$return.= '<option value=\"'.$id.'\" selected>'.$value;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$return.= '<option value=\"'.$id.'\">'.$value;\n\t\t\t}\n\t\t\t$return.= '</option>';\n\t\t}\n\t\t$return.= '</select>';", "\t\treturn $return;\n\t}", "\t/**\n\t * Return a HTML select list of shipping mode\n\t *\n\t * @param\tstring\t$selected Id shipping mode pre-selected\n\t * @param string\t$htmlname Name of select zone\n\t * @param string\t$filtre To filter list\n\t * @param int\t\t$useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @param string\t$moreattrib To add more attribute on select\n\t * \t@return\tvoid\n\t */\n\tfunction selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')\n\t{\n\t\tglobal $langs, $conf, $user;", "\t\t$langs->load(\"admin\");\n\t\t$langs->load(\"deliveries\");", "\t\t$sql = \"SELECT rowid, code, libelle as label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_shipment_mode\";\n\t\t$sql.= \" WHERE active > 0\";\n\t\tif ($filtre) $sql.=\" AND \".$filtre;\n\t\t$sql.= \" ORDER BY libelle ASC\";", "\t\tdol_syslog(get_class($this).\"::selectShippingMode\", LOG_DEBUG);\n\t\t$result = $this->db->query($sql);\n\t\tif ($result) {\n\t\t\t$num = $this->db->num_rows($result);\n\t\t\t$i = 0;\n\t\t\tif ($num) {\n\t\t\t\tprint '<select id=\"select'.$htmlname.'\" class=\"flat selectshippingmethod\" name=\"'.$htmlname.'\"'.($moreattrib?' '.$moreattrib:'').'>';\n\t\t\t\tif ($useempty == 1 || ($useempty == 2 && $num > 1)) {\n\t\t\t\t\tprint '<option value=\"-1\">&nbsp;</option>';\n\t\t\t\t}\n\t\t\t\twhile ($i < $num) {\n\t\t\t\t\t$obj = $this->db->fetch_object($result);\n\t\t\t\t\tif ($selected == $obj->rowid) {\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">';\n\t\t\t\t\t}\n\t\t\t\t\tprint ($langs->trans(\"SendingMethod\".strtoupper($obj->code)) != \"SendingMethod\".strtoupper($obj->code)) ? $langs->trans(\"SendingMethod\".strtoupper($obj->code)) : $obj->label;\n\t\t\t\t\tprint '</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t\tprint \"</select>\";\n\t\t\t\tif ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t\t\t} else {\n\t\t\t\tprint $langs->trans(\"NoShippingMethodDefined\");\n\t\t\t}\n\t\t} else {\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Display form to select shipping mode\n\t *\n\t * @param\tstring\t$page Page\n\t * @param int\t\t$selected Id of shipping mode\n\t * @param string\t$htmlname Name of select html field\n\t * @param int\t\t$addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @return\tvoid\n\t */\n\tfunction formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)\n\t{\n\t\tglobal $langs, $db;", "\t\t$langs->load(\"deliveries\");", "\t\tif ($htmlname != \"none\") {\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setshippingmethod\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->selectShippingMethod($selected, $htmlname, '', $addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t} else {\n\t\t\tif ($selected) {\n\t\t\t\t$code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');\n\t\t\t\tprint $langs->trans(\"SendingMethod\".strtoupper($code));\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Creates HTML last in cycle situation invoices selector\n\t *\n\t * @param string $selected \t\tPreselected ID\n\t * @param int $socid \t\tCompany ID\n\t *\n\t * @return string HTML select\n\t */\n\tfunction selectSituationInvoices($selected = '', $socid = 0)\n\t{\n\t\tglobal $langs;", "\t\t$langs->load('bills');", "\t\t$opt = '<option value =\"\" selected></option>';\n\t\t$sql = 'SELECT rowid, facnumber, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';\n\t\t$sql.= ' ORDER by situation_cycle_ref, situation_counter desc';\n\t\t$resql = $this->db->query($sql);\n\t\tif ($resql && $this->db->num_rows($resql) > 0) {\n\t\t\t// Last seen cycle\n\t\t\t$ref = 0;\n\t\t\twhile ($res = $this->db->fetch_array($resql, MYSQL_NUM)) {\n\t\t\t\t//Same company ?\n\t\t\t\tif ($socid == $res[5]) {\n\t\t\t\t\t//Same cycle ?\n\t\t\t\t\tif ($res[2] != $ref) {\n\t\t\t\t\t\t// Just seen this cycle\n\t\t\t\t\t\t$ref = $res[2];\n\t\t\t\t\t\t//not final ?\n\t\t\t\t\t\tif ($res[4] != 1) {\n\t\t\t\t\t\t\t//Not prov?\n\t\t\t\t\t\t\tif (substr($res[1], 1, 4) != 'PROV') {\n\t\t\t\t\t\t\t\tif ($selected == $res[0]) {\n\t\t\t\t\t\t\t\t\t$opt .= '<option value=\"' . $res[0] . '\" selected>' . $res[1] . '</option>';\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t$opt .= '<option value=\"' . $res[0] . '\">' . $res[1] . '</option>';\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\tdol_syslog(\"Error sql=\" . $sql . \", error=\" . $this->error, LOG_ERR);\n\t\t}\n\t\tif ($opt == '<option value =\"\" selected></option>')\n\t\t{\n\t\t\t$opt = '<option value =\"0\" selected>' . $langs->trans('NoSituations') . '</option>';\n\t\t}\n\t\treturn $opt;\n\t}", "\t/**\n\t * Creates HTML units selector (code => label)\n\t *\n\t * @param\tstring\t$selected Preselected Unit ID\n\t * @param string\t$htmlname Select name\n\t * @param\tint\t\t$showempty\t\tAdd a nempty line\n\t * \t\t@return\tstring HTML select\n\t */\n\tfunction selectUnits($selected = '', $htmlname = 'units', $showempty=0)\n\t{\n\t\tglobal $langs;", "\t\t$langs->load('products');", "\t\t$return= '<select class=\"flat\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\">';", "\t\t$sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';\n\t\t$sql.= ' WHERE active > 0';", "\t\t$resql = $this->db->query($sql);\n\t\tif($resql && $this->db->num_rows($resql) > 0)\n\t\t{\n\t\t\tif ($showempty) $return .= '<option value=\"none\"></option>';", "\t\t\twhile($res = $this->db->fetch_object($resql))\n\t\t\t{\n\t\t\t\tif ($selected == $res->rowid)\n\t\t\t\t{\n\t\t\t\t\t$return.='<option value=\"'.$res->rowid.'\" selected>'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$return.='<option value=\"'.$res->rowid.'\">'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';\n\t\t\t\t}\n\t\t\t}\n\t\t\t$return.='</select>';\n\t\t}\n\t\treturn $return;\n\t}", "\t/**\n\t * Return a HTML select list of bank accounts\n\t *\n\t * @param\tstring\t$selected Id account pre-selected\n\t * @param string\t$htmlname Name of select zone\n\t * @param int\t\t$statut Status of searched accounts (0=open, 1=closed, 2=both)\n\t * @param string\t$filtre To filter list\n\t * @param int\t\t$useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @param string\t$moreattrib To add more attribute on select\n\t * @param\tint\t\t$showcurrency\t\tShow currency in label\n\t * \t@return\tvoid\n\t */\n\tfunction select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)\n\t{\n\t\tglobal $langs, $conf;", "\t\t$langs->load(\"admin\");", "\t\t$sql = \"SELECT rowid, label, bank, clos as status, currency_code\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"bank_account\";\n\t\t$sql.= \" WHERE entity IN (\".getEntity('bank_account').\")\";\n\t\tif ($statut != 2) $sql.= \" AND clos = '\".$statut.\"'\";\n\t\tif ($filtre) $sql.=\" AND \".$filtre;\n\t\t$sql.= \" ORDER BY label\";", "\t\tdol_syslog(get_class($this).\"::select_comptes\", LOG_DEBUG);\n\t\t$result = $this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\t$num = $this->db->num_rows($result);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tprint '<select id=\"select'.$htmlname.'\" class=\"flat selectbankaccount\" name=\"'.$htmlname.'\"'.($moreattrib?' '.$moreattrib:'').'>';\n\t\t\t\tif ($useempty == 1 || ($useempty == 2 && $num > 1))\n\t\t\t\t{\n\t\t\t\t\tprint '<option value=\"-1\">&nbsp;</option>';\n\t\t\t\t}", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($result);\n\t\t\t\t\tif ($selected == $obj->rowid)\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">';\n\t\t\t\t\t}\n\t\t\t\t\tprint trim($obj->label);\n\t\t\t\t\tif ($showcurrency) print ' ('.$obj->currency_code.')';\n\t\t\t\t\tif ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans(\"Closed\").')';\n\t\t\t\t\tprint '</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t\tprint \"</select>\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint $langs->trans(\"NoActiveBankAccountDefined\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Display form to select bank account\n\t *\n\t * @param\tstring\t$page Page\n\t * @param int\t\t$selected Id of bank account\n\t * @param string\t$htmlname Name of select html field\n\t * @param int\t\t$addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.\n\t * @return\tvoid\n\t */\n\tfunction formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\") {\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setbankaccount\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->select_comptes($selected, $htmlname, 0, '', $addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t} else {", "\t\t\t$langs->load('banks');", "\t\t\tif ($selected) {\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';\n\t\t\t\t$bankstatic=new Account($this->db);\n\t\t\t\t$bankstatic->fetch($selected);\n\t\t\t\tprint $bankstatic->getNomUrl(1);\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Return list of categories having choosed type\n\t *\n\t * @param\tstring|int\t$type\t\t\t\tType of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.\n\t * @param string\t\t$selected \t\tId of category preselected or 'auto' (autoselect category if there is only one element)\n\t * @param string\t\t$htmlname\t\t\tHTML field name\n\t * @param int\t\t\t$maxlength \tMaximum length for labels\n\t * @param int\t\t\t$excludeafterid \tExclude all categories after this leaf in category tree.\n\t * @param\tint\t\t\t$outputmode\t\t\t0=HTML select string, 1=Array\n\t * @return\tstring\n\t * @see select_categories\n\t */\n\tfunction select_all_categories($type, $selected='', $htmlname=\"parent\", $maxlength=64, $excludeafterid=0, $outputmode=0)\n\t{\n\t\tglobal $conf, $langs;\n\t\t$langs->load(\"categories\");", "\t\tinclude_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';", "\t\t// For backward compatibility\n\t\tif (is_numeric($type))\n\t\t{\n\t\t\tdol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);\n\t\t}", "\t\tif ($type === Categorie::TYPE_BANK_LINE)\n\t\t{\n\t\t\t// TODO Move this into common category feature\n\t\t\t$categids=array();\n\t\t\t$sql = \"SELECT c.label, c.rowid\";\n\t\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"bank_categ as c\";\n\t\t\t$sql.= \" WHERE entity = \".$conf->entity;\n\t\t\t$sql.= \" ORDER BY c.label\";\n\t\t\t$result = $this->db->query($sql);\n\t\t\tif ($result)\n\t\t\t{\n\t\t\t\t$num = $this->db->num_rows($result);\n\t\t\t\t$i = 0;\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$objp = $this->db->fetch_object($result);\n\t\t\t\t\tif ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t\t$this->db->free($result);\n\t\t\t}\n\t\t\telse dol_print_error($this->db);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$cat = new Categorie($this->db);\n\t\t\t$cate_arbo = $cat->get_full_arbo($type, $excludeafterid);\n\t\t}", "\t\t$output = '<select class=\"flat\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';\n\t\t$outarray=array();\n\t\tif (is_array($cate_arbo))\n\t\t{\n\t\t\tif (! count($cate_arbo)) $output.= '<option value=\"-1\" disabled>'.$langs->trans(\"NoCategoriesDefined\").'</option>';\n\t\t\telse\n\t\t\t{\n\t\t\t\t$output.= '<option value=\"-1\">&nbsp;</option>';\n\t\t\t\tforeach($cate_arbo as $key => $value)\n\t\t\t\t{\n\t\t\t\t\tif ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))\n\t\t\t\t\t{\n\t\t\t\t\t\t$add = 'selected ';\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$add = '';\n\t\t\t\t\t}\n\t\t\t\t\t$output.= '<option '.$add.'value=\"'.$cate_arbo[$key]['id'].'\">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';", "\t\t\t\t\t$outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$output.= '</select>';\n\t\t$output.= \"\\n\";", "\t\tif ($outputmode) return $outarray;\n\t\treturn $output;\n\t}", "\t/**\n\t * Show a confirmation HTML form or AJAX popup\n\t *\n\t * @param\tstring\t\t$page \t \tUrl of page to call if confirmation is OK\n\t * @param\tstring\t\t$title \t \tTitle\n\t * @param\tstring\t\t$question \t \tQuestion\n\t * @param \tstring\t\t$action \t \tAction\n\t *\t @param\tarray\t\t$formquestion\t \tAn array with forms complementary inputs\n\t * \t @param\tstring\t\t$selectedchoice\t\t\"\" or \"no\" or \"yes\"\n\t * \t @param\tint\t\t\t$useajax\t\t \t0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx\n\t * @param\tint\t\t\t$height \tForce height of box\n\t * @param\tint\t\t\t$width\t\t\t\tForce width of box\n\t * @return \tvoid\n\t * @deprecated\n\t * @see formconfirm()\n\t */\n\tfunction form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice=\"\", $useajax=0, $height=170, $width=500)\n\t{\n\t\tprint $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);\n\t}", "\t/**\n\t * Show a confirmation HTML form or AJAX popup.\n\t * Easiest way to use this is with useajax=1.\n\t * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)\n\t * just after calling this method. For example:\n\t * print '<script type=\"text/javascript\">'.\"\\n\";\n\t * print 'jQuery(document).ready(function() {'.\"\\n\";\n\t * print 'jQuery(\".xxxlink\").click(function(e) { jQuery(\"#aparamid\").val(jQuery(this).attr(\"rel\")); jQuery(\"#dialog-confirm-xxx\").dialog(\"open\"); return false; });'.\"\\n\";\n\t * print '});'.\"\\n\";\n\t * print '</script>'.\"\\n\";\n\t *\n\t * @param \tstring\t\t$page \t \tUrl of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)\n\t * @param\tstring\t\t$title \t \tTitle\n\t * @param\tstring\t\t$question \t \tQuestion\n\t * @param \tstring\t\t$action \t \tAction\n\t *\t @param \tarray\t\t$formquestion\t \tAn array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))\n\t *\t\t\t\t\t\t\t\t\t\t\t\ttype can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', ...\n\t * \t @param \tstring\t\t$selectedchoice \t\"\" or \"no\" or \"yes\"\n\t * \t @param \tint\t\t\t$useajax\t\t \t0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx\n\t * @param \tint\t\t\t$height \tForce height of box\n\t * @param\tint\t\t\t$width\t\t\t\tForce width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.\n\t * @param\tint\t\t\t$disableformtag\t\t1=Disable form tag. Can be used if we are already inside a <form> section.\n\t * @return \tstring \t \t\t\tHTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form\n\t */\n\tfunction formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=200, $width=500, $disableformtag=0)\n\t{\n\t\tglobal $langs,$conf;\n\t\tglobal $useglobalvars;", "\t\t$more='';\n\t\t$formconfirm='';\n\t\t$inputok=array();\n\t\t$inputko=array();", "\t\t// Clean parameters\n\t\t$newselectedchoice=empty($selectedchoice)?\"no\":$selectedchoice;\n\t\tif ($conf->browser->layout == 'phone') $width='95%';", "\t\tif (is_array($formquestion) && ! empty($formquestion))\n\t\t{\n\t\t\t// First add hidden fields and value\n\t\t\tforeach ($formquestion as $key => $input)\n\t\t\t{\n\t\t\t\tif (is_array($input) && ! empty($input))\n\t\t\t\t{\n\t\t\t\t\tif ($input['type'] == 'hidden')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<input type=\"hidden\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\" value=\"'.dol_escape_htmltag($input['value']).'\">'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\t// Now add questions\n\t\t\t$more.='<table class=\"paddingtopbottomonly\" width=\"100%\">'.\"\\n\";\n\t\t\t$more.='<tr><td colspan=\"3\">'.(! empty($formquestion['text'])?$formquestion['text']:'').'</td></tr>'.\"\\n\";\n\t\t\tforeach ($formquestion as $key => $input)\n\t\t\t{\n\t\t\t\tif (is_array($input) && ! empty($input))\n\t\t\t\t{\n\t\t\t\t\t$size=(! empty($input['size'])?' size=\"'.$input['size'].'\"':'');\n\t\t\t\t\t$moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');\n\t\t\t\t\t$morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');", "\t\t\t\t\tif ($input['type'] == 'text')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>'.$input['label'].'</td><td colspan=\"2\" align=\"left\"><input type=\"text\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\"'.$size.' value=\"'.$input['value'].'\"'.$moreattr.' /></td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'password')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>'.$input['label'].'</td><td colspan=\"2\" align=\"left\"><input type=\"password\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\"'.$size.' value=\"'.$input['value'].'\"'.$moreattr.' /></td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'select')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>';\n\t\t\t\t\t\tif (! empty($input['label'])) $more.=$input['label'].'</td><td valign=\"top\" colspan=\"2\" align=\"left\">';\n\t\t\t\t\t\t$more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'checkbox')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr>';\n\t\t\t\t\t\t$more.='<td>'.$input['label'].' </td><td align=\"left\">';\n\t\t\t\t\t\t$more.='<input type=\"checkbox\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\"'.$moreattr;\n\t\t\t\t\t\tif (! is_bool($input['value']) && $input['value'] != 'false') $more.=' checked';\n\t\t\t\t\t\tif (is_bool($input['value']) && $input['value']) $more.=' checked';\n\t\t\t\t\t\tif (isset($input['disabled'])) $more.=' disabled';\n\t\t\t\t\t\t$more.=' /></td>';\n\t\t\t\t\t\t$more.='<td align=\"left\">&nbsp;</td>';\n\t\t\t\t\t\t$more.='</tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'radio')\n\t\t\t\t\t{\n\t\t\t\t\t\t$i=0;\n\t\t\t\t\t\tforeach($input['values'] as $selkey => $selval)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$more.='<tr>';\n\t\t\t\t\t\t\tif ($i==0) $more.='<td class=\"tdtop\">'.$input['label'].'</td>';\n\t\t\t\t\t\t\telse $more.='<td>&nbsp;</td>';\n\t\t\t\t\t\t\t$more.='<td width=\"20\"><input type=\"radio\" class=\"flat'.$morecss.'\" id=\"'.$input['name'].'\" name=\"'.$input['name'].'\" value=\"'.$selkey.'\"'.$moreattr;\n\t\t\t\t\t\t\tif ($input['disabled']) $more.=' disabled';\n\t\t\t\t\t\t\t$more.=' /></td>';\n\t\t\t\t\t\t\t$more.='<td align=\"left\">';\n\t\t\t\t\t\t\t$more.=$selval;\n\t\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t\t\t$i++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'date')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>'.$input['label'].'</td>';\n\t\t\t\t\t\t$more.='<td colspan=\"2\" align=\"left\">';\n\t\t\t\t\t\t$more.=$this->select_date($input['value'],$input['name'],0,0,0,'',1,0,1);\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'day');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'month');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'year');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'hour');\n\t\t\t\t\t\t$formquestion[] = array('name'=>$input['name'].'min');\n\t\t\t\t\t}\n\t\t\t\t\telse if ($input['type'] == 'other')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td>';\n\t\t\t\t\t\tif (! empty($input['label'])) $more.=$input['label'].'</td><td colspan=\"2\" align=\"left\">';\n\t\t\t\t\t\t$more.=$input['value'];\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t}", "\t\t\t\t\telse if ($input['type'] == 'onecolumn')\n\t\t\t\t\t{\n\t\t\t\t\t\t$more.='<tr><td colspan=\"3\" align=\"left\">';\n\t\t\t\t\t\t$more.=$input['value'];\n\t\t\t\t\t\t$more.='</td></tr>'.\"\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t$more.='</table>'.\"\\n\";\n\t\t}", "\t\t// JQUI method dialog is broken with jmobile, we use standard HTML.\n\t\t// Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx\n\t\t// See page product/card.php for example\n\t\tif (! empty($conf->dol_use_jmobile)) $useajax=0;\n\t\tif (empty($conf->use_javascript_ajax)) $useajax=0;", "\t\tif ($useajax)\n\t\t{\n\t\t\t$autoOpen=true;\n\t\t\t$dialogconfirm='dialog-confirm';\n\t\t\t$button='';\n\t\t\tif (! is_numeric($useajax))\n\t\t\t{\n\t\t\t\t$button=$useajax;\n\t\t\t\t$useajax=1;\n\t\t\t\t$autoOpen=false;\n\t\t\t\t$dialogconfirm.='-'.$button;\n\t\t\t}\n\t\t\t$pageyes=$page.(preg_match('/\\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';\n\t\t\t$pageno=($useajax == 2 ? $page.(preg_match('/\\?/',$page)?'&':'?').'confirm=no':'');\n\t\t\t// Add input fields into list of fields to read during submit (inputok and inputko)\n\t\t\tif (is_array($formquestion))\n\t\t\t{\n\t\t\t\tforeach ($formquestion as $key => $input)\n\t\t\t\t{\n\t\t\t\t\t//print \"xx \".$key.\" rr \".is_array($input).\"<br>\\n\";\n\t\t\t\t\tif (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);\n\t\t\t\t\tif (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Show JQuery confirm box. Note that global var $useglobalvars is used inside this template\n\t\t\t$formconfirm.= '<div id=\"'.$dialogconfirm.'\" title=\"'.dol_escape_htmltag($title).'\" style=\"display: none;\">';\n\t\t\tif (! empty($more)) {\n\t\t\t\t$formconfirm.= '<div class=\"confirmquestions\">'.$more.'</div>';\n\t\t\t}\n\t\t\t$formconfirm.= ($question ? '<div class=\"confirmmessage\">'.img_help('','').' '.$question . '</div>': '');\n\t\t\t$formconfirm.= '</div>'.\"\\n\";", "\t\t\t$formconfirm.= \"\\n<!-- begin ajax form_confirm page=\".$page.\" -->\\n\";\n\t\t\t$formconfirm.= '<script type=\"text/javascript\">'.\"\\n\";\n\t\t\t$formconfirm.= 'jQuery(document).ready(function() {\n $(function() {\n \t$( \"#'.$dialogconfirm.'\" ).dialog(\n \t{\n autoOpen: '.($autoOpen ? \"true\" : \"false\").',';\n\t\t\t\t\tif ($newselectedchoice == 'no')\n\t\t\t\t\t{\n\t\t\t\t\t\t$formconfirm.='\n\t\t\t\t\t\topen: function() {\n \t\t\t\t$(this).parent().find(\"button.ui-button:eq(2)\").focus();\n\t\t\t\t\t\t},';\n\t\t\t\t\t}\n\t\t\t\t\t$formconfirm.='\n resizable: false,\n height: \"'.$height.'\",\n width: \"'.$width.'\",\n modal: true,\n closeOnEscape: false,\n buttons: {\n \"'.dol_escape_js($langs->transnoentities(\"Yes\")).'\": function() {\n \tvar options=\"\";\n \tvar inputok = '.json_encode($inputok).';\n \tvar pageyes = \"'.dol_escape_js(! empty($pageyes)?$pageyes:'').'\";\n \tif (inputok.length>0) {\n \t\t$.each(inputok, function(i, inputname) {\n \t\t\tvar more = \"\";\n \t\t\tif ($(\"#\" + inputname).attr(\"type\") == \"checkbox\") { more = \":checked\"; }\n \t\t if ($(\"#\" + inputname).attr(\"type\") == \"radio\") { more = \":checked\"; }\n \t\t\tvar inputvalue = $(\"#\" + inputname + more).val();\n \t\t\tif (typeof inputvalue == \"undefined\") { inputvalue=\"\"; }\n \t\t\toptions += \"&\" + inputname + \"=\" + inputvalue;\n \t\t});\n \t}\n \tvar urljump = pageyes + (pageyes.indexOf(\"?\") < 0 ? \"?\" : \"\") + options;\n \t//alert(urljump);\n \t\t\t\tif (pageyes.length > 0) { location.href = urljump; }\n $(this).dialog(\"close\");\n },\n \"'.dol_escape_js($langs->transnoentities(\"No\")).'\": function() {\n \tvar options = \"\";\n \tvar inputko = '.json_encode($inputko).';\n \tvar pageno=\"'.dol_escape_js(! empty($pageno)?$pageno:'').'\";\n \tif (inputko.length>0) {\n \t\t$.each(inputko, function(i, inputname) {\n \t\t\tvar more = \"\";\n \t\t\tif ($(\"#\" + inputname).attr(\"type\") == \"checkbox\") { more = \":checked\"; }\n \t\t\tvar inputvalue = $(\"#\" + inputname + more).val();\n \t\t\tif (typeof inputvalue == \"undefined\") { inputvalue=\"\"; }\n \t\t\toptions += \"&\" + inputname + \"=\" + inputvalue;\n \t\t});\n \t}\n \tvar urljump=pageno + (pageno.indexOf(\"?\") < 0 ? \"?\" : \"\") + options;\n \t//alert(urljump);\n \t\t\t\tif (pageno.length > 0) { location.href = urljump; }\n $(this).dialog(\"close\");\n }\n }\n }\n );", " \tvar button = \"'.$button.'\";\n \tif (button.length > 0) {\n \t$( \"#\" + button ).click(function() {\n \t\t$(\"#'.$dialogconfirm.'\").dialog(\"open\");\n \t\t\t});\n }\n });\n });\n </script>';\n\t\t\t$formconfirm.= \"<!-- end ajax form_confirm -->\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$formconfirm.= \"\\n<!-- begin form_confirm page=\".$page.\" -->\\n\";", "\t\t\tif (empty($disableformtag)) $formconfirm.= '<form method=\"POST\" action=\"'.$page.'\" class=\"notoptoleftroright\">'.\"\\n\";", "\t\t\t$formconfirm.= '<input type=\"hidden\" name=\"action\" value=\"'.$action.'\">'.\"\\n\";\n\t\t\tif (empty($disableformtag)) $formconfirm.= '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">'.\"\\n\";", "\t\t\t$formconfirm.= '<table width=\"100%\" class=\"valid\">'.\"\\n\";", "\t\t\t// Line title\n\t\t\t$formconfirm.= '<tr class=\"validtitre\"><td class=\"validtitre\" colspan=\"3\">'.img_picto('','recent').' '.$title.'</td></tr>'.\"\\n\";", "\t\t\t// Line form fields\n\t\t\tif ($more)\n\t\t\t{\n\t\t\t\t$formconfirm.='<tr class=\"valid\"><td class=\"valid\" colspan=\"3\">'.\"\\n\";\n\t\t\t\t$formconfirm.=$more;\n\t\t\t\t$formconfirm.='</td></tr>'.\"\\n\";\n\t\t\t}", "\t\t\t// Line with question\n\t\t\t$formconfirm.= '<tr class=\"valid\">';\n\t\t\t$formconfirm.= '<td class=\"valid\">'.$question.'</td>';\n\t\t\t$formconfirm.= '<td class=\"valid\">';\n\t\t\t$formconfirm.= $this->selectyesno(\"confirm\",$newselectedchoice);\n\t\t\t$formconfirm.= '</td>';\n\t\t\t$formconfirm.= '<td class=\"valid\" align=\"center\"><input class=\"button valignmiddle\" type=\"submit\" value=\"'.$langs->trans(\"Validate\").'\"></td>';\n\t\t\t$formconfirm.= '</tr>'.\"\\n\";", "\t\t\t$formconfirm.= '</table>'.\"\\n\";", "\t\t\tif (empty($disableformtag)) $formconfirm.= \"</form>\\n\";\n\t\t\t$formconfirm.= '<br>';", "\t\t\t$formconfirm.= \"<!-- end form_confirm -->\\n\";\n\t\t}", "\t\treturn $formconfirm;\n\t}", "\n\t/**\n\t * Show a form to select a project\n\t *\n\t * @param\tint\t\t$page \t\tPage\n\t * @param\tint\t\t$socid \t\tId third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)\n\t * @param int\t\t$selected \t\tId pre-selected project\n\t * @param string\t$htmlname \t\tName of select field\n\t * @param\tint\t\t$discard_closed\t\tDiscard closed projects (0=Keep,1=hide completely except $selected,2=Disable)\n\t * @param\tint\t\t$maxlength\t\t\tMax length\n\t * @param\tint\t\t$forcefocus\t\t\tForce focus on field (works with javascript only)\n\t * @param int $nooutput No print is done. String is returned.\n\t * @return\tstring Return html content\n\t */\n\tfunction form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)\n\t{\n\t\tglobal $langs;", "\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';\n\t\trequire_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';", "\t\t$out='';", "\t\t$formproject=new FormProjets($this->db);", "\t\t$langs->load(\"project\");\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\t$out.=\"\\n\";\n\t\t\t$out.='<form method=\"post\" action=\"'.$page.'\">';\n\t\t\t$out.='<input type=\"hidden\" name=\"action\" value=\"classin\">';\n\t\t\t$out.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);\n\t\t\t$out.='<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\t$out.='</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$projet = new Project($this->db);\n\t\t\t\t$projet->fetch($selected);\n\t\t\t\t//print '<a href=\"'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'\">'.$projet->title.'</a>';\n\t\t\t\t$out.=$projet->getNomUrl(0,'',1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.=\"&nbsp;\";\n\t\t\t}\n\t\t}", "\t\tif (empty($nooutput))\n\t\t{\n\t\t\tprint $out;\n\t\t\treturn '';\n\t\t}\n\t\treturn $out;\n\t}", "\t/**\n\t *\tShow a form to select payment conditions\n\t *\n\t * @param\tint\t\t$page \tPage\n\t * @param string\t$selected \tId condition pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t *\t@param\tint\t\t$addempty\t\tAdd empty entry\n\t * @return\tvoid\n\t */\n\tfunction form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setconditions\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->select_conditions_paiements($selected,$htmlname,-1,$addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->load_cache_conditions_paiements();\n\t\t\t\tprint $this->cache_conditions_paiements[$selected]['label'];\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Show a form to select a delivery delay\n\t *\n\t * @param int\t\t$page \tPage\n\t * @param string\t$selected \tId condition pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t *\t@param\tint\t\t$addempty\t\tAjoute entree vide\n\t * @return\tvoid\n\t */\n\tfunction form_availability($page, $selected='', $htmlname='availability', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setavailability\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->load_cache_availability();\n\t\t\t\tprint $this->cache_availability[$selected]['label'];\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t *\tOutput HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)\n\t * List found into table c_input_reason loaded by loadCacheInputReason\n\t *\n\t * @param string\t$page \tPage\n\t * @param string\t$selected \tId condition pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t *\t@param\tint\t\t$addempty\t\tAdd empty entry\n\t * @return\tvoid\n\t */\n\tfunction formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setdemandreason\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->selectInputReason($selected,$htmlname,-1,$addempty);\n\t\t\tprint '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->loadCacheInputReason();\n\t\t\t\tforeach ($this->cache_demand_reason as $key => $val)\n\t\t\t\t{\n\t\t\t\t\tif ($val['id'] == $selected)\n\t\t\t\t\t{\n\t\t\t\t\t\tprint $val['label'];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Show a form + html select a date\n\t *\n\t * @param\tstring\t\t$page \tPage\n\t * @param\tstring\t\t$selected \tDate preselected\n\t * @param string\t\t$htmlname \tHtml name of date input fields or 'none'\n\t * @param int\t\t\t$displayhour \tDisplay hour selector\n\t * @param int\t\t\t$displaymin\t\tDisplay minutes selector\n\t * @param\tint\t\t\t$nooutput\t\t1=No print output, return string\n\t * @return\tstring\n\t * @see\t\tselect_date\n\t */\n\tfunction form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)\n\t{\n\t\tglobal $langs;", "\t\t$ret='';", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\t$ret.='<form method=\"post\" action=\"'.$page.'\" name=\"form'.$htmlname.'\">';\n\t\t\t$ret.='<input type=\"hidden\" name=\"action\" value=\"set'.$htmlname.'\">';\n\t\t\t$ret.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$ret.='<table class=\"nobordernopadding\" cellpadding=\"0\" cellspacing=\"0\">';\n\t\t\t$ret.='<tr><td>';\n\t\t\t$ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1);\n\t\t\t$ret.='</td>';\n\t\t\t$ret.='<td align=\"left\"><input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\"></td>';\n\t\t\t$ret.='</tr></table></form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($displayhour) $ret.=dol_print_date($selected,'dayhour');\n\t\t\telse $ret.=dol_print_date($selected,'day');\n\t\t}", "\t\tif (empty($nooutput)) print $ret;\n\t\treturn $ret;\n\t}", "\n\t/**\n\t * Show a select form to choose a user\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param string\t$selected \tId of user preselected\n\t * @param string\t$htmlname \tName of input html field. If 'none', we just output the user link.\n\t * @param array\t$exclude\t\tList of users id to exclude\n\t * @param array\t$include List of users id to include\n\t * @return\tvoid\n\t */\n\tfunction form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')\n\t{\n\t\tglobal $langs;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\" name=\"form'.$htmlname.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"set'.$htmlname.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';\n\t\t\t\t$theuser=new User($this->db);\n\t\t\t\t$theuser->fetch($selected);\n\t\t\t\tprint $theuser->getNomUrl(1);\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\n\t/**\n\t * Show form with payment mode\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param int\t\t$selected \tId mode pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t * @param \tstring\t$filtertype\t\tTo filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))\n\t * @param int $active Active or not, -1 = all\n\t * @return\tvoid\n\t */\n\tfunction form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setmode\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t$this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\t$this->load_cache_types_paiements();\n\t\t\t\tprint $this->cache_types_paiements[$selected]['label'];\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Show form with multicurrency code\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param string\t$selected \tcode pre-selectionne\n\t * @param string\t$htmlname \tName of select html field\n\t * @return\tvoid\n\t */\n\tfunction form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')\n\t{\n\t\tglobal $langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setmulticurrencycode\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint $this->selectMultiCurrency($selected, $htmlname, 0);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_include_once('/core/lib/company.lib.php');\n\t\t\tprint !empty($selected) ? currency_name($selected,1) : '&nbsp;';\n\t\t}\n\t}", "\t/**\n\t * Show form with multicurrency rate\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param double\t$rate\t \tCurrent rate\n\t * @param string\t$htmlname \tName of select html field\n\t * @param string $currency Currency code to explain the rate\n\t * @return\tvoid\n\t */\n\tfunction form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')\n\t{\n\t\tglobal $langs, $mysoc, $conf;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"POST\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setmulticurrencyrate\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint '<input type=\"text\" name=\"'.$htmlname.'\" value=\"'.(!empty($rate) ? price($rate) : 1).'\" size=\"10\" /> ';\n\t\t\tprint '<select name=\"calculation_mode\">';\n\t\t\tprint '<option value=\"1\">'.$currency.' > '.$conf->currency.'</option>';\n\t\t\tprint '<option value=\"2\">'.$conf->currency.' > '.$currency.'</option>';\n\t\t\tprint '</select> ';\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (! empty($rate))\n\t\t\t{\n\t\t\t\tprint price($rate, 1, $langs, 1, 0);\n\t\t\t\tif ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint 1;\n\t\t\t}\n\t\t}\n\t}", "\n\t/**\n\t *\tShow a select box with available absolute discounts\n\t *\n\t * @param string\t$page \tPage URL where form is shown\n\t * @param int\t\t$selected \tValue pre-selected\n\t *\t@param string\t$htmlname \tName of SELECT component. If 'none', not changeable. Example 'remise_id'.\n\t *\t@param\tint\t\t$socid\t\t\tThird party id\n\t * \t@param\tfloat\t$amount\t\t\tTotal amount available\n\t * \t@param\tstring\t$filter\t\t\tSQL filter on discounts\n\t * \t@param\tint\t\t$maxvalue\t\tMax value for lines that can be selected\n\t * @param string\t$more More string to add\n\t * @param int $hidelist 1=Hide list\n\t * @return\tvoid\n\t */\n\tfunction form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0)\n\t{\n\t\tglobal $conf,$langs;\n\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setabsolutediscount\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint '<div class=\"inline-block\">';\n\t\t\tif (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))\n\t\t\t{\n\t\t\t\tif (! $filter || $filter==\"fk_facture_source IS NULL\") print $langs->trans(\"CompanyHasAbsoluteDiscount\",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice\n\t\t\t\telse print $langs->trans(\"CompanyHasCreditNote\",price($amount,0,$langs,0,0,-1,$conf->currency));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (! $filter || $filter==\"fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))\") print $langs->trans(\"CompanyHasAbsoluteDiscount\",price($amount,0,$langs,0,0,-1,$conf->currency));\n\t\t\t\telse print $langs->trans(\"CompanyHasCreditNote\",price($amount,0,$langs,0,0,-1,$conf->currency));\n\t\t\t}\n\t\t\tif (empty($hidelist)) print ': ';\n\t\t\tprint '</div>';\n\t\t\tif (empty($hidelist))\n\t\t\t{\n\t\t\t\tprint '<div class=\"inline-block\" style=\"padding-right: 10px\">';\n\t\t\t\t$newfilter='fk_facture IS NULL AND fk_facture_line IS NULL';\t// Remises disponibles\n\t\t\t\tif ($filter) $newfilter.=' AND ('.$filter.')';\n\t\t\t\t$nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);\n\t\t\t\tif ($nbqualifiedlines > 0)\n\t\t\t\t{\n\t\t\t\t\tprint ' &nbsp; <input type=\"submit\" class=\"button\" value=\"'.dol_escape_htmltag($langs->trans(\"UseLine\")).'\"';\n\t\t\t\t\tif ($filter && $filter != \"fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')\") print ' title=\"'.$langs->trans(\"UseCreditNoteInInvoicePayment\").'\"';\n\t\t\t\t\tprint '>';\n\t\t\t\t}\n\t\t\t\tprint '</div>';\n\t\t\t}\n\t\t\tif ($more)\n\t\t\t{\n\t\t\t\tprint '<div class=\"inline-block\">';\n\t\t\t\tprint $more;\n\t\t\t\tprint '</div>';\n\t\t\t}\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\tprint $selected;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint \"0\";\n\t\t\t}\n\t\t}\n\t}", "\n\t/**\n\t * Show forms to select a contact\n\t *\n\t * @param\tstring\t\t$page \tPage\n\t * @param\tSociete\t\t$societe\t\tFilter on third party\n\t * @param int\t\t\t$selected \tId contact pre-selectionne\n\t * @param string\t\t$htmlname \tName of HTML select. If 'none', we just show contact link.\n\t * @return\tvoid\n\t */\n\tfunction form_contacts($page, $societe, $selected='', $htmlname='contactid')\n\t{\n\t\tglobal $langs, $conf;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"set_contact\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint '<table class=\"nobordernopadding\" cellpadding=\"0\" cellspacing=\"0\">';\n\t\t\tprint '<tr><td>';\n\t\t\t$num=$this->select_contacts($societe->id, $selected, $htmlname);\n\t\t\tif ($num==0)\n\t\t\t{\n\t\t\t\t$addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans(\"AddContact\") : $langs->trans(\"AddContactAddress\"));\n\t\t\t\tprint '<a href=\"'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1\">'.$addcontact.'</a>';\n\t\t\t}\n\t\t\tprint '</td>';\n\t\t\tprint '<td align=\"left\"><input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\"></td>';\n\t\t\tprint '</tr></table></form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';\n\t\t\t\t$contact=new Contact($this->db);\n\t\t\t\t$contact->fetch($selected);\n\t\t\t\tprint $contact->getFullName($langs);\n\t\t\t} else {\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Output html select to select thirdparty\n\t *\n\t * @param\tstring\t$page \tPage\n\t * @param string\t$selected \tId preselected\n\t * @param string\t$htmlname\t\tName of HTML select\n\t * @param string\t$filter optional filters criteras\n\t *\t@param\tint\t\t$showempty\t\tAdd an empty field\n\t * \t@param\tint\t\t$showtype\t\tShow third party type in combolist (customer, prospect or supplier)\n\t * \t@param\tint\t\t$forcecombo\t\tForce to use combo box\n\t * @param\tarray\t$events\t\t\tEvent options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))\n\t * @return\tvoid\n\t */\n\tfunction form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array())\n\t{\n\t\tglobal $langs;", "\t\tif ($htmlname != \"none\")\n\t\t{\n\t\t\tprint '<form method=\"post\" action=\"'.$page.'\">';\n\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"set_thirdparty\">';\n\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\tprint $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);\n\t\t\tprint '<input type=\"submit\" class=\"button valignmiddle\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\tprint '</form>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ($selected)\n\t\t\t{\n\t\t\t\trequire_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';\n\t\t\t\t$soc = new Societe($this->db);\n\t\t\t\t$soc->fetch($selected);\n\t\t\t\tprint $soc->getNomUrl($langs);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint \"&nbsp;\";\n\t\t\t}\n\t\t}\n\t}", "\t/**\n\t * Retourne la liste des devises, dans la langue de l'utilisateur\n\t *\n\t * @param\tstring\t$selected preselected currency code\n\t * @param string\t$htmlname name of HTML select list\n\t * @return\tvoid\n\t */\n\tfunction select_currency($selected='',$htmlname='currency_id')\n\t{\n\t\tprint $this->selectCurrency($selected,$htmlname);\n\t}", "\t/**\n\t * Retourne la liste des devises, dans la langue de l'utilisateur\n\t *\n\t * @param\tstring\t$selected preselected currency code\n\t * @param string\t$htmlname name of HTML select list\n\t * \t@return\tstring\n\t */\n\tfunction selectCurrency($selected='',$htmlname='currency_id')\n\t{\n\t\tglobal $conf,$langs,$user;", "\t\t$langs->loadCacheCurrencies('');", "\t\t$out='';", "\t\tif ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite", "\t\t$out.= '<select class=\"flat maxwidth200onsmartphone minwidth300\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';\n\t\tforeach ($langs->cache_currencies as $code_iso => $currency)\n\t\t{\n\t\t\tif ($selected && $selected == $code_iso)\n\t\t\t{\n\t\t\t\t$out.= '<option value=\"'.$code_iso.'\" selected>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$out.= '<option value=\"'.$code_iso.'\">';\n\t\t\t}\n\t\t\t$out.= $currency['label'];\n\t\t\t$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';\n\t\t\t$out.= '</option>';\n\t\t}\n\t\t$out.= '</select>';\n\t\tif ($user->admin) $out.= info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);", "\t\t// Make select dynamic\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t$out .= ajax_combobox($htmlname);", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn array of currencies in user language\n\t *\n\t * @param\tstring\t$selected preselected currency code\n\t * @param string\t$htmlname name of HTML select list\n\t * @param integer\t$useempty 1=Add empty line\n\t * \t@return\tstring\n\t */\n\tfunction selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)\n\t{\n\t\tglobal $db,$conf,$langs,$user;", "\t\t$langs->loadCacheCurrencies(''); // Load ->cache_currencies", "\t\t$TCurrency = array();", "\t\t$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';\n\t\t$sql.= \" WHERE entity IN ('\".getEntity('mutlicurrency').\"')\";\n\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\twhile ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;\n\t\t}", "\t\t$out='';\n\t\t$out.= '<select class=\"flat\" name=\"'.$htmlname.'\" id=\"'.$htmlname.'\">';\n\t\tif ($useempty) $out .= '<option value=\"\"></option>';\n\t\t// If company current currency not in table, we add it into list. Should always be available.\n\t\tif (! in_array($conf->currency, $TCurrency))\n\t\t{\n\t\t\t$TCurrency[$conf->currency] = $conf->currency;\n\t\t}\n\t\tif (count($TCurrency) > 0)\n\t\t{\n\t\t\tforeach ($langs->cache_currencies as $code_iso => $currency)\n\t\t\t{\n\t\t\t\tif (isset($TCurrency[$code_iso]))\n\t\t\t\t{\n\t\t\t\t\tif (!empty($selected) && $selected == $code_iso) $out.= '<option value=\"'.$code_iso.'\" selected=\"selected\">';\n\t\t\t\t\telse $out.= '<option value=\"'.$code_iso.'\">';", "\t\t\t\t\t$out.= $currency['label'];\n\t\t\t\t\t$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';\n\t\t\t\t\t$out.= '</option>';\n\t\t\t\t}\n\t\t\t}", "\t\t}", "\t\t$out.= '</select>';\n\t\t// Make select dynamic\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t$out.= ajax_combobox($htmlname);", "\t\treturn $out;\n\t}", "\t/**\n\t *\tLoad into the cache vat rates of a country\n\t *\n\t *\t@param\tstring\t$country_code\t\tCountry code with quotes (\"'CA'\", or \"'CA,IN,...'\")\n\t *\t@return\tint\t\t\t\t\t\t\tNb of loaded lines, 0 if already loaded, <0 if KO\n\t */\n\tfunction load_cache_vatrates($country_code)\n\t{\n\t\tglobal $langs;", "\t\t$num = count($this->cache_vatrates);\n\t\tif ($num > 0) return $num; // Cache already loaded", "\t\tdol_syslog(__METHOD__, LOG_DEBUG);", "\t\t$sql = \"SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"c_tva as t, \".MAIN_DB_PREFIX.\"c_country as c\";\n\t\t$sql.= \" WHERE t.fk_pays = c.rowid\";\n\t\t$sql.= \" AND t.active > 0\";\n\t\t$sql.= \" AND c.code IN (\".$country_code.\")\";\n\t\t$sql.= \" ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC\";", "\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$num = $this->db->num_rows($resql);\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tfor ($i = 0; $i < $num; $i++)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$this->cache_vatrates[$i]['rowid']\t= $obj->rowid;\n\t\t\t\t\t$this->cache_vatrates[$i]['code']\t= $obj->code;\n\t\t\t\t\t$this->cache_vatrates[$i]['txtva']\t= $obj->taux;\n\t\t\t\t\t$this->cache_vatrates[$i]['nprtva']\t= $obj->recuperableonly;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax1']\t = $obj->localtax1;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax1_type']\t= $obj->localtax1_type;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax2']\t = $obj->localtax2;\n\t\t\t\t\t$this->cache_vatrates[$i]['localtax2_type']\t= $obj->localtax1_type;", "\t\t\t\t\t$this->cache_vatrates[$i]['label']\t= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or *\n\t\t\t\t\t$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');\t// Must never be used as key, only label\n\t\t\t\t\t$positiverates='';\n\t\t\t\t\tif ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;\n\t\t\t\t\tif ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;\n\t\t\t\t\tif ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;\n\t\t\t\t\tif (empty($positiverates)) $positiverates='0';\n\t\t\t\t\t$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');\t// Must never be used as key, only label\n\t\t\t\t}", "\t\t\t\treturn $num;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$this->error = '<font class=\"error\">'.$langs->trans(\"ErrorNoVATRateDefinedForSellerCountry\",$country_code).'</font>';\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$this->error = '<font class=\"error\">'.$this->db->error().'</font>';\n\t\t\treturn -2;\n\t\t}\n\t}", "\t/**\n\t * Output an HTML select vat rate.\n\t * The name of this function should be selectVat. We keep bad name for compatibility purpose.\n\t *\n\t * @param\tstring\t $htmlname Name of HTML select field\n\t * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.\n\t * @param Societe\t $societe_vendeuse Thirdparty seller\n\t * @param Societe\t $societe_acheteuse Thirdparty buyer\n\t * @param int\t\t $idprod Id product. O if unknown of NA.\n\t * @param int\t\t $info_bits Miscellaneous information on line (1 for NPR)\n\t * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)\n\t * \t\t Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.\n\t * \t\t\t\t\t Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.\n\t * \t\t\t\t\t Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.\n\t * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.\n\t * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.\n\t * \t\t\t\t\t Sinon la TVA proposee par defaut=0. Fin de regle.\n\t * @param\tbool\t $options_only\t\t Return HTML options lines only (for ajax treatment)\n\t * @param int $mode 0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key\n\t * @return\tstring\n\t */\n\tfunction load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)\n\t{\n\t\tglobal $langs,$conf,$mysoc;", "\t\t$langs->load('errors');", "\t\t$return='';", "\t\t// Define defaultnpr, defaultttx and defaultcode\n\t\t$defaultnpr=($info_bits & 0x01);\n\t\t$defaultnpr=(preg_match('/\\*/',$selectedrate) ? 1 : $defaultnpr);\n\t\t$defaulttx=str_replace('*','',$selectedrate);\n\t\t$defaultcode='';\n\t\tif (preg_match('/\\((.*)\\)/', $defaulttx, $reg))\n\t\t{\n\t\t\t$defaultcode=$reg[1];\n\t\t\t$defaulttx=preg_replace('/\\s*\\(.*\\)/','',$defaulttx);\n\t\t}\n\t\t//var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);", "\t\t// Check parameters\n\t\tif (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)\n\t\t{\n\t\t\tif ($societe_vendeuse->id == $mysoc->id)\n\t\t\t{\n\t\t\t\t$return.= '<font class=\"error\">'.$langs->trans(\"ErrorYourCountryIsNotDefined\").'</div>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$return.= '<font class=\"error\">'.$langs->trans(\"ErrorSupplierCountryIsNotDefined\").'</div>';\n\t\t\t}\n\t\t\treturn $return;\n\t\t}", "\t\t//var_dump($societe_acheteuse);\n\t\t//print \"name=$name, selectedrate=$selectedrate, seller=\".$societe_vendeuse->country_code.\" buyer=\".$societe_acheteuse->country_code.\" buyer is company=\".$societe_acheteuse->isACompany().\" idprod=$idprod, info_bits=$info_bits type=$type\";\n\t\t//exit;", "\t\t// Define list of countries to use to search VAT rates to show\n\t\t// First we defined code_country to use to find list\n\t\tif (is_object($societe_vendeuse))\n\t\t{\n\t\t\t$code_country=\"'\".$societe_vendeuse->country_code.\"'\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$code_country=\"'\".$mysoc->country_code.\"'\"; // Pour compatibilite ascendente\n\t\t}\n\t\tif (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';\n\t\t\tif (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))\n\t\t\t{\n\t\t\t\t// We also add the buyer\n\t\t\t\tif (is_numeric($type))\n\t\t\t\t{\n\t\t\t\t\tif ($type == 1) // We know product is a service\n\t\t\t\t\t{\n\t\t\t\t\t\t$code_country.=\",'\".$societe_acheteuse->country_code.\"'\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (! $idprod) // We don't know type of product\n\t\t\t\t{\n\t\t\t\t\t$code_country.=\",'\".$societe_acheteuse->country_code.\"'\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$prodstatic=new Product($this->db);\n\t\t\t\t\t$prodstatic->fetch($idprod);\n\t\t\t\t\tif ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service\n\t\t\t\t\t{\n\t\t\t\t\t\t$code_country.=\",'\".$societe_acheteuse->country_code.\"'\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t// Now we get list\n\t\t$num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error", "\t\tif ($num > 0)\n\t\t{\n\t\t\t// Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')\n\t\t\tif ($defaulttx < 0 || dol_strlen($defaulttx) == 0)\n\t\t\t{\n\t\t\t\t$tmpthirdparty=new Societe($this->db);\n\t\t\t\t$defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);\n\t\t\t\t$defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);\n\t\t\t\tif (empty($defaulttx)) $defaultnpr=0;\n\t\t\t}", "\t\t\t// Si taux par defaut n'a pu etre determine, on prend dernier de la liste.\n\t\t\t// Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant\n\t\t\tif ($defaulttx < 0 || dol_strlen($defaulttx) == 0)\n\t\t\t{\n\t\t\t\tif (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];\n\t\t\t\telse $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);\n\t\t\t}", "\t\t\t// Disabled if seller is not subject to VAT\n\t\t\t$disabled=false; $title='';\n\t\t\tif (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == \"0\")\n\t\t\t{\n\t\t\t\t$title=' title=\"'.$langs->trans('VATIsNotUsed').'\"';\n\t\t\t\t$disabled=true;\n\t\t\t}", "\t\t\tif (! $options_only) $return.= '<select class=\"flat minwidth75imp\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.($disabled?' disabled':'').$title.'>';", "\t\t\t$selectedfound=false;\n\t\t\tforeach ($this->cache_vatrates as $rate)\n\t\t\t{\n\t\t\t\t// Keep only 0 if seller is not subject to VAT\n\t\t\t\tif ($disabled && $rate['txtva'] != 0) continue;", "\t\t\t\t// Define key to use into select list\n\t\t\t\t$key = $rate['txtva'];\n\t\t\t\t$key.= $rate['nprtva'] ? '*': '';\n\t\t\t\tif ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';\n\t\t\t\tif ($mode < 0) $key = $rate['rowid'];", "\t\t\t\t$return.= '<option value=\"'.$key.'\"';\n\t\t\t\tif (! $selectedfound)\n\t\t\t\t{\n\t\t\t\t\tif ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($defaultcode == $rate['code'])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$return.= ' selected';\n\t\t\t\t\t\t\t$selectedfound=true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)\n\t\t\t \t\t{\n\t\t\t \t\t\t$return.= ' selected';\n\t\t\t \t\t\t$selectedfound=true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$return.= '>';\n\t\t\t\t//if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))\n\t\t\t\tif ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))\n\t\t\t\t{\n\t\t\t\t\t$return.= $rate['labelpositiverates'];\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$return.= vatrate($rate['label']);\n\t\t\t\t}\n\t\t\t\t//$return.=($rate['code']?' '.$rate['code']:'');\n\t\t\t\t$return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': ''; // We show the * (old behaviour only if new vat code is not used)", "\t\t\t\t$return.= '</option>';\n\t\t\t}", "\t\t\tif (! $options_only) $return.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$return.= $this->error;\n\t\t}", "\t\t$this->num = $num;\n\t\treturn $return;\n\t}", "\n\t/**\n\t *\tShow a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.\n\t * Fields are preselected with :\n\t * \t- set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')\n\t * \t- local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)\n\t * \t- Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)\n\t *\n\t *\t@param\ttimestamp\t$set_time \t\tPre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0).\n\t *\t@param\tstring\t\t$prefix\t\t\tPrefix for fields name\n\t *\t@param\tint\t\t\t$h\t\t\t\t1=Show also hours (-1 has same effect, but hour and minutes are prefilled with 23:59 if $set_time = -1)\n\t *\t@param\tint\t\t\t$m\t\t\t\t1=Show also minutes\n\t *\t@param\tint\t\t\t$empty\t\t\t0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only\n\t *\t@param\tstring\t\t$form_name \t\tNot used\n\t *\t@param\tint\t\t\t$d\t\t\t\t1=Show days, month, years\n\t * \t@param\tint\t\t\t$addnowlink\t\tAdd a link \"Now\"\n\t * \t@param\tint\t\t\t$nooutput\t\tDo not output html string but return it\n\t * \t@param \tint\t\t\t$disabled\t\tDisable input fields\n\t * @param int\t\t\t$fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59\n\t * @param\tstring\t\t$addplusone\t\tAdd a link \"+1 hour\". Value must be name of another select_date field.\n\t * @param datetime $adddateof Add a link \"Date of invoice\" using the following date.\n\t * \t@return\tstring|null\t\t\t\t\t\tNothing or string if nooutput is 1\n\t * @see\tform_date\n\t */\n\tfunction select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name=\"\", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')\n\t{\n\t\tglobal $conf,$langs;", "\t\t$retstring='';", "\t\tif($prefix=='') $prefix='re';\n\t\tif($h == '') $h=0;\n\t\tif($m == '') $m=0;\n\t\t$emptydate=0;\n\t\t$emptyhours=0;\n\t\tif ($empty == 1) { $emptydate=1; $emptyhours=1; }\n\t\tif ($empty == 2) { $emptydate=0; $emptyhours=1; }\n\t\t$orig_set_time=$set_time;", "\t\tif ($set_time === '' && $emptydate == 0)\n\t\t{\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';\n\t\t\t$set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone\n\t\t}", "\t\t// Analysis of the pre-selection date\n\t\tif (preg_match('/^([0-9]+)\\-([0-9]+)\\-([0-9]+)\\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))\n\t\t{\n\t\t\t// Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'\n\t\t\t$syear\t= (! empty($reg[1])?$reg[1]:'');\n\t\t\t$smonth\t= (! empty($reg[2])?$reg[2]:'');\n\t\t\t$sday\t= (! empty($reg[3])?$reg[3]:'');\n\t\t\t$shour\t= (! empty($reg[4])?$reg[4]:'');\n\t\t\t$smin\t= (! empty($reg[5])?$reg[5]:'');\n\t\t}\n\t\telseif (strval($set_time) != '' && $set_time != -1)\n\t\t{\n\t\t\t// set_time est un timestamps (0 possible)\n\t\t\t$syear = dol_print_date($set_time, \"%Y\");\n\t\t\t$smonth = dol_print_date($set_time, \"%m\");\n\t\t\t$sday = dol_print_date($set_time, \"%d\");\n\t\t\tif ($orig_set_time != '')\n\t\t\t{\n\t\t\t\t$shour = dol_print_date($set_time, \"%H\");\n\t\t\t\t$smin = dol_print_date($set_time, \"%M\");\n\t\t\t\t$ssec = dol_print_date($set_time, \"%S\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$shour = '';\n\t\t\t\t$smin = '';\n\t\t\t\t$ssec = '';\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Date est '' ou vaut -1\n\t\t\t$syear = '';\n\t\t\t$smonth = '';\n\t\t\t$sday = '';\n\t\t\t$shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;\n\t\t\t$smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;\n\t\t\t$ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;\n\t\t}", "\t\t// You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'\n\t\t$usecalendar='combo';\n\t\tif (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != \"none\")) {\n\t\t\t$usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);\n\t\t}\n\t\t//if (! empty($conf->browser->phone)) $usecalendar='combo';", "\t\tif ($d)\n\t\t{\n\t\t\t// Show date with popup\n\t\t\tif ($usecalendar != 'combo')\n\t\t\t{\n\t\t\t\t$formated_date='';\n\t\t\t\t//print \"e\".$set_time.\" t \".$conf->format_date_short;\n\t\t\t\tif (strval($set_time) != '' && $set_time != -1)\n\t\t\t\t{\n\t\t\t\t\t//$formated_date=dol_print_date($set_time,$conf->format_date_short);\n\t\t\t\t\t$formated_date=dol_print_date($set_time,$langs->trans(\"FormatDateShortInput\")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript\n\t\t\t\t}", "\t\t\t\t// Calendrier popup version eldy\n\t\t\t\tif ($usecalendar == \"eldy\")\n\t\t\t\t{\n\t\t\t\t\t// Zone de saisie manuelle de la date\n\t\t\t\t\t$retstring.='<input id=\"'.$prefix.'\" name=\"'.$prefix.'\" type=\"text\" class=\"maxwidth75\" maxlength=\"11\" value=\"'.$formated_date.'\"';\n\t\t\t\t\t$retstring.=($disabled?' disabled':'');\n\t\t\t\t\t$retstring.=' onChange=\"dpChangeDay(\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\'); \"'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript\n\t\t\t\t\t$retstring.='>';", "\t\t\t\t\t// Icone calendrier\n\t\t\t\t\tif (! $disabled)\n\t\t\t\t\t{\n\t\t\t\t\t\t$retstring.='<button id=\"'.$prefix.'Button\" type=\"button\" class=\"dpInvisibleButtons\"';\n\t\t\t\t\t\t$base=DOL_URL_ROOT.'/core/';\n\t\t\t\t\t\t$retstring.=' onClick=\"showDP(\\''.$base.'\\',\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\',\\''.$langs->defaultlang.'\\');\"';\n\t\t\t\t\t\t$retstring.='>'.img_object($langs->trans(\"SelectDate\"),'calendarday','class=\"datecallink\"').'</button>';\n\t\t\t\t\t}\n\t\t\t\t\telse $retstring.='<button id=\"'.$prefix.'Button\" type=\"button\" class=\"dpInvisibleButtons\">'.img_object($langs->trans(\"Disabled\"),'calendarday','class=\"datecallink\"').'</button>';", "\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'day\" name=\"'.$prefix.'day\" value=\"'.$sday.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'month\" name=\"'.$prefix.'month\" value=\"'.$smonth.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\" value=\"'.$syear.'\">'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telseif ($usecalendar == 'jquery')\n\t\t\t\t{\n\t\t\t\t\tif (! $disabled)\n\t\t\t\t\t{\n\t\t\t\t\t\t// Output javascript for datepicker\n\t\t\t\t\t\t$retstring.=\"<script type='text/javascript'>\";\n\t\t\t\t\t\t$retstring.=\"$(function(){ $('#\".$prefix.\"').datepicker({\n\t\t\t\t\t\t\tdateFormat: '\".$langs->trans(\"FormatDateShortJQueryInput\").\"',\n\t\t\t\t\t\t\tautoclose: true,\n\t\t\t\t\t\t\ttodayHighlight: true,\";\n\t\t\t\t\t\t\tif (! empty($conf->dol_use_jmobile))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t$retstring.=\"\n\t\t\t\t\t\t\t\tbeforeShow: function (input, datePicker) {\n\t\t\t\t\t\t\t\t\tinput.disabled = true;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonClose: function (dateText, datePicker) {\n\t\t\t\t\t\t\t\t\tthis.disabled = false;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php\n\t\t\t\t\t\t\tif (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$retstring.=\"\n\t\t\t\t\t\t\t\tshowOn: 'button',\n\t\t\t\t\t\t\t\tbuttonImage: '\".DOL_URL_ROOT.\"/theme/\".$conf->theme.\"/img/object_calendarday.png',\n\t\t\t\t\t\t\t\tbuttonImageOnly: true\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t$retstring.=\"\n\t\t\t\t\t\t\t}) });\";\n\t\t\t\t\t\t$retstring.=\"</script>\";\n\t\t\t\t\t}", "\t\t\t\t\t// Zone de saisie manuelle de la date\n\t\t\t\t\t$retstring.='<input id=\"'.$prefix.'\" name=\"'.$prefix.'\" type=\"text\" class=\"maxwidth75\" maxlength=\"11\" value=\"'.$formated_date.'\"';\n\t\t\t\t\t$retstring.=($disabled?' disabled':'');\n\t\t\t\t\t$retstring.=' onChange=\"dpChangeDay(\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\'); \"'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript\n\t\t\t\t\t$retstring.='>';", "\t\t\t\t\t// Icone calendrier\n\t\t\t\t\tif (! $disabled)\n\t\t\t\t\t{\n\t\t\t\t\t\t/* Not required. Managed by option buttonImage of jquery\n \t\t$retstring.=img_object($langs->trans(\"SelectDate\"),'calendarday','id=\"'.$prefix.'id\" class=\"datecallink\"');\n \t\t$retstring.=\"<script type='text/javascript'>\";\n \t\t$retstring.=\"jQuery(document).ready(function() {\";\n \t\t$retstring.='\tjQuery(\"#'.$prefix.'id\").click(function() {';\n \t\t$retstring.=\" \tjQuery('#\".$prefix.\"').focus();\";\n \t\t$retstring.=' });';\n \t\t$retstring.='});';\n \t\t$retstring.=\"</script>\";*/\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t$retstring.='<button id=\"'.$prefix.'Button\" type=\"button\" class=\"dpInvisibleButtons\">'.img_object($langs->trans(\"Disabled\"),'calendarday','class=\"datecallink\"').'</button>';\n\t\t\t\t\t}", "\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'day\" name=\"'.$prefix.'day\" value=\"'.$sday.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'month\" name=\"'.$prefix.'month\" value=\"'.$smonth.'\">'.\"\\n\";\n\t\t\t\t\t$retstring.='<input type=\"hidden\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\" value=\"'.$syear.'\">'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$retstring.=\"Bad value of MAIN_POPUP_CALENDAR\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Show date with combo selects\n\t\t\telse\n\t\t\t{\n\t\t\t\t//$retstring.='<div class=\"inline-block\">';\n\t\t\t\t// Day\n\t\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth50imp\" id=\"'.$prefix.'day\" name=\"'.$prefix.'day\">';", "\t\t\t\tif ($emptydate || $set_time == -1)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"0\" selected>&nbsp;</option>';\n\t\t\t\t}", "\t\t\t\tfor ($day = 1 ; $day <= 31; $day++)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"'.$day.'\"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';\n\t\t\t\t}", "\t\t\t\t$retstring.=\"</select>\";", "\t\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth75imp\" id=\"'.$prefix.'month\" name=\"'.$prefix.'month\">';\n\t\t\t\tif ($emptydate || $set_time == -1)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"0\" selected>&nbsp;</option>';\n\t\t\t\t}", "\t\t\t\t// Month\n\t\t\t\tfor ($month = 1 ; $month <= 12 ; $month++)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<option value=\"'.$month.'\"'.($month == $smonth?' selected':'').'>';\n\t\t\t\t\t$retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),\"%b\");\n\t\t\t\t\t$retstring.=\"</option>\";\n\t\t\t\t}\n\t\t\t\t$retstring.=\"</select>\";", "\t\t\t\t// Year\n\t\t\t\tif ($emptydate || $set_time == -1)\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<input'.($disabled?' disabled':'').' placeholder=\"'.dol_escape_htmltag($langs->trans(\"Year\")).'\" class=\"flat maxwidth50imp valignmiddle\" type=\"number\" min=\"0\" max=\"3000\" maxlength=\"4\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\" value=\"'.$syear.'\">';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth75imp\" id=\"'.$prefix.'year\" name=\"'.$prefix.'year\">';", "\t\t\t\t\tfor ($year = $syear - 10; $year < $syear + 10 ; $year++)\n\t\t\t\t\t{\n\t\t\t\t\t\t$retstring.='<option value=\"'.$year.'\"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';\n\t\t\t\t\t}\n\t\t\t\t\t$retstring.=\"</select>\\n\";\n\t\t\t\t}\n\t\t\t\t//$retstring.='</div>';\n\t\t\t}\n\t\t}", "\t\tif ($d && $h) $retstring.=($h==2?'<br>':' ');", "\t\tif ($h)\n\t\t{\n\t\t\t// Show hour\n\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'\" id=\"'.$prefix.'hour\" name=\"'.$prefix.'hour\">';\n\t\t\tif ($emptyhours) $retstring.='<option value=\"-1\">&nbsp;</option>';\n\t\t\tfor ($hour = 0; $hour < 24; $hour++)\n\t\t\t{\n\t\t\t\tif (strlen($hour) < 2) $hour = \"0\" . $hour;\n\t\t\t\t$retstring.='<option value=\"'.$hour.'\"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';\n\t\t\t}\n\t\t\t$retstring.='</select>';\n\t\t\tif ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=\":\";\n\t\t}", "\t\tif ($m)\n\t\t{\n\t\t\t// Show minutes\n\t\t\t$retstring.='<select'.($disabled?' disabled':'').' class=\"flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'\" id=\"'.$prefix.'min\" name=\"'.$prefix.'min\">';\n\t\t\tif ($emptyhours) $retstring.='<option value=\"-1\">&nbsp;</option>';\n\t\t\tfor ($min = 0; $min < 60 ; $min++)\n\t\t\t{\n\t\t\t\tif (strlen($min) < 2) $min = \"0\" . $min;\n\t\t\t\t$retstring.='<option value=\"'.$min.'\"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';\n\t\t\t}\n\t\t\t$retstring.='</select>';", "\t\t\t$retstring.='<input type=\"hidden\" name=\"'.$prefix.'sec\" value=\"'.$ssec.'\">';\n\t\t}", "\t\t// Add a \"Now\" link\n\t\tif ($conf->use_javascript_ajax && $addnowlink)\n\t\t{\n\t\t\t// Script which will be inserted in the onClick of the \"Now\" link\n\t\t\t$reset_scripts = \"\";", "\t\t\t// Generate the date part, depending on the use or not of the javascript calendar\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'\\').val(\\''.dol_print_date(dol_now(),'day').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'day\\').val(\\''.dol_print_date(dol_now(),'%d').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'month\\').val(\\''.dol_print_date(dol_now(),'%m').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'year\\').val(\\''.dol_print_date(dol_now(),'%Y').'\\');';\n\t\t\t/*if ($usecalendar == \"eldy\")\n {\n $base=DOL_URL_ROOT.'/core/';\n $reset_scripts .= 'resetDP(\\''.$base.'\\',\\''.$prefix.'\\',\\''.$langs->trans(\"FormatDateShortJavaInput\").'\\',\\''.$langs->defaultlang.'\\');';\n }\n else\n {\n $reset_scripts .= 'this.form.elements[\\''.$prefix.'day\\'].value=formatDate(new Date(), \\'d\\'); ';\n $reset_scripts .= 'this.form.elements[\\''.$prefix.'month\\'].value=formatDate(new Date(), \\'M\\'); ';\n $reset_scripts .= 'this.form.elements[\\''.$prefix.'year\\'].value=formatDate(new Date(), \\'yyyy\\'); ';\n }*/\n\t\t\t// Update the hour part\n\t\t\tif ($h)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t//$reset_scripts .= 'this.form.elements[\\''.$prefix.'hour\\'].value=formatDate(new Date(), \\'HH\\'); ';\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'hour\\').val(\\''.dol_print_date(dol_now(),'%H').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// Update the minute part\n\t\t\tif ($m)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t//$reset_scripts .= 'this.form.elements[\\''.$prefix.'min\\'].value=formatDate(new Date(), \\'mm\\'); ';\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'min\\').val(\\''.dol_print_date(dol_now(),'%M').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// If reset_scripts is not empty, print the link with the reset_scripts in the onClick\n\t\t\tif ($reset_scripts && empty($conf->dol_optimize_smallscreen))\n\t\t\t{\n\t\t\t\t$retstring.=' <button class=\"dpInvisibleButtons datenowlink\" id=\"'.$prefix.'ButtonNow\" type=\"button\" name=\"_useless\" value=\"now\" onClick=\"'.$reset_scripts.'\">';\n\t\t\t\t$retstring.=$langs->trans(\"Now\");\n\t\t\t\t$retstring.='</button> ';\n\t\t\t}\n\t\t}", "\t\t// Add a \"Plus one hour\" link\n\t\tif ($conf->use_javascript_ajax && $addplusone)\n\t\t{\n\t\t\t// Script which will be inserted in the onClick of the \"Add plusone\" link\n\t\t\t$reset_scripts = \"\";", "\t\t\t// Generate the date part, depending on the use or not of the javascript calendar\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'\\').val(\\''.dol_print_date(dol_now(),'day').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'day\\').val(\\''.dol_print_date(dol_now(),'%d').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'month\\').val(\\''.dol_print_date(dol_now(),'%m').'\\');';\n\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'year\\').val(\\''.dol_print_date(dol_now(),'%Y').'\\');';\n\t\t\t// Update the hour part\n\t\t\tif ($h)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'hour\\').val(\\''.dol_print_date(dol_now(),'%H').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// Update the minute part\n\t\t\tif ($m)\n\t\t\t{\n\t\t\t\tif ($fullday) $reset_scripts .= \" if (jQuery('#fullday:checked').val() == null) {\";\n\t\t\t\t$reset_scripts .= 'jQuery(\\'#'.$prefix.'min\\').val(\\''.dol_print_date(dol_now(),'%M').'\\');';\n\t\t\t\tif ($fullday) $reset_scripts .= ' } ';\n\t\t\t}\n\t\t\t// If reset_scripts is not empty, print the link with the reset_scripts in the onClick\n\t\t\tif ($reset_scripts && empty($conf->dol_optimize_smallscreen))\n\t\t\t{\n\t\t\t\t$retstring.=' <button class=\"dpInvisibleButtons datenowlink\" id=\"'.$prefix.'ButtonPlusOne\" type=\"button\" name=\"_useless2\" value=\"plusone\" onClick=\"'.$reset_scripts.'\">';\n\t\t\t\t$retstring.=$langs->trans(\"DateStartPlusOne\");\n\t\t\t\t$retstring.='</button> ';\n\t\t\t}\n\t\t}", "\t\t// Add a \"Plus one hour\" link\n\t\tif ($conf->use_javascript_ajax && $adddateof)\n\t\t{\n\t\t\t$tmparray=dol_getdate($adddateof);\n\t\t\t$retstring.=' - <button class=\"dpInvisibleButtons datenowlink\" id=\"dateofinvoice\" type=\"button\" name=\"_dateofinvoice\" value=\"now\" onclick=\"jQuery(\\'#re\\').val(\\''.dol_print_date($adddateof,'day').'\\');jQuery(\\'#reday\\').val(\\''.$tmparray['mday'].'\\');jQuery(\\'#remonth\\').val(\\''.$tmparray['mon'].'\\');jQuery(\\'#reyear\\').val(\\''.$tmparray['year'].'\\');\">'.$langs->trans(\"DateInvoice\").'</a>';\n\t\t}", "\t\tif (! empty($nooutput)) return $retstring;", "\t\tprint $retstring;\n\t\treturn;\n\t}", "\t/**\n\t *\tFunction to show a form to select a duration on a page\n\t *\n\t *\t@param\tstring\t$prefix \t\tPrefix for input fields\n\t *\t@param int\t$iSecond \t\t Default preselected duration (number of seconds or '')\n\t * \t@param\tint\t$disabled Disable the combo box\n\t * \t@param\tstring\t$typehour\t\tIf 'select' then input hour and input min is a combo,\n\t *\t\t\t\t\t\t if 'text' input hour is in text and input min is a text,\n\t *\t\t\t\t\t\t if 'textselect' input hour is in text and input min is a combo\n\t * @param\tinteger\t$minunderhours\tIf 1, show minutes selection under the hours\n\t * \t@param\tint\t$nooutput\t\t Do not output html string but return it\n\t * @return\tstring|null\n\t */\n\tfunction select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)\n\t{\n\t\tglobal $langs;", "\t\t$retstring='';", "\t\t$hourSelected=0; $minSelected=0;", "\t\t// Hours\n\t\tif ($iSecond != '')\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';", "\t\t\t$hourSelected = convertSecondToTime($iSecond,'allhour');\n\t\t\t$minSelected = convertSecondToTime($iSecond,'min');\n\t\t}", "\t\tif ($typehour=='select' )\n\t\t{\n\t\t\t$retstring.='<select class=\"flat\" name=\"'.$prefix.'hour\"'.($disabled?' disabled':'').'>';\n\t\t\tfor ($hour = 0; $hour < 25; $hour++)\t// For a duration, we allow 24 hours\n\t\t\t{\n\t\t\t\t$retstring.='<option value=\"'.$hour.'\"';\n\t\t\t\tif ($hourSelected == $hour)\n\t\t\t\t{\n\t\t\t\t\t$retstring.=\" selected\";\n\t\t\t\t}\n\t\t\t\t$retstring.=\">\".$hour.\"</option>\";\n\t\t\t}\n\t\t\t$retstring.=\"</select>\";\n\t\t}\n\t\telseif ($typehour=='text' || $typehour=='textselect')\n\t\t{\n\t\t\t$retstring.='<input placeholder=\"'.$langs->trans('HourShort').'\" type=\"number\" min=\"0\" size=\"1\" name=\"'.$prefix.'hour\"'.($disabled?' disabled':'').' class=\"flat maxwidth50 inputhour\" value=\"'.(($hourSelected != '')?((int) $hourSelected):'').'\">';\n\t\t}\n\t\telse return 'BadValueForParameterTypeHour';", "\t\tif ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');\n\t\telse $retstring.='<span class=\"hideonsmartphone\">:</span>';", "\t\t// Minutes\n\t\tif ($minunderhours) $retstring.='<br>';\n\t\telse $retstring.='<span class=\"hideonsmartphone\">&nbsp;</span>';", "\t\tif ($typehour=='select' || $typehour=='textselect')\n\t\t{\n\t\t\t$retstring.='<select class=\"flat\" name=\"'.$prefix.'min\"'.($disabled?' disabled':'').'>';\n\t\t\tfor ($min = 0; $min <= 55; $min=$min+5)\n\t\t\t{\n\t\t\t\t$retstring.='<option value=\"'.$min.'\"';\n\t\t\t\tif ($minSelected == $min) $retstring.=' selected';\n\t\t\t\t$retstring.='>'.$min.'</option>';\n\t\t\t}\n\t\t\t$retstring.=\"</select>\";\n\t\t}\n\t\telseif ($typehour=='text' )\n\t\t{\n\t\t\t$retstring.='<input placeholder=\"'.$langs->trans('MinuteShort').'\" type=\"number\" min=\"0\" size=\"1\" name=\"'.$prefix.'min\"'.($disabled?' disabled':'').' class=\"flat maxwidth50 inputminute\" value=\"'.(($minSelected != '')?((int) $minSelected):'').'\">';\n\t\t}", "\t\tif ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');", "\t\t//$retstring.=\"&nbsp;\";", "\t\tif (! empty($nooutput)) return $retstring;", "\t\tprint $retstring;\n\t\treturn;\n\t}", "\n\t/**\n\t * Generic method to select a component from a combo list.\n\t * This is the generic method that will replace all specific existing methods.\n\t *\n\t * @param \tstring\t\t\t$objectdesc\t\t\tObjectclassname:Objectclasspath\n\t * @param\tstring\t\t\t$htmlname\t\t\tName of HTML select component\n\t * @param\tint\t\t\t\t$preselectedvalue\tPreselected value (ID of element)\n\t * @param\tstring\t\t\t$showempty\t\t\t''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)\n\t * @param\tstring\t\t\t$searchkey\t\t\tSearch criteria\n\t * @param\tstring\t\t\t$placeholder\t\tPlace holder\n\t * @param\tstring\t\t\t$morecss\t\t\tMore CSS\n\t * @param\tstring\t\t\t$moreparams\t\t\tMore params provided to ajax call\n\t * @param\tint\t\t\t\t$forcecombo\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @return\tstring\t\t\t\t\t\t\t\tReturn HTML string\n\t * @see selectForFormsList select_thirdparty\n\t */\n\tfunction selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)\n\t{\n\t\tglobal $conf, $user;", "\t\t$objecttmp = null;", "\t\t$InfoFieldList = explode(\":\", $objectdesc);\n\t\t$classname=$InfoFieldList[0];\n\t\t$classpath=$InfoFieldList[1];\n\t\tif (! empty($classpath))\n\t\t{\n\t\t\tdol_include_once($classpath);\n\t\t\tif ($classname && class_exists($classname))\n\t\t\t{\n\t\t\t\t$objecttmp = new $classname($this->db);\n\t\t\t}\n\t\t}\n\t\tif (! is_object($objecttmp))\n\t\t{\n\t\t\tdol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);\n\t\t\treturn 'Error bad setup of type for field '.join(',', $InfoFieldList);\n\t\t}", "\t\t$prefixforautocompletemode=$objecttmp->element;\n\t\tif ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';\n\t\t$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';\t// For example COMPANY_USE_SEARCH_TO_SELECT", "\t\tdol_syslog(get_class($this).\"::selectForForms\", LOG_DEBUG);", "\t\t$out='';\n\t\tif (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)\n\t\t{\n\t\t\t$objectdesc=$classname.':'.$classpath;\n\t\t\t$urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';\n\t\t\t//if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';", "\t\t\t// No immediate load of all database\n\t\t\t$urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');\n\t\t\t// Activate the auto complete using ajax call.\n\t\t\t$out.= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());\n\t\t\t$out.= '<style type=\"text/css\">.ui-autocomplete { z-index: 250; }</style>';\n\t\t\tif ($placeholder) $placeholder=' placeholder=\"'.$placeholder.'\"';\n\t\t\t$out.= '<input type=\"text\" class=\"'.$morecss.'\" name=\"search_'.$htmlname.'\" id=\"search_'.$htmlname.'\" value=\"'.$preselectedvalue.'\"'.$placeholder.' />';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Immediate load of all database\n\t\t\t$out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Output html form to select an object.\n\t * Note, this function is called by selectForForms or by ajax selectobject.php\n\t *\n\t * @param \tObject\t\t\t$objecttmp\t\t\tObject\n\t * @param\tstring\t\t\t$htmlname\t\t\tName of HTML select component\n\t * @param\tint\t\t\t\t$preselectedvalue\tPreselected value (ID of element)\n\t * @param\tstring\t\t\t$showempty\t\t\t''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)\n\t * @param\tstring\t\t\t$searchkey\t\t\tSearch value\n\t * @param\tstring\t\t\t$placeholder\t\tPlace holder\n\t * @param\tstring\t\t\t$morecss\t\t\tMore CSS\n\t * @param\tstring\t\t\t$moreparams\t\t\tMore params provided to ajax call\n\t * @param\tint\t\t\t\t$forcecombo\t\t\tForce to load all values and output a standard combobox (with no beautification)\n\t * @param\tint\t\t\t\t$outputmode\t\t\t0=HTML select string, 1=Array\n\t * @return\tstring\t\t\t\t\t\t\t\tReturn HTML string\n\t * @see selectForForms\n\t */\n\tfunction selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)\n\t{\n\t\tglobal $conf, $langs, $user;", "\t\t$prefixforautocompletemode=$objecttmp->element;\n\t\tif ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';\n\t\t$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';\t// For example COMPANY_USE_SEARCH_TO_SELECT", "\t\t$fieldstoshow='t.ref';\n\t\tif (! empty($objecttmp->fields))\t// For object that declare it, it is better to use declared fields ( like societe, contact, ...)\n\t\t{\n\t\t\t$tmpfieldstoshow='';\n\t\t\tforeach($objecttmp->fields as $key => $val)\n\t\t\t{\n\t\t\t\tif ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;\n\t\t\t}\n\t\t\tif ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;\n\t\t}", "\t\t$out='';\n\t\t$outarray=array();", "\t\t$num=0;", "\t\t// Search data\n\t\t$sql = \"SELECT t.rowid, \".$fieldstoshow.\" FROM \".MAIN_DB_PREFIX .$objecttmp->table_element.\" as t\";\n\t\tif ($objecttmp->ismultientitymanaged == 2)\n\t\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= \", \".MAIN_DB_PREFIX.\"societe_commerciaux as sc\";\n\t\t$sql.= \" WHERE 1=1\";\n\t\tif(! empty($objecttmp->ismultientitymanaged)) $sql.= \" AND t.entity IN (\".getEntity($objecttmp->table_element).\")\";\n\t\tif ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))\n\t\t{\n\t\t\tif ($objecttmp->element == 'societe') $sql.= \" AND t.rowid = \".$user->societe_id;\n\t\t\t\telse $sql.= \" AND t.fk_soc = \".$user->societe_id;\n\t\t}\n\t\tif ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);\n\t\tif ($objecttmp->ismultientitymanaged == 2)\n\t\t\tif (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= \" AND t.rowid = sc.fk_soc AND sc.fk_user = \" .$user->id;\n\t\t$sql.=$this->db->order($fieldstoshow,\"ASC\");\n\t\t//$sql.=$this->db->plimit($limit, 0);", "\t\t// Build output string\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\tif (! $forcecombo)\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t\t$out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);\n\t\t\t}", "\t\t\t// Construct $out and $outarray\n\t\t\t$out.= '<select id=\"'.$htmlname.'\" class=\"flat'.($morecss?' '.$morecss:'').'\"'.($moreparams?' '.$moreparams:'').' name=\"'.$htmlname.'\">'.\"\\n\";", "\t\t\t// Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4\n\t\t\t$textifempty='&nbsp;';", "\t\t\t//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';\n\t\t\tif (! empty($conf->global->$confkeyforautocompletemode))\n\t\t\t{\n\t\t\t\tif ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);\n\t\t\t\telse $textifempty.=$langs->trans(\"All\");\n\t\t\t}\n\t\t\tif ($showempty) $out.= '<option value=\"-1\">'.$textifempty.'</option>'.\"\\n\";", "\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$label='';\n\t\t\t\t\t$tmparray=explode(',', $fieldstoshow);\n\t\t\t\t\tforeach($tmparray as $key => $val)\n\t\t\t\t\t{\n\t\t\t\t\t\t$val = preg_replace('/t\\./','',$val);\n\t\t\t\t\t\t$label .= (($label && $obj->$val)?' - ':'').$obj->$val;\n\t\t\t\t\t}\n\t\t\t\t\tif (empty($outputmode))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\" selected>'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\">'.$label.'</option>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tarray_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));\n\t\t\t\t\t}", "\t\t\t\t\t$i++;\n\t\t\t\t\tif (($i % 10) == 0) $out.=\"\\n\";\n\t\t\t\t}\n\t\t\t}", "\t\t\t$out.= '</select>'.\"\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\t$this->result=array('nbofelement'=>$num);", "\t\tif ($outputmode) return $outarray;\n\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn a HTML select string, built from an array of key+value.\n\t * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.\n\t *\n\t *\t@param\tstring\t\t\t$htmlname Name of html select area. Must start with \"multi\" if this is a multiselect\n\t *\t@param\tarray\t\t\t$array Array (key => value)\n\t *\t@param\tstring|string[]\t$id Preselected key or preselected keys for multiselect\n\t *\t@param\tint|string\t\t$show_empty 0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.\n\t *\t@param\tint\t\t\t\t$key_in_label 1 to show key into label with format \"[key] value\"\n\t *\t@param\tint\t\t\t\t$value_as_key 1 to use value as key\n\t *\t@param string\t\t\t$moreparam Add more parameters onto the select tag. For example 'style=\"width: 95%\"' to avoid select2 component to go over parent container\n\t *\t@param int\t\t\t\t$translate\t\t1=Translate and encode value\n\t * \t@param\tint\t\t\t\t$maxlen\t\t\tLength maximum for labels\n\t * \t@param\tint\t\t\t\t$disabled\t\tHtml select box is disabled\n\t * @param\tstring\t\t\t$sort\t\t\t'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order\n\t * @param\tstring\t\t\t$morecss\t\tAdd more class to css styles\n\t * @param\tint\t\t\t\t$addjscombo\t\t Add js combo\n\t * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set\n\t * @param int $disablebademail Check if an email is found into value and if not disable and colorize entry\n\t * @param int $nohtmlescape No html escaping.\n\t * \t@return\tstring\t\t\t\t\t\t\t HTML select string.\n\t * @see multiselectarray\n\t */\n\tstatic function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)\n\t{\n\t\tglobal $conf, $langs;", "\t\t// Do we want a multiselect ?\n\t\t//$jsbeautify = 0;\n\t\t//if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;\n\t\t$jsbeautify = 1;", "\t\tif ($value_as_key) $array=array_combine($array, $array);", "\t\t$out='';", "\t\t// Add code for jquery to use multiselect\n\t\tif ($addjscombo && $jsbeautify)\n\t\t{\n\t\t\t$minLengthToAutocomplete=0;\n\t\t\t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;", "\t\t\t// Enhance with select2\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t\t$out .= ajax_combobox($htmlname);\n\t\t}", "\t\t$out.='<select id=\"'.preg_replace('/^\\./','',$htmlname).'\" '.($disabled?'disabled ':'').'class=\"flat '.(preg_replace('/^\\./','',$htmlname)).($morecss?' '.$morecss:'').'\"';\n\t\t$out.=' name=\"'.preg_replace('/^\\./','',$htmlname).'\" '.($moreparam?$moreparam:'');\n\t\t$out.='>';", "\t\tif ($show_empty)\n\t\t{\n\t\t\t$textforempty=' ';\n\t\t\tif (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';\t// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.\n\t\t\tif (! is_numeric($show_empty)) $textforempty=$show_empty;\n\t\t\t$out.='<option class=\"optiongrey\" '.($moreparamonempty?$moreparamonempty.' ':'').'value=\"'.($show_empty < 0 ? $show_empty : -1).'\"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'.\"\\n\";\n\t\t}", "\t\tif (is_array($array))\n\t\t{\n\t\t\t// Translate\n\t\t\tif ($translate)\n\t\t\t{\n\t\t\t\tforeach($array as $key => $value)\n\t\t\t\t{\n\t\t\t\t\t$array[$key]=$langs->trans($value);\n\t\t\t\t}\n\t\t\t}", "\t\t\t// Sort\n\t\t\tif ($sort == 'ASC') asort($array);\n\t\t\telseif ($sort == 'DESC') arsort($array);", "\t\t\tforeach($array as $key => $value)\n\t\t\t{\n\t\t\t\t$disabled=''; $style='';\n\t\t\t\tif (! empty($disablebademail))\n\t\t\t\t{\n\t\t\t\t\tif (! preg_match('/&lt;.+@.+&gt;/', $value))\n\t\t\t\t\t{\n\t\t\t\t\t\t//$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);\n\t\t\t\t\t\t$disabled=' disabled';\n\t\t\t\t\t\t$style=' class=\"warning\"';\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tif ($key_in_label)\n\t\t\t\t{\n\t\t\t\t\tif (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));\n\t\t\t\t\telse $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);\n\t\t\t\t\telse $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;\n\t\t\t\t\tif ($value == '' || $value == '-') $selectOptionValue='&nbsp;';\n\t\t\t\t}", "\t\t\t\t$out.='<option value=\"'.$key.'\"';\n\t\t\t\t$out.=$style.$disabled;\n\t\t\t\tif ($id != '' && $id == $key && ! $disabled) $out.=' selected';\t\t// To preselect a value\n\t\t\t\tif ($nohtmlescape) $out.=' data-html=\"'.dol_escape_htmltag($selectOptionValue).'\"';\n\t\t\t\t$out.='>';\n\t\t\t\t//var_dump($selectOptionValue);\n\t\t\t\t$out.=$selectOptionValue;\n\t\t\t\t$out.=\"</option>\\n\";\n\t\t\t}\n\t\t}", "\t\t$out.=\"</select>\";\n\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn a HTML select string, built from an array of key+value but content returned into select come from an Ajax call of an URL.\n\t * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.\n\t *\n\t *\t@param\tstring\t$htmlname \t\tName of html select area\n\t *\t@param\tstring\t$url\t\t\t\t\tUrl. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)\n\t *\t@param\tstring\t$id \t\tPreselected key\n\t *\t@param string\t$moreparam \t\tAdd more parameters onto the select tag\n\t *\t@param string\t$moreparamtourl \t\tAdd more parameters onto the Ajax called URL\n\t * \t@param\tint\t\t$disabled\t\t\t\tHtml select box is disabled\n\t * @param\tint\t\t$minimumInputLength\t\tMinimum Input Length\n\t * @param\tstring\t$morecss\t\t\t\tAdd more class to css styles\n\t * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.\n\t * @param string $placeholder String to use as placeholder\n\t * @param integer $acceptdelayedhtml 1 if caller request to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)\n\t * \t@return\tstring \t\t\t\t\t\tHTML select string\n\t * @see ajax_combobox in ajax.lib.php\n\t */\n\tstatic function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)\n\t{\n\t\tglobal $conf, $langs;\n\t\tglobal $delayedhtmlcontent;", "\t\t// TODO Use an internal dolibarr component instead of select2\n\t\tif (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';", "\t\t$out='<select type=\"text\" class=\"'.$htmlname.($morecss?' '.$morecss:'').'\" '.($moreparam?$moreparam.' ':'').'name=\"'.$htmlname.'\"></select>';", "\t\t$tmpplugin='select2';\n\t\t$outdelayed=\"\\n\".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->\n\t \t<script type=\"text/javascript\">\n\t \t$(document).ready(function () {", " \t '.($callurlonselect ? 'var saveRemoteData = [];':'').'", " $(\".'.$htmlname.'\").select2({\n\t\t\t \tajax: {\n\t\t\t\t \tdir: \"ltr\",\n\t\t\t\t \turl: \"'.$url.'\",\n\t\t\t\t \tdataType: \\'json\\',\n\t\t\t\t \tdelay: 250,\n\t\t\t\t \tdata: function (params) {\n\t\t\t\t \t\treturn {\n\t\t\t\t\t\t \tq: params.term, \t// search term\n\t\t\t\t \t\t\tpage: params.page\n\t\t\t\t \t\t};\n\t\t\t \t\t},\n\t\t\t \t\tprocessResults: function (data) {\n\t\t\t \t\t\t// parse the results into the format expected by Select2.\n\t\t\t \t\t\t// since we are using custom formatting functions we do not need to alter the remote JSON data\n\t\t\t \t\t\t//console.log(data);\n\t\t\t\t\t\t\tsaveRemoteData = data;\n\t\t\t\t \t /* format json result for select2 */\n\t\t\t\t \t result = []\n\t\t\t\t \t $.each( data, function( key, value ) {\n\t\t\t\t \t result.push({id: key, text: value.text});\n });\n\t\t\t \t\t\t//return {results:[{id:\\'none\\', text:\\'aa\\'}, {id:\\'rrr\\', text:\\'Red\\'},{id:\\'bbb\\', text:\\'Search a into projects\\'}], more:false}\n\t\t\t \t\t\t//console.log(result);\n\t\t\t \t\t\treturn {results: result, more: false}\n\t\t\t \t\t},\n\t\t\t \t\tcache: true\n\t\t\t \t},\n\t \t\t\t\tlanguage: select2arrayoflanguage,\n\t\t\t\t\tcontainerCssClass: \\':all:\\',\t\t\t\t\t/* Line to add class of origin SELECT propagated to the new <span class=\"select2-selection...> tag */\n\t\t\t\t placeholder: \"'.dol_escape_js($placeholder).'\",\n\t\t\t \tescapeMarkup: function (markup) { return markup; }, \t// let our custom formatter work\n\t\t\t \tminimumInputLength: '.$minimumInputLength.',\n\t\t\t formatResult: function(result, container, query, escapeMarkup) {\n return escapeMarkup(result.text);\n },\n\t\t\t });", " '.($callurlonselect ? '\n /* Code to execute a GET when we select a value */\n $(\".'.$htmlname.'\").change(function() {\n\t\t\t \tvar selected = $(\".'.$htmlname.'\").val();\n \tconsole.log(\"We select \"+selected)\n\t\t\t $(\".'.$htmlname.'\").val(\"\"); /* reset visible combo value */\n \t\t\t $.each( saveRemoteData, function( key, value ) {\n \t\t\t\t if (key == selected)\n \t\t\t {\n \t\t\t console.log(\"selectArrayAjax - Do a redirect to \"+value.url)\n \t\t\t location.assign(value.url);\n \t\t\t }\n });\n \t\t\t});' : '' ) . '", " \t });\n\t </script>';", "\t\tif ($acceptdelayedhtml)\n\t\t{\n\t\t\t$delayedhtmlcontent.=$outdelayed;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$out.=$outdelayed;\n\t\t}\n\t\treturn $out;\n\t}", "\t/**\n\t *\tShow a multiselect form from an array.\n\t *\n\t *\t@param\tstring\t$htmlname\t\tName of select\n\t *\t@param\tarray\t$array\t\t\tArray with key+value\n\t *\t@param\tarray\t$selected\t\tArray with key+value preselected\n\t *\t@param\tint\t\t$key_in_label 1 pour afficher la key dans la valeur \"[key] value\"\n\t *\t@param\tint\t\t$value_as_key 1 to use value as key\n\t *\t@param string\t$morecss Add more css style\n\t *\t@param int\t\t$translate\t\tTranslate and encode value\n\t * @param\tint\t\t$width\t\t\tForce width of select box. May be used only when using jquery couch. Example: 250, 95%\n\t * @param\tstring\t$moreattrib\t\tAdd more options on select component. Example: 'disabled'\n\t * @param\tstring\t$elemtype\t\tType of element we show ('category', ...)\n\t *\t@return\tstring\t\t\t\t\tHTML multiselect string\n\t * @see selectarray\n\t */\n\tstatic function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='',$elemtype='')\n\t{\n\t\tglobal $conf, $langs;", "\t\t$out = '';", "\t\t// Add code for jquery to use multiselect\n\t\tif (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))\n\t\t{\n\t\t\t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;\n \t\t\t$out.=\"\\n\".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->\n \t\t\t<script type=\"text/javascript\">\n\t \t\t\tfunction formatResult(record) {'.\"\\n\";\n\t\t\t\t\t\tif ($elemtype == 'category')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='\t//return \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> <a href=\"'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\\'+record.id+\\'\">\\'+record.text+\\'</a></span>\\';\n\t\t\t\t\t\t\t\t \treturn \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> \\'+record.text+\\'</span>\\';';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='return record.text;';\n\t\t\t\t\t\t}\n\t\t\t$out.= '\t};\n \t\t\t\tfunction formatSelection(record) {'.\"\\n\";\n\t\t\t\t\t\tif ($elemtype == 'category')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='\t//return \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> <a href=\"'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\\'+record.id+\\'\">\\'+record.text+\\'</a></span>\\';\n\t\t\t\t\t\t\t\t \treturn \\'<span><img src=\"'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'\"> \\'+record.text+\\'</span>\\';';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t$out.='return record.text;';\n\t\t\t\t\t\t}\n\t\t\t$out.= '\t};\n\t \t\t\t$(document).ready(function () {\n \t\t\t\t\t$(\\'#'.$htmlname.'\\').'.$tmpplugin.'({\n \t\t\t\t\t\tdir: \\'ltr\\',\n\t\t\t\t\t\t\t// Specify format function for dropdown item\n\t\t\t\t\t\t\tformatResult: formatResult,\n \t\t\t\t\t \ttemplateResult: formatResult,\t\t/* For 4.0 */\n\t\t\t\t\t\t\t// Specify format function for selected item\n\t\t\t\t\t\t\tformatSelection: formatSelection,\n \t\t\t\t\t \ttemplateResult: formatSelection\t\t/* For 4.0 */\n \t\t\t\t\t});\n \t\t\t\t});\n \t\t\t</script>';\n\t\t}", "\t\t// Try also magic suggest", "\t\t$out .= '<select id=\"'.$htmlname.'\" class=\"multiselect'.($morecss?' '.$morecss:'').'\" multiple name=\"'.$htmlname.'[]\"'.($moreattrib?' '.$moreattrib:'').($width?' style=\"width: '.(preg_match('/%/',$width)?$width:$width.'px').'\"':'').'>'.\"\\n\";\n\t\tif (is_array($array) && ! empty($array))\n\t\t{\n\t\t\tif ($value_as_key) $array=array_combine($array, $array);", "\t\t\tif (! empty($array))\n\t\t\t{\n\t\t\t\tforeach ($array as $key => $value)\n\t\t\t\t{\n\t\t\t\t\t$out.= '<option value=\"'.$key.'\"';\n\t\t\t\t\tif (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= ' selected';\n\t\t\t\t\t}\n\t\t\t\t\t$out.= '>';", "\t\t\t\t\t$newval = ($translate ? $langs->trans($value) : $value);\n\t\t\t\t\t$newval = ($key_in_label ? $key.' - '.$newval : $newval);\n\t\t\t\t\t$out.= dol_htmlentitiesbr($newval);\n\t\t\t\t\t$out.= '</option>'.\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t$out.= '</select>'.\"\\n\";", "\t\treturn $out;\n\t}", "\n\t/**\n\t *\tShow a multiselect dropbox from an array.\n\t *\n\t *\t@param\tstring\t$htmlname\t\tName of HTML field\n\t *\t@param\tarray\t$array\t\t\tArray with array of fields we could show. This array may be modified according to setup of user.\n\t * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER[\"PHP_SELF\"]:$contextpage);\n\t *\t@return\tstring\t\t\t\t\tHTML multiselect string\n\t * @see selectarray\n\t */\n\tstatic function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)\n\t{\n\t\tglobal $conf,$langs,$user;", "\t\tif (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';", "\t\t$tmpvar=\"MAIN_SELECTEDFIELDS_\".$varpage;\n\t\tif (! empty($user->conf->$tmpvar))\n\t\t{\n\t\t\t$tmparray=explode(',', $user->conf->$tmpvar);\n\t\t\tforeach($array as $key => $val)\n\t\t\t{\n\t\t\t\t//var_dump($key);\n\t\t\t\t//var_dump($tmparray);\n\t\t\t\tif (in_array($key, $tmparray)) $array[$key]['checked']=1;\n\t\t\t\telse $array[$key]['checked']=0;\n\t\t\t}\n\t\t}\n\t\t//var_dump($array);", "\t\t$lis='';\n\t\t$listcheckedstring='';", "\t\tforeach($array as $key => $val)\n\t\t{\n\t\t /* var_dump($val);\n var_dump(array_key_exists('enabled', $val));\n var_dump(!$val['enabled']);*/\n\t\t if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])\n\t\t {\n\t\t\t unset($array[$key]); // We don't want this field\n\t\t\t continue;\n\t\t }\n\t\t if ($val['label'])\n\t\t {\n\t\t\t $lis.='<li><input type=\"checkbox\" value=\"'.$key.'\"'.(empty($val['checked'])?'':' checked=\"checked\"').'/>'.dol_escape_htmltag($langs->trans($val['label'])).'</li>';\n\t\t\t $listcheckedstring.=(empty($val['checked'])?'':$key.',');\n\t\t }\n\t\t}", "\t\t$out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->", " <dl class=\"dropdown\">\n <dt>\n <a href=\"#\">\n '.img_picto('','list').'\n </a>\n <input type=\"hidden\" class=\"'.$htmlname.'\" name=\"'.$htmlname.'\" value=\"'.$listcheckedstring.'\">\n </dt>\n <dd class=\"dropowndd\">\n <div class=\"multiselectcheckbox'.$htmlname.'\">\n <ul class=\"ul'.$htmlname.'\">\n '.$lis.'\n </ul>\n </div>\n </dd>\n </dl>", " <script type=\"text/javascript\">\n jQuery(document).ready(function () {\n $(\\'.multiselectcheckbox'.$htmlname.' input[type=\"checkbox\"]\\').on(\\'click\\', function () {\n console.log(\"A new field was added/removed\")\n $(\"input:hidden[name=formfilteraction]\").val(\\'listafterchangingselectedfields\\')\n var title = $(this).val() + \",\";\n if ($(this).is(\\':checked\\')) {\n $(\\'.'.$htmlname.'\\').val(title + $(\\'.'.$htmlname.'\\').val());\n }\n else {\n $(\\'.'.$htmlname.'\\').val( $(\\'.'.$htmlname.'\\').val().replace(title, \\'\\') )\n }\n // Now, we submit page\n $(this).parents(\\'form:first\\').submit();\n });\n });\n </script>", " ';\n\t\treturn $out;\n\t}", "\t/**\n\t * \tRender list of categories linked to object with id $id and type $type\n\t *\n\t * \t@param\t\tint\t\t$id\t\t\t\tId of object\n\t * \t@param\t\tstring\t$type\t\t\tType of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.\n\t * @param\t\tint\t\t$rendermode\t\t0=Default, use multiselect. 1=Emulate multiselect (recommended)\n\t * \t@return\t\tstring\t\t\t\t\tString with categories\n\t */\n\tfunction showCategories($id, $type, $rendermode=0)\n\t{\n\t\tglobal $db;", "\t\tinclude_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';", "\t\t$cat = new Categorie($db);\n\t\t$categories = $cat->containing($id, $type);", "\t\tif ($rendermode == 1)\n\t\t{\n\t\t\t$toprint = array();\n\t\t\tforeach($categories as $c)\n\t\t\t{\n\t\t\t\t$ways = $c->print_all_ways(); // $ways[0] = \"ccc2 >> ccc2a >> ccc2a1\" with html formated text\n\t\t\t\tforeach($ways as $way)\n\t\t\t\t{\n\t\t\t\t\t$toprint[] = '<li class=\"select2-search-choice-dolibarr noborderoncategories\"'.($c->color?' style=\"background: #'.$c->color.';\"':' style=\"background: #aaa\"').'>'.img_object('','category').' '.$way.'</li>';\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn '<div class=\"select2-container-multi-dolibarr\" style=\"width: 90%;\"><ul class=\"select2-choices-dolibarr\">'.implode(' ', $toprint).'</ul></div>';\n\t\t}", "\t\tif ($rendermode == 0)\n\t\t{\n\t\t\t$cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);\n\t\t\tforeach($categories as $c) {\n\t\t\t\t$arrayselected[] = $c->id;\n\t\t\t}", "\t\t\treturn $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');\n\t\t}", "\t\treturn 'ErrorBadValueForParameterRenderMode';\t// Should not happened\n\t}", "\n\t/**\n\t * Show linked object block.\n\t *\n\t * @param\tCommonObject\t$object\t\t Object we want to show links to\n\t * @param string $morehtmlright More html to show on right of title\n\t * @return\tint\t\t\t\t\t\t\t <0 if KO, >=0 if OK\n\t */\n\tfunction showLinkedObjectBlock($object, $morehtmlright='')\n\t{\n\t\tglobal $conf,$langs,$hookmanager;\n\t\tglobal $bc;", "\t\t$object->fetchObjectLinked();", "\t\t// Bypass the default method\n\t\t$hookmanager->initHooks(array('commonobject'));\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook", "\t\tif (empty($reshook))\n\t\t{\n\t\t\t$nbofdifferenttypes = count($object->linkedObjects);", "\t\t\tprint '<!-- showLinkedObjectBlock -->';\n\t\t\tprint load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');", "\n\t\t\tprint '<div class=\"div-table-responsive-no-min\">';\n\t\t\tprint '<table class=\"noborder allwidth\">';", "\t\t\tprint '<tr class=\"liste_titre\">';\n\t\t\tprint '<td>'.$langs->trans(\"Type\").'</td>';\n\t\t\tprint '<td>'.$langs->trans(\"Ref\").'</td>';\n\t\t\tprint '<td align=\"center\"></td>';\n\t\t\tprint '<td align=\"center\">'.$langs->trans(\"Date\").'</td>';\n\t\t\tprint '<td align=\"right\">'.$langs->trans(\"AmountHTShort\").'</td>';\n\t\t\tprint '<td align=\"right\">'.$langs->trans(\"Status\").'</td>';\n\t\t\tprint '<td></td>';\n\t\t\tprint '</tr>';", "\t\t\t$nboftypesoutput=0;", "\t\t\tforeach($object->linkedObjects as $objecttype => $objects)\n\t\t\t{\n\t\t\t\t$tplpath = $element = $subelement = $objecttype;", "\t\t\t\tif ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))\n\t\t\t\t{\n\t\t\t\t\t$element = $regs[1];\n\t\t\t\t\t$subelement = $regs[2];\n\t\t\t\t\t$tplpath = $element.'/'.$subelement;\n\t\t\t\t}\n\t\t\t\t$tplname='linkedobjectblock';", "\t\t\t\t// To work with non standard path\n\t\t\t\tif ($objecttype == 'facture') {\n\t\t\t\t\t$tplpath = 'compta/'.$element;\n\t\t\t\t\tif (empty($conf->facture->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'facturerec') {\n\t\t\t\t\t$tplpath = 'compta/facture';\n\t\t\t\t\t$tplname = 'linkedobjectblockForRec';\n\t\t\t\t\tif (empty($conf->facture->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'propal') {\n\t\t\t\t\t$tplpath = 'comm/'.$element;\n\t\t\t\t\tif (empty($conf->propal->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'supplier_proposal') {\n\t\t\t\t\tif (empty($conf->supplier_proposal->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'shipping' || $objecttype == 'shipment') {\n\t\t\t\t\t$tplpath = 'expedition';\n\t\t\t\t\tif (empty($conf->expedition->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'delivery') {\n\t\t\t\t\t$tplpath = 'livraison';\n\t\t\t\t\tif (empty($conf->expedition->enabled)) continue;\t// Do not show if module disabled\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'invoice_supplier') {\n\t\t\t\t\t$tplpath = 'fourn/facture';\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'order_supplier') {\n\t\t\t\t\t$tplpath = 'fourn/commande';\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'expensereport') {\n\t\t\t\t\t$tplpath = 'expensereport';\n\t\t\t\t}\n\t\t\t\telse if ($objecttype == 'subscription') {\n\t\t\t\t\t$tplpath = 'adherents';\n\t\t\t\t}", "\t\t\t\tglobal $linkedObjectBlock;\n\t\t\t\t$linkedObjectBlock = $objects;", "\n\t\t\t\t// Output template part (modules that overwrite templates must declare this into descriptor)\n\t\t\t\t$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));\n\t\t\t\tforeach($dirtpls as $reldir)\n\t\t\t\t{\n\t\t\t\t\tif ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after\n\t\t\t\t\t{\n\t\t\t\t\t\tglobal $noMoreLinkedObjectBlockAfter;\n\t\t\t\t\t\t$noMoreLinkedObjectBlockAfter=1;\n\t\t\t\t\t}", "\t\t\t\t\t$res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');\n\t\t\t\t\tif ($res)\n\t\t\t\t\t{\n\t\t\t\t\t\t$nboftypesoutput++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (! $nboftypesoutput)\n\t\t\t{\n\t\t\t\tprint '<tr><td class=\"impair opacitymedium\" colspan=\"7\">'.$langs->trans(\"None\").'</td></tr>';\n\t\t\t}", "\t\t\tprint '</table>';\n\t\t\tprint '</div>';", "\t\t\treturn $nbofdifferenttypes;\n\t\t}\n\t}", "\t/**\n\t * Show block with links to link to other objects.\n\t *\n\t * @param\tCommonObject\t$object\t\t\t\tObject we want to show links to\n\t * @param\tarray\t\t\t$restrictlinksto\tRestrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.\n\t * @param\tarray\t\t\t$excludelinksto\t\tDo not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.\n\t * @return\tstring\t\t\t\t\t\t\t\t<0 if KO, >0 if OK\n\t */\n\tfunction showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())\n\t{\n\t\tglobal $conf, $langs, $hookmanager;\n\t\tglobal $bc;", "\t\t$linktoelem='';\n\t\t$linktoelemlist='';", "\t\tif (! is_object($object->thirdparty)) $object->fetch_thirdparty();", "\t\t$possiblelinks=array();\n\t\tif (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)\n\t\t{\n\t\t\t$listofidcompanytoscan=$object->thirdparty->id;\n\t\t\tif (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;\n\t\t\tif (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))\n\t\t\t{\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';\n\t\t\t\t$tmpproject=new Project($this->db);\n\t\t\t\t$tmpproject->fetch($object->fk_project);\n\t\t\t\tif ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;\n\t\t\t\tunset($tmpproject);\n\t\t\t}", "\t\t\t$possiblelinks=array(\n\t\t\t\t'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),\n\t\t\t\t'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),\n\t\t\t\t'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.facnumber as ref, t.ref_client, t.total as total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture').')'),\n\t\t\t\t'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),\n\t\t\t\t'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),\n\t\t\t\t'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),\n\t\t\t\t'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),\n\t\t\t\t'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>\"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM \".MAIN_DB_PREFIX.\"societe as s, \".MAIN_DB_PREFIX.\"facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (\".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')\n\t\t\t);\n\t\t}", "\t\tglobal $action;", "\t\t// Can complete the possiblelink array\n\t\t$hookmanager->initHooks(array('commonobject'));\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n\t\tif (empty($reshook))\n\t\t{\n\t\t\tif (is_array($hookmanager->resArray) && count($hookmanager->resArray))\n\t\t\t{\n\t\t\t\t$possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);\n\t\t\t}\n\t\t}\n\t\telse if ($reshook > 0)\n\t\t{\n\t\t\tif (is_array($hookmanager->resArray) && count($hookmanager->resArray))\n\t\t\t{\n\t\t\t\t$possiblelinks=$hookmanager->resArray;\n\t\t\t}\n\t\t}", "\t\tforeach($possiblelinks as $key => $possiblelink)\n\t\t{\n\t\t\t$num = 0;", "\t\t\tif (empty($possiblelink['enabled'])) continue;", "\t\t\tif (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))\n\t\t\t{\n\t\t\t\tprint '<div id=\"'.$key.'list\"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style=\"display:none\"':'').'>';\n\t\t\t\t$sql = $possiblelink['sql'];", "\t\t\t\t$resqllist = $this->db->query($sql);\n\t\t\t\tif ($resqllist)\n\t\t\t\t{\n\t\t\t\t\t$num = $this->db->num_rows($resqllist);\n\t\t\t\t\t$i = 0;", "\t\t\t\t\tprint '<br><form action=\"'.$_SERVER[\"PHP_SELF\"].'\" method=\"POST\" name=\"formlinked'.$key.'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"id\" value=\"'.$object->id.'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"addlink\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"addlink\" value=\"'.$key.'\">';\n\t\t\t\t\tprint '<table class=\"noborder\">';\n\t\t\t\t\tprint '<tr class=\"liste_titre\">';\n\t\t\t\t\tprint '<td class=\"nowrap\"></td>';\n\t\t\t\t\tprint '<td align=\"center\">' . $langs->trans(\"Ref\") . '</td>';\n\t\t\t\t\tprint '<td align=\"left\">' . $langs->trans(\"RefCustomer\") . '</td>';\n\t\t\t\t\tprint '<td align=\"right\">' . $langs->trans(\"AmountHTShort\") . '</td>';\n\t\t\t\t\tprint '<td align=\"left\">' . $langs->trans(\"Company\") . '</td>';\n\t\t\t\t\tprint '</tr>';\n\t\t\t\t\twhile ($i < $num)\n\t\t\t\t\t{\n\t\t\t\t\t\t$objp = $this->db->fetch_object($resqlorderlist);", "\t\t\t\t\t\t$var = ! $var;\n\t\t\t\t\t\tprint '<tr ' . $bc [$var] . '>';\n\t\t\t\t\t\tprint '<td aling=\"left\">';\n\t\t\t\t\t\tprint '<input type=\"radio\" name=\"idtolinkto\" value=' . $objp->rowid . '>';\n\t\t\t\t\t\tprint '</td>';\n\t\t\t\t\t\tprint '<td align=\"center\">' . $objp->ref . '</td>';\n\t\t\t\t\t\tprint '<td>' . $objp->ref_client . '</td>';\n\t\t\t\t\t\tprint '<td align=\"right\">' . price($objp->total_ht) . '</td>';\n\t\t\t\t\t\tprint '<td>' . $objp->name . '</td>';\n\t\t\t\t\t\tprint '</tr>';\n\t\t\t\t\t\t$i++;\n\t\t\t\t\t}\n\t\t\t\t\tprint '</table>';\n\t\t\t\t\tprint '<div class=\"center\"><input type=\"submit\" class=\"button valignmiddle\" value=\"' . $langs->trans('ToLink') . '\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"submit\" class=\"button\" name=\"cancel\" value=\"' . $langs->trans('Cancel') . '\"></div>';", "\t\t\t\t\tprint '</form>';\n\t\t\t\t\t$this->db->free($resqllist);\n\t\t\t\t} else {\n\t\t\t\t\tdol_print_error($this->db);\n\t\t\t\t}\n\t\t\t\tprint '</div>';\n\t\t\t\tif ($num > 0)\n\t\t\t\t{\n\t\t\t\t}", "\t\t\t\t//$linktoelem.=($linktoelem?' &nbsp; ':'');\n\t\t\t\tif ($num > 0) $linktoelemlist.='<li><a href=\"#linkto'.$key.'\" class=\"linkto dropdowncloseonclick\" rel=\"'.$key.'\">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';\n\t\t\t\t//else $linktoelem.=$langs->trans($possiblelink['label']);\n\t\t\t\telse $linktoelemlist.='<li><span class=\"linktodisabled\">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';\n\t\t\t}\n\t\t}", "\t\tif ($linktoelemlist)\n\t\t{\n\t\t\t$linktoelem='\n \t\t<dl class=\"dropdown\" id=\"linktoobjectname\">\n \t\t<dt><a href=\"#linktoobjectname\">'.$langs->trans(\"LinkTo\").'...</a></dt>\n \t\t<dd>\n \t\t<div class=\"multiselectlinkto\">\n \t\t<ul class=\"ulselectedfields\">'.$linktoelemlist.'\n \t\t</ul>\n \t\t</div>\n \t\t</dd>\n \t\t</dl>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$linktoelem='';\n\t\t}", "\t\tprint '<!-- Add js to show linkto box -->\n\t\t\t\t<script type=\"text/javascript\" language=\"javascript\">\n\t\t\t\tjQuery(document).ready(function() {\n\t\t\t\t\tjQuery(\".linkto\").click(function() {\n\t\t\t\t\t\tconsole.log(\"We choose to show/hide link for rel=\"+jQuery(this).attr(\\'rel\\'));\n\t\t\t\t\t jQuery(\"#\"+jQuery(this).attr(\\'rel\\')+\"list\").toggle();\n\t\t\t\t\t\tjQuery(this).toggle();\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\t</script>\n\t\t';", "\t\treturn $linktoelem;\n\t}", "\t/**\n\t *\tReturn an html string with a select combo box to choose yes or no\n\t *\n\t *\t@param\tstring\t\t$htmlname\t\tName of html select field\n\t *\t@param\tstring\t\t$value\t\t\tPre-selected value\n\t *\t@param\tint\t\t\t$option\t\t\t0 return yes/no, 1 return 1/0\n\t *\t@param\tbool\t\t$disabled\t\ttrue or false\n\t * @param\tint \t$useempty\t\t1=Add empty line\n\t *\t@return\tstring\t\t\t\t\t\tSee option\n\t */\n\tfunction selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty='')\n\t{\n\t\tglobal $langs;", "\t\t$yes=\"yes\"; $no=\"no\";\n\t\tif ($option)\n\t\t{\n\t\t\t$yes=\"1\";\n\t\t\t$no=\"0\";\n\t\t}", "\t\t$disabled = ($disabled ? ' disabled' : '');", "\t\t$resultyesno = '<select class=\"flat\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.$disabled.'>'.\"\\n\";\n\t\tif ($useempty) $resultyesno .= '<option value=\"-1\"'.(($value < 0)?' selected':'').'>&nbsp;</option>'.\"\\n\";\n\t\tif ((\"$value\" == 'yes') || ($value == 1))\n\t\t{\n\t\t\t$resultyesno .= '<option value=\"'.$yes.'\" selected>'.$langs->trans(\"Yes\").'</option>'.\"\\n\";\n\t\t\t$resultyesno .= '<option value=\"'.$no.'\">'.$langs->trans(\"No\").'</option>'.\"\\n\";\n\t\t}\n\t\telse\n\t {\n\t \t\t$selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');\n\t\t\t$resultyesno .= '<option value=\"'.$yes.'\">'.$langs->trans(\"Yes\").'</option>'.\"\\n\";\n\t\t\t$resultyesno .= '<option value=\"'.$no.'\"'.$selected.'>'.$langs->trans(\"No\").'</option>'.\"\\n\";\n\t\t}\n\t\t$resultyesno .= '</select>'.\"\\n\";\n\t\treturn $resultyesno;\n\t}", "", "\t/**\n\t * Return list of export templates\n\t *\n\t * @param\tstring\t$selected Id modele pre-selectionne\n\t * @param string\t$htmlname Name of HTML select\n\t * @param string\t$type Type of searched templates\n\t * @param int\t\t$useempty Affiche valeur vide dans liste\n\t * @return\tvoid\n\t */\n\tfunction select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)\n\t{", "\t\t$sql = \"SELECT rowid, label\";\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"export_model\";\n\t\t$sql.= \" WHERE type = '\".$type.\"'\";\n\t\t$sql.= \" ORDER BY rowid\";\n\t\t$result = $this->db->query($sql);\n\t\tif ($result)\n\t\t{\n\t\t\tprint '<select class=\"flat\" name=\"'.$htmlname.'\">';\n\t\t\tif ($useempty)\n\t\t\t{\n\t\t\t\tprint '<option value=\"-1\">&nbsp;</option>';\n\t\t\t}", "\t\t\t$num = $this->db->num_rows($result);\n\t\t\t$i = 0;\n\t\t\twhile ($i < $num)\n\t\t\t{\n\t\t\t\t$obj = $this->db->fetch_object($result);\n\t\t\t\tif ($selected == $obj->rowid)\n\t\t\t\t{\n\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\" selected>';\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprint '<option value=\"'.$obj->rowid.'\">';\n\t\t\t\t}\n\t\t\t\tprint $obj->label;\n\t\t\t\tprint '</option>';\n\t\t\t\t$i++;\n\t\t\t}\n\t\t\tprint \"</select>\";\n\t\t}\n\t\telse {\n\t\t\tdol_print_error($this->db);\n\t\t}\n\t}", "\t/**\n\t * Return a HTML area with the reference of object and a navigation bar for a business object\n\t * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.\n\t *\n\t * @param\tobject\t$object\t\t\tObject to show.\n\t * @param\tstring\t$paramid \t\tName of parameter to use to name the id into the URL next/previous link.\n\t * @param\tstring\t$morehtml \t\tMore html content to output just before the nav bar.\n\t * @param\tint\t\t$shownav\t \tShow Condition (navigation is shown if value is 1).\n\t * @param\tstring\t$fieldid \t\tName of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.\n\t * @param\tstring\t$fieldref \tName of field ref of object (object->ref) to show or 'none' to not show ref.\n\t * @param\tstring\t$morehtmlref \tMore html to show after ref.\n\t * @param\tstring\t$moreparam \tMore param to add in nav link url. Must start with '&...'.\n\t *\t @param\tint\t\t$nodbprefix\t\tDo not include DB prefix to forge table name.\n\t *\t @param\tstring\t$morehtmlleft\tMore html code to show before ref.\n\t *\t @param\tstring\t$morehtmlstatus\tMore html code to show under navigation arrows (status place).\n\t *\t @param\tstring\t$morehtmlright\tMore html code to show after ref.\n\t * \t @return\tstring \t\t\t\tPortion HTML with ref + navigation buttons\n\t */\n\tfunction showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')\n\t{\n\t\tglobal $langs,$conf,$hookmanager;", "\t\t$ret='';\n\t\tif (empty($fieldid)) $fieldid='rowid';\n\t\tif (empty($fieldref)) $fieldref='ref';", "\t\t// Add where from hooks\n\t\tif (is_object($hookmanager))\n\t\t{\n\t\t\t$parameters=array();\n\t\t\t$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object); // Note that $action and $object may have been modified by hook\n\t\t\t$object->next_prev_filter.=$hookmanager->resPrint;\n\t\t}\n\t\t$previous_ref = $next_ref = '';\n\t\tif ($shownav)\n\t\t{\n\t\t\t//print \"paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam\";\n\t\t\t$object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);", "\t\t\t$navurl = $_SERVER[\"PHP_SELF\"];\n\t\t\t// Special case for project/task page\n\t\t\tif ($paramid == 'project_ref')\n\t\t\t{\n\t\t\t\t$navurl = preg_replace('/\\/tasks\\/(task|contact|time|note|document)\\.php/','/tasks.php',$navurl);\n\t\t\t\t$paramid='ref';\n\t\t\t}", "\t\t\t// accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox\n\t\t\t// accesskey is for Mac: CTRL + key for all browsers\n\t\t\t$previous_ref = $object->ref_previous?'<a accesskey=\"p\" href=\"'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'\"><i class=\"fa fa-chevron-left\"></i></a>':'<span class=\"inactive\"><i class=\"fa fa-chevron-left opacitymedium\"></i></span>';\n\t\t\t$next_ref = $object->ref_next?'<a accesskey=\"n\" href=\"'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'\"><i class=\"fa fa-chevron-right\"></i></a>':'<span class=\"inactive\"><i class=\"fa fa-chevron-right opacitymedium\"></i></span>';\n\t\t}", "\t\t//print \"xx\".$previous_ref.\"x\".$next_ref;\n\t\t$ret.='<!-- Start banner content --><div style=\"vertical-align: middle\">';", "\t\t// Right part of banner\n\t\tif ($morehtmlright) $ret.='<div class=\"inline-block floatleft\">'.$morehtmlright.'</div>';", "\t\tif ($previous_ref || $next_ref || $morehtml)\n\t\t{\n\t\t\t$ret.='<div class=\"pagination paginationref\"><ul class=\"right\">';\n\t\t}\n\t\tif ($morehtml)\n\t\t{\n\t\t\t$ret.='<li class=\"noborder litext\">'.$morehtml.'</li>';\n\t\t}\n\t\tif ($shownav && ($previous_ref || $next_ref))\n\t\t{\n\t\t\t$ret.='<li class=\"pagination\">'.$previous_ref.'</li>';\n\t\t\t$ret.='<li class=\"pagination\">'.$next_ref.'</li>';\n\t\t}\n\t\tif ($previous_ref || $next_ref || $morehtml)\n\t\t{\n\t\t\t$ret.='</ul></div>';\n\t\t}\n\t\tif ($morehtmlstatus) $ret.='<div class=\"statusref\">'.$morehtmlstatus.'</div>';", "\t\t// Left part of banner\n\t\tif ($morehtmlleft)\n\t\t{\n\t\t\tif ($conf->browser->layout == 'phone') $ret.='<div class=\"floatleft\">'.$morehtmlleft.'</div>'; // class=\"center\" to have photo in middle\n\t\t\telse $ret.='<div class=\"inline-block floatleft\">'.$morehtmlleft.'</div>';\n\t\t}", "\t\t//if ($conf->browser->layout == 'phone') $ret.='<div class=\"clearboth\"></div>';\n\t\t$ret.='<div class=\"inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'\">';", "\t\t// For thirdparty, contact, user, member, the ref is the id, so we show something else\n\t\tif ($object->element == 'societe')\n\t\t{\n\t\t\t$ret.=dol_htmlentities($object->name);\n\t\t}\n\t\telse if ($object->element == 'member')\n\t\t{\n\t\t\t$fullname=$object->getFullName($langs);\n\t\t\tif ($object->morphy == 'mor') {\n\t\t\t\t$ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');\n\t\t\t} else {\n\t\t\t\t$ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');\n\t\t\t}\n\t\t}\n\t\telse if (in_array($object->element, array('contact', 'user', 'usergroup')))\n\t\t{\n\t\t\t$ret.=dol_htmlentities($object->getFullName($langs));\n\t\t}\n\t\telse if (in_array($object->element, array('action', 'agenda')))\n\t\t{\n\t\t\t$ret.=$object->ref.'<br>'.$object->label;\n\t\t}\n\t\telse if (in_array($object->element, array('adherent_type')))\n\t\t{\n\t\t\t$ret.=$object->label;\n\t\t}\n\t\telse if ($object->element == 'ecm_directories')\n\t\t{\n\t\t\t$ret.='';\n\t\t}\n\t\telse if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);", "\n\t\tif ($morehtmlref)\n\t\t{\n\t\t\t$ret.=' '.$morehtmlref;\n\t\t}\n\t\t$ret.='</div>';", "\t\t$ret.='</div><!-- End banner content -->';", "\t\treturn $ret;\n\t}", "\n\t/**\n\t * \tReturn HTML code to output a barcode\n\t *\n\t * \t@param\tObject\t$object\t\tObject containing data to retrieve file name\n\t * \t\t@param\tint\t\t$width\t\t\tWidth of photo\n\t * \t \t@return string \t\t\t\tHTML code to output barcode\n\t */\n\tfunction showbarcode(&$object,$width=100)\n\t{\n\t\tglobal $conf;", "\t\t//Check if barcode is filled in the card\n\t\tif (empty($object->barcode)) return '';", "\t\t// Complete object if not complete\n\t\tif (empty($object->barcode_type_code) || empty($object->barcode_type_coder))\n\t\t{\n\t\t\t$result = $object->fetch_barcode();\n\t\t\t//Check if fetch_barcode() failed\n\t\t\tif ($result < 1) return '<!-- ErrorFetchBarcode -->';\n\t\t}", "\t\t// Barcode image\n\t\t$url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);\n\t\t$out ='<!-- url barcode = '.$url.' -->';\n\t\t$out.='<img src=\"'.$url.'\">';\n\t\treturn $out;\n\t}", "\t/**\n\t * \tReturn HTML code to output a photo\n\t *\n\t * \t@param\tstring\t\t$modulepart\t\t\tKey to define module concerned ('societe', 'userphoto', 'memberphoto')\n\t * \t@param object\t\t$object\t\t\t\tObject containing data to retrieve file name\n\t * \t\t@param\tint\t\t\t$width\t\t\t\tWidth of photo\n\t * \t\t@param\tint\t\t\t$height\t\t\t\tHeight of photo (auto if 0)\n\t * \t\t@param\tint\t\t\t$caneditfield\t\tAdd edit fields\n\t * \t\t@param\tstring\t\t$cssclass\t\t\tCSS name to use on img for photo\n\t * \t\t@param\tstring\t\t$imagesize\t\t 'mini', 'small' or '' (original)\n\t * @param int $addlinktofullsize Add link to fullsize image\n\t * @param int $cache 1=Accept to use image in cache\n\t * \t \t@return string \t\t\t\t\t\tHTML code to output photo\n\t */\n\tstatic function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0)\n\t{\n\t\tglobal $conf,$langs;", "\t\t$entity = (! empty($object->entity) ? $object->entity : $conf->entity);\n\t\t$id = (! empty($object->id) ? $object->id : $object->rowid);", "\t\t$ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';\n\t\tif ($modulepart=='societe')\n\t\t{\n\t\t\t$dir=$conf->societe->multidir_output[$entity];\n\t\t\tif (! empty($object->logo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');\n\t\t\t\telse $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;\n\t\t\t\t$originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;\n\t\t\t}\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse if ($modulepart=='contact')\n\t\t{\n\t\t\t$dir=$conf->societe->multidir_output[$entity].'/contact';\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;\n\t\t\t\t$originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;\n\t\t\t}\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse if ($modulepart=='userphoto')\n\t\t{\n\t\t\t$dir=$conf->user->dir_output;\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;\n\t\t\t\t$originalfile=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;\n\t\t\t}\n\t\t\tif (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.\".jpg\";\t// For backward compatibility\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse if ($modulepart=='memberphoto')\n\t\t{\n\t\t\t$dir=$conf->adherent->dir_output;\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;\n\t\t\t\t$originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;\n\t\t\t}\n\t\t\tif (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.\".jpg\";\t// For backward compatibility\n\t\t\t$email=$object->email;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Generic case to show photos\n\t\t\t$dir=$conf->$modulepart->dir_output;\n\t\t\tif (! empty($object->photo))\n\t\t\t{\n\t\t\t\tif ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');\n\t\t\t\telse if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');\n\t\t\t\telse $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;\n\t\t\t\t$originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;\n\t\t\t}\n\t\t\tif (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.\".jpg\";\t// For backward compatibility\n\t\t\t$email=$object->email;\n\t\t}", "\t\tif ($dir)\n\t\t{\n\t\t\tif ($file && file_exists($dir.\"/\".$file))\n\t\t\t{\n\t\t\t\tif ($addlinktofullsize)\n\t\t\t\t{\n\t\t\t\t\t$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);\n\t\t\t\t\tif ($urladvanced) $ret.='<a href=\"'.$urladvanced.'\">';\n\t\t\t\t\telse $ret.='<a href=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'\">';\n\t\t\t\t}\n\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"Photo\" id=\"photologo'.(preg_replace('/[^a-z]/i','_',$file)).'\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'\">';\n\t\t\t\tif ($addlinktofullsize) $ret.='</a>';\n\t\t\t}\n\t\t\telse if ($altfile && file_exists($dir.\"/\".$altfile))\n\t\t\t{\n\t\t\t\tif ($addlinktofullsize)\n\t\t\t\t{\n\t\t\t\t\t$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);\n\t\t\t\t\tif ($urladvanced) $ret.='<a href=\"'.$urladvanced.'\">';\n\t\t\t\t\telse $ret.='<a href=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'\">';\n\t\t\t\t}\n\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"Photo alt\" id=\"photologo'.(preg_replace('/[^a-z]/i','_',$file)).'\" class=\"'.$cssclass.'\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'\">';\n\t\t\t\tif ($addlinktofullsize) $ret.='</a>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$nophoto='/public/theme/common/nophoto.png';\n\t\t\t\tif (in_array($modulepart,array('userphoto','contact')))\t// For module that are \"physical\" users\n\t\t\t\t{\n\t\t\t\t\t$nophoto='/public/theme/common/user_anonymous.png';\n\t\t\t\t\tif ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';\n\t\t\t\t\tif ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';\n\t\t\t\t}", "\t\t\t\tif (! empty($conf->gravatar->enabled) && $email)\n\t\t\t\t{\n\t\t\t\t\t/**\n\t\t\t\t\t * @see https://gravatar.com/site/implement/images/php/\n\t\t\t\t\t */\n\t\t\t\t\tglobal $dolibarr_main_url_root;\n\t\t\t\t\t$ret.='<!-- Put link to gravatar -->';\n\t\t\t\t\t//$defaultimg=urlencode(dol_buildpath($nophoto,3));\n\t\t\t\t\t$defaultimg='mm';\n\t\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"Gravatar avatar\" title=\"'.$email.' Gravatar avatar\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'\">';\t// gravatar need md5 hash\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$ret.='<img class=\"photo'.$modulepart.($cssclass?' '.$cssclass:'').'\" alt=\"No photo\" '.($width?' width=\"'.$width.'\"':'').($height?' height=\"'.$height.'\"':'').' src=\"'.DOL_URL_ROOT.$nophoto.'\">';\n\t\t\t\t}\n\t\t\t}", "\t\t\tif ($caneditfield)\n\t\t\t{\n\t\t\t\tif ($object->photo) $ret.=\"<br>\\n\";\n\t\t\t\t$ret.='<table class=\"nobordernopadding centpercent\">';\n\t\t\t\tif ($object->photo) $ret.='<tr><td><input type=\"checkbox\" class=\"flat photodelete\" name=\"deletephoto\" id=\"photodelete\"> '.$langs->trans(\"Delete\").'<br><br></td></tr>';\n\t\t\t\t$ret.='<tr><td class=\"tdoverflow\"><input type=\"file\" class=\"flat maxwidth200onsmartphone\" name=\"photo\" id=\"photoinput\"></td></tr>';\n\t\t\t\t$ret.='</table>';\n\t\t\t}", "\t\t}\n\t\telse dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);", "\t\treturn $ret;\n\t}", "\t/**\n\t *\tReturn select list of groups\n\t *\n\t * @param\tstring\t$selected Id group preselected\n\t * @param string\t$htmlname Field name in form\n\t * @param int\t\t$show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue\n\t * @param string\t$exclude Array list of groups id to exclude\n\t * \t@param\tint\t\t$disabled\t\tIf select list must be disabled\n\t * @param string\t$include Array list of groups id to include\n\t * \t@param\tint\t\t$enableonly\t\tArray list of groups id to be enabled. All other must be disabled\n\t * \t@param\tstring\t$force_entity\t'0' or Ids of environment to force\n\t * @return\tstring\n\t * @see select_dolusers\n\t */\n\tfunction select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0')\n\t{\n\t\tglobal $conf,$user,$langs;", "\t\t// Permettre l'exclusion de groupes\n\t\tif (is_array($exclude))\t$excludeGroups = implode(\"','\",$exclude);\n\t\t// Permettre l'inclusion de groupes\n\t\tif (is_array($include))\t$includeGroups = implode(\"','\",$include);", "\t\t$out='';", "\t\t// On recherche les groupes\n\t\t$sql = \"SELECT ug.rowid, ug.nom as name\";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \", e.label\";\n\t\t}\n\t\t$sql.= \" FROM \".MAIN_DB_PREFIX.\"usergroup as ug \";\n\t\tif (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)\n\t\t{\n\t\t\t$sql.= \" LEFT JOIN \".MAIN_DB_PREFIX.\"entity as e ON e.rowid=ug.entity\";\n\t\t\tif ($force_entity) $sql.= \" WHERE ug.entity IN (0,\".$force_entity.\")\";\n\t\t\telse $sql.= \" WHERE ug.entity IS NOT NULL\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$sql.= \" WHERE ug.entity IN (0,\".$conf->entity.\")\";\n\t\t}\n\t\tif (is_array($exclude) && $excludeGroups) $sql.= \" AND ug.rowid NOT IN ('\".$excludeGroups.\"')\";\n\t\tif (is_array($include) && $includeGroups) $sql.= \" AND ug.rowid IN ('\".$includeGroups.\"')\";\n\t\t$sql.= \" ORDER BY ug.nom ASC\";", "\t\tdol_syslog(get_class($this).\"::select_dolgroups\", LOG_DEBUG);\n\t\t$resql=$this->db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t// Enhance with select2\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';\n\t\t \t$out .= ajax_combobox($htmlname);", "\t\t\t$out.= '<select class=\"flat minwidth200\" id=\"'.$htmlname.'\" name=\"'.$htmlname.'\"'.($disabled?' disabled':'').'>';", "\t\t\t$num = $this->db->num_rows($resql);\n\t\t\t$i = 0;\n\t\t\tif ($num)\n\t\t\t{\n\t\t\t\tif ($show_empty) $out.= '<option value=\"-1\"'.($selected==-1?' selected':'').'>&nbsp;</option>'.\"\\n\";", "\t\t\t\twhile ($i < $num)\n\t\t\t\t{\n\t\t\t\t\t$obj = $this->db->fetch_object($resql);\n\t\t\t\t\t$disableline=0;\n\t\t\t\t\tif (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;", "\t\t\t\t\t$out.= '<option value=\"'.$obj->rowid.'\"';\n\t\t\t\t\tif ($disableline) $out.= ' disabled';\n\t\t\t\t\tif ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= ' selected';\n\t\t\t\t\t}\n\t\t\t\t\t$out.= '>';", "\t\t\t\t\t$out.= $obj->name;\n\t\t\t\t\tif (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\t$out.= \" (\".$obj->label.\")\";\n\t\t\t\t\t}", "\t\t\t\t\t$out.= '</option>';\n\t\t\t\t\t$i++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif ($show_empty) $out.= '<option value=\"-1\"'.($selected==-1?' selected':'').'></option>'.\"\\n\";\n\t\t\t\t$out.= '<option value=\"\" disabled>'.$langs->trans(\"NoUserGroupDefined\").'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($this->db);\n\t\t}", "\t\treturn $out;\n\t}", "\n\t/**\n\t *\tReturn HTML to show the search and clear seach button\n\t *\n\t * @return\tstring\n\t */\n\tfunction showFilterButtons()\n\t{\n\t\tglobal $conf, $langs;", "\t\t$out='<div class=\"nowrap\">';\n\t\t$out.='<input type=\"image\" class=\"liste_titre\" name=\"button_search\" src=\"'.img_picto($langs->trans(\"Search\"),'search.png','','',1).'\" value=\"'.dol_escape_htmltag($langs->trans(\"Search\")).'\" title=\"'.dol_escape_htmltag($langs->trans(\"Search\")).'\">';\n\t\t$out.='<input type=\"image\" class=\"liste_titre\" name=\"button_removefilter\" src=\"'.img_picto($langs->trans(\"Search\"),'searchclear.png','','',1).'\" value=\"'.dol_escape_htmltag($langs->trans(\"RemoveFilter\")).'\" title=\"'.dol_escape_htmltag($langs->trans(\"RemoveFilter\")).'\">';\n\t\t$out.='</div>';", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn HTML to show the search and clear seach button\n\t *\n\t * @param string $cssclass CSS class\n\t * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes\n\t * @return\tstring\n\t */\n\tfunction showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)\n\t{\n\t\tglobal $conf, $langs;", "\t\t$out='';\n\t\tif (! empty($conf->use_javascript_ajax)) $out.='<div class=\"inline-block checkallactions\"><input type=\"checkbox\" id=\"checkallactions\" name=\"checkallactions\" class=\"checkallactions\"></div>';\n\t\t$out.='<script type=\"text/javascript\">\n $(document).ready(function() {\n \t$(\"#checkallactions\").click(function() {\n if($(this).is(\\':checked\\')){\n console.log(\"We check all\");\n \t\t$(\".'.$cssclass.'\").prop(\\'checked\\', true);\n }\n else\n {\n console.log(\"We uncheck all\");\n \t\t$(\".'.$cssclass.'\").prop(\\'checked\\', false);\n }'.\"\\n\";\n\t\tif ($calljsfunction) $out.='if (typeof initCheckForSelect == \\'function\\') { initCheckForSelect(0); } else { console.log(\"No function initCheckForSelect found. Call won\\'t be done.\"); }';\n\t\t$out.=' });\n });\n </script>';", "\t\treturn $out;\n\t}", "\t/**\n\t *\tReturn HTML to show the search and clear seach button\n\t *\n\t * @param\tint \t$addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this\n\t * @param string $cssclass CSS class\n\t * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes\n\t * @return\tstring\n\t */\n\tfunction showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)\n\t{\n\t\t$out.=$this->showFilterButtons();\n\t\tif ($addcheckuncheckall)\n\t\t{\n\t\t\t$out.=$this->showCheckAddButtons($cssclass, $calljsfunction);\n\t\t}\n\t\treturn $out;\n\t}", "\t/**\n\t * Return HTML to show the select categories of expense category\n\t *\n\t * @param\tstring\t$selected preselected category\n\t * @param\tstring\t$htmlname name of HTML select list\n\t * @param\tinteger\t$useempty 1=Add empty line\n\t * @param\tarray\t$excludeid id to exclude\n\t * @param\tstring\t$target htmlname of target select to bind event\n\t * @param\tint\t\t$default_selected default category to select if fk_c_type_fees change = EX_KME\n\t * @param\tarray\t$params param to give\n\t * @return\tstring\n\t */\n\tfunction selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())\n\t{\n\t\tglobal $db, $conf, $langs, $user;", "\t\t$sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';\n\t\t$sql.= ' AND entity IN (0,'.getEntity('').')';\n\t\tif (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';\n\t\t$sql.= ' ORDER BY label';", "\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out = '<select name=\"'.$htmlname.'\" class=\"'.$htmlname.' flat minwidth75imp\">';\n\t\t\tif ($useempty) $out.= '<option value=\"0\">&nbsp;</option>';", "\t\t\twhile ($obj = $db->fetch_object($resql))\n\t\t\t{\n\t\t\t\t$out.= '<option '.($selected == $obj->rowid ? 'selected=\"selected\"' : '').' value=\"'.$obj->rowid.'\">'.$langs->trans($obj->label).'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t\tif (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);", "\t\t\tif (!empty($target))\n\t\t\t{\n\t\t\t\t$sql = \"SELECT c.id FROM \".MAIN_DB_PREFIX.\"c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1\";\n\t\t\t\t$resql = $db->query($sql);\n\t\t\t\tif ($resql)\n\t\t\t\t{\n\t\t\t\t\tif ($db->num_rows($resql) > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t$obj = $db->fetch_object($resql);\n\t\t\t\t\t\t$out.= '<script type=\"text/javascript\">\n\t\t\t\t\t\t\t$(function() {\n\t\t\t\t\t\t\t\t$(\"select[name='.$target.']\").on(\"change\", function() {\n\t\t\t\t\t\t\t\t\tvar current_val = $(this).val();\n\t\t\t\t\t\t\t\t\tif (current_val == '.$obj->id.') {';\n\t\t\t\t\t\tif (!empty($default_selected) || !empty($selected)) $out.= '$(\"select[name='.$htmlname.']\").val(\"'.($default_selected > 0 ? $default_selected : $selected).'\");';", "\t\t\t\t\t\t$out.= '\n\t\t\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").change();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});", "\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").change(function() {", "\t\t\t\t\t\t\t\t\tif ($(\"select[name='.$target.']\").val() == '.$obj->id.') {\n\t\t\t\t\t\t\t\t\t\t// get price of kilometer to fill the unit price\n\t\t\t\t\t\t\t\t\t\tvar data = '.json_encode($params).';\n\t\t\t\t\t\t\t\t\t\tdata.fk_c_exp_tax_cat = $(this).val();", "\t\t\t\t\t\t\t\t\t\t$.ajax({\n\t\t\t\t\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\t\t\t\t\tdataType: \"json\",\n\t\t\t\t\t\t\t\t\t\t\tdata: data,\n\t\t\t\t\t\t\t\t\t\t\turl: \"'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php').'\",\n\t\t\t\t\t\t\t\t\t\t}).done(function( data, textStatus, jqXHR ) {\n\t\t\t\t\t\t\t\t\t\t\tconsole.log(data);\n\t\t\t\t\t\t\t\t\t\t\tif (typeof data.up != \"undefined\") {\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"input[name=value_unit]\").val(data.up);\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").attr(\"title\", data.title);\n\t\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"input[name=value_unit]\").val(\"\");\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"select[name='.$htmlname.']\").attr(\"title\", \"\");\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t</script>';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Return HTML to show the select ranges of expense range\n\t *\n\t * @param\tstring\t$selected preselected category\n\t * @param\tstring\t$htmlname name of HTML select list\n\t * @param\tinteger\t$useempty 1=Add empty line\n\t * @return\tstring\n\t */\n\tfunction selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)\n\t{\n\t\tglobal $db,$conf,$langs;", "\t\t$sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';\n\t\t$sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';", "\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out = '<select name=\"'.$htmlname.'\" class=\"'.$htmlname.' flat minwidth75imp\">';\n\t\t\tif ($useempty) $out.= '<option value=\"0\"></option>';", "\t\t\twhile ($obj = $db->fetch_object($resql))\n\t\t\t{\n\t\t\t\t$out.= '<option '.($selected == $obj->rowid ? 'selected=\"selected\"' : '').' value=\"'.$obj->rowid.'\">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}", "\t\treturn $out;\n\t}", "\t/**\n\t * Return HTML to show a select of expense\n\t *\n\t * @param\tstring\t$selected preselected category\n\t * @param\tstring\t$htmlname name of HTML select list\n\t * @param\tinteger\t$useempty 1=Add empty choice\n\t * @param\tinteger\t$allchoice 1=Add all choice\n\t * @param\tinteger\t$useid 0=use 'code' as key, 1=use 'id' as key\n\t * @return\tstring\n\t */\n\tfunction selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)\n\t{\n\t\tglobal $db,$langs;", "\t\t$sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';\n\t\t$sql.= ' WHERE active = 1';", "\t\t$resql = $db->query($sql);\n\t\tif ($resql)\n\t\t{\n\t\t\t$out = '<select name=\"'.$htmlname.'\" class=\"'.$htmlname.' flat minwidth75imp\">';\n\t\t\tif ($useempty) $out.= '<option value=\"0\"></option>';\n\t\t\tif ($allchoice) $out.= '<option value=\"-1\">'.$langs->trans('AllExpenseReport').'</option>';", "\t\t\t$field = 'code';\n\t\t\tif ($useid) $field = 'id';", "\t\t\twhile ($obj = $db->fetch_object($resql))\n\t\t\t{\n\t\t\t\t$key = $langs->trans($obj->code);\n\t\t\t\t$out.= '<option '.($selected == $obj->{$field} ? 'selected=\"selected\"' : '').' value=\"'.$obj->{$field}.'\">'.($key != $obj->code ? $key : $obj->label).'</option>';\n\t\t\t}\n\t\t\t$out.= '</select>';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdol_print_error($db);\n\t\t}", "\t\treturn $out;\n\t}", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>\n * Copyright (C) 2003 Xavier Dutoit <doli@sydesy.com>\n * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>\n * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>\n * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>\n * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>\n * Copyright (C) 2011-2014 Philippe Grand <philippe.grand@atoo-net.com>\n * Copyright (C) 2008 Matteli\n * Copyright (C) 2011-2016 Juanjo Menent <jmenent@2byte.es>\n * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>\n * Copyright (C) 2014-2015 Marcos GarcΓ­a <marcosgdf@gmail.com>\n * Copyright (C) 2015 RaphaΓ«l Doursenaud <rdoursenaud@gpcsolutions.fr>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n *\t\\file htdocs/main.inc.php\n *\t\\ingroup\tcore\n *\t\\brief File that defines environment for Dolibarr GUI pages only (file not required by scripts)\n */", "//@ini_set('memory_limit', '128M');\t// This may be useless if memory is hard limited by your PHP", "// For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.\n$micro_start_time=0;\nif (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))\n{\n\tlist($usec, $sec) = explode(\" \", microtime());\n\t$micro_start_time=((float) $usec + (float) $sec);\n\t// Add Xdebug code coverage\n\t//define('XDEBUGCOVERAGE',1);\n\tif (defined('XDEBUGCOVERAGE')) {\n\t\txdebug_start_code_coverage();\n\t}\n}", "// Removed magic_quotes\nif (function_exists('get_magic_quotes_gpc'))\t// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5\n{\n\tif (get_magic_quotes_gpc())\n\t{\n\t\t// Forcing parameter setting magic_quotes_gpc and cleaning parameters\n\t\t// (Otherwise he would have for each position, condition\n\t\t// Reading stripslashes variable according to state get_magic_quotes_gpc).\n\t\t// Off mode recommended (just do $db->escape for insert / update).\n\t\tfunction stripslashes_deep($value)\n\t\t{\n\t\t\treturn (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));\n\t\t}\n\t\t$_GET = array_map('stripslashes_deep', $_GET);\n\t\t$_POST = array_map('stripslashes_deep', $_POST);\n\t\t$_FILES = array_map('stripslashes_deep', $_FILES);\n\t\t//$_COOKIE = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql\n\t\t@set_magic_quotes_runtime(0);\n\t}\n}", "/**\n * Security: SQL Injection and XSS Injection (scripts) protection (Filters on GET, POST, PHP_SELF).\n *\n * @param\t\tstring\t\t$val\t\tValue", " * @param\t\tstring\t\t$type\t\t1=GET, 0=POST, 2=PHP_SELF", " * @return\t\tint\t\t\t\t\t\t>0 if there is an injection, 0 if none\n */\nfunction test_sql_and_script_inject($val, $type)\n{\n\t$inj = 0;\n\t// For SQL Injection (only GET are used to be included into bad escaped SQL requests)", "\tif ($type == 1)\n\t{\n\t\t$inj += preg_match('/updatexml\\(/i',\t $val);", "\t\t$inj += preg_match('/delete\\s+from/i',\t $val);\n\t\t$inj += preg_match('/create\\s+table/i',\t $val);\n\t\t$inj += preg_match('/insert\\s+into/i', \t $val);\n\t\t$inj += preg_match('/select\\s+from/i', \t $val);\n\t\t$inj += preg_match('/into\\s+(outfile|dumpfile)/i', $val);", "\t}\n\tif ($type != 2)\t// Not common, we can check on POST\n\t{", "\t\t$inj += preg_match('/update.+set.+=/i', $val);\n\t\t$inj += preg_match('/union.+select/i', \t $val);\n\t\t$inj += preg_match('/(\\.\\.%2f)+/i',\t\t $val);\n\t}\n\t// For XSS Injection done by adding javascript with script\n\t// This is all cases a browser consider text is javascript:\n\t// When it found '<script', 'javascript:', '<style', 'onload\\s=' on body tag, '=\"&' on a tag size with old browsers\n\t// All examples on page: http://ha.ckers.org/xss.html#XSScalc\n\t// More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\n\t$inj += preg_match('/<script/i', $val);\n\t$inj += preg_match('/<iframe/i', $val);\n\t$inj += preg_match('/<audio/i', $val);\n\t$inj += preg_match('/Set\\.constructor/i', $val);\t// ECMA script 6\n\tif (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);\n\t$inj += preg_match('/base[\\s]+href/si', $val);\n\t$inj += preg_match('/<.*onmouse/si', $val); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>\n\t$inj += preg_match('/onerror\\s*=/i', $val); // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>\n\t$inj += preg_match('/onfocus\\s*=/i', $val); // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>\n\t$inj += preg_match('/onload\\s*=/i', $val); // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>\n\t$inj += preg_match('/onloadstart\\s*=/i', $val); // onload can be set on audio tag <audio onloadstart=alert(1)>\n\t$inj += preg_match('/onclick\\s*=/i', $val); // onclick can be set on img text html tag like <img onclick = alert(1)>\n\t$inj += preg_match('/onscroll\\s*=/i', $val); // onscroll can be on textarea\n\t//$inj += preg_match('/on[A-Z][a-z]+\\*=/', $val); // To lock event handlers onAbort(), ...\n\t$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);\t\t// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'\n\t//if ($type == 1)\n\t//{\n\t\t$inj += preg_match('/javascript:/i', $val);\n\t\t$inj += preg_match('/vbscript:/i', $val);\n\t//}\n\t// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)\n\tif ($type == 1) $inj += preg_match('/\"/i', $val);\t\t// We refused \" in GET parameters value\n\tif ($type == 2) $inj += preg_match('/[;\"]/', $val);\t\t// PHP_SELF is a file system path. It can contains spaces.\n\treturn $inj;\n}", "/**\n * Return true if security check on parameters are OK, false otherwise.\n *\n * @param\t\tstring\t\t\t$var\t\tVariable name\n * @param\t\tstring\t\t\t$type\t\t1=GET, 0=POST, 2=PHP_SELF\n * @return\t\tboolean|null\t\t\t\ttrue if there is no injection. Stop code if injection found.\n */\nfunction analyseVarsForSqlAndScriptsInjection(&$var, $type)\n{\n\tif (is_array($var))\n\t{\n\t\tforeach ($var as $key => $value)\t// Warning, $key may also be used for attacks\n\t\t{\n\t\t\tif (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))\n\t\t\t{\n\t\t\t\t//$var[$key] = $value;\t// This is useless\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER[\"REQUEST_URI\"]).')';\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn (test_sql_and_script_inject($var, $type) <= 0);\n\t}\n}", "\n// Check consistency of NOREQUIREXXX DEFINES\nif ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU'))\n{\n\tprint 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';\n\texit;\n}", "// Sanity check on URL\nif (! empty($_SERVER[\"PHP_SELF\"]))\n{\n\t$morevaltochecklikepost=array($_SERVER[\"PHP_SELF\"]);\n\tanalyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);\n}\n// Sanity check on GET parameters\nif (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER[\"QUERY_STRING\"]))\n{\n\t$morevaltochecklikeget=array($_SERVER[\"QUERY_STRING\"]);\n\tanalyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);\n}\n// Sanity check on POST\nif (! defined('NOSCANPOSTFORINJECTION'))\n{\n\tanalyseVarsForSqlAndScriptsInjection($_POST,0);\n}", "// This is to make Dolibarr working with Plesk\nif (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')\n{\n\tset_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');\n}", "// Include the conf.php and functions.lib.php\nrequire_once 'filefunc.inc.php';", "// If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.\n// This is used for example by form of boxes to save personalization of some options.\n// DOL_AUTOSET_COOKIE=cookiename:val1,val2 and cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))\nif (! empty($_POST[\"DOL_AUTOSET_COOKIE\"]))\n{\n\t$tmpautoset=explode(':',$_POST[\"DOL_AUTOSET_COOKIE\"],2);\n\t$tmplist=explode(',',$tmpautoset[1]);\n\t$cookiearrayvalue=array();\n\tforeach ($tmplist as $tmpkey)\n\t{\n\t\t$postkey=$tmpautoset[0].'_'.$tmpkey;\n\t\t//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);\n\t\tif (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];\n\t}\n\t$cookiename=$tmpautoset[0];\n\t$cookievalue=json_encode($cookiearrayvalue);\n\t//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);\n\tsetcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);\t// keep cookie 1 year and add tag httponly\n\tif (empty($cookievalue)) unset($_COOKIE[$cookiename]);\n}", "\n// Init session. Name of session is specific to Dolibarr instance.\n// Note: the function dol_getprefix may have been redefined to return a different key to manage another area to protect.\n$prefix=dol_getprefix('');", "$sessionname='DOLSESSID_'.$prefix;\n$sessiontimeout='DOLSESSTIMEOUT_'.$prefix;\nif (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);\nsession_name($sessionname);\nsession_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.\n// This create lock, released when session_write_close() or end of page.\n// We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.\nif (! defined('NOSESSION'))\n{\n\tsession_start();\n\tif (ini_get('register_globals')) // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION\n\t{\n\t\tforeach ($_SESSION as $key=>$value)\n\t\t{\n\t\t\tif (isset($GLOBALS[$key])) unset($GLOBALS[$key]);\n\t\t}\n\t}\n}", "// Init the 5 global objects, this include will make the new and set properties for: $conf, $db, $langs, $user, $mysoc\nrequire_once 'master.inc.php';", "// Activate end of page function\nregister_shutdown_function('dol_shutdown');", "// Detection browser\nif (isset($_SERVER[\"HTTP_USER_AGENT\"]))\n{\n\t$tmp=getBrowserInfo($_SERVER[\"HTTP_USER_AGENT\"]);\n\t$conf->browser->name=$tmp['browsername'];\n\t$conf->browser->os=$tmp['browseros'];\n\t$conf->browser->version=$tmp['browserversion'];\n\t$conf->browser->layout=$tmp['layout']; // 'classic', 'phone', 'tablet'\n\t$conf->browser->phone=$tmp['phone'];\t // TODO deprecated, use ->layout\n\t$conf->browser->tablet=$tmp['tablet'];\t // TODO deprecated, use ->layout\n\t//var_dump($conf->browser);", "\tif ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;\n\tif ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;\n}", "// Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)\n// $_SERVER[\"HTTPS\"] is 'on' when link is https, otherwise $_SERVER[\"HTTPS\"] is empty or 'off'\nif (! empty($conf->file->main_force_https) && (empty($_SERVER[\"HTTPS\"]) || $_SERVER[\"HTTPS\"] != 'on'))\n{\n\t$newurl='';\n\tif (is_numeric($conf->file->main_force_https))\n\t{\n\t\tif ($conf->file->main_force_https == '1' && ! empty($_SERVER[\"SCRIPT_URI\"]))\t// If SCRIPT_URI supported by server\n\t\t{\n\t\t\tif (preg_match('/^http:/i',$_SERVER[\"SCRIPT_URI\"]) && ! preg_match('/^https:/i',$_SERVER[\"SCRIPT_URI\"]))\t// If link is http\n\t\t\t{\n\t\t\t\t$newurl=preg_replace('/^http:/i','https:',$_SERVER[\"SCRIPT_URI\"]);\n\t\t\t}\n\t\t}\n\t\telse\t// Check HTTPS environment variable (Apache/mod_ssl only)\n\t\t{\n\t\t\t$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER[\"REQUEST_URI\"];\n\t\t}\n\t}\n\telse\n\t{\n\t\t// Check HTTPS environment variable (Apache/mod_ssl only)\n\t\t$newurl=$conf->file->main_force_https.$_SERVER[\"REQUEST_URI\"];\n\t}\n\t// Start redirect\n\tif ($newurl)\n\t{\n\t\tdol_syslog(\"main.inc: dolibarr_main_force_https is on, we make a redirect to \".$newurl);\n\t\theader(\"Location: \".$newurl);\n\t\texit;\n\t}\n\telse\n\t{\n\t\tdol_syslog(\"main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done\", LOG_WARNING);\n\t}\n}", "\n// Loading of additional presentation includes\nif (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';\t // Need 660ko memory (800ko in 2.2)\nif (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';\t// Need 22ko memory", "// If install or upgrade process not done or not completely finished, we call the install page.\nif (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))\n{\n\tdol_syslog(\"main.inc: A previous install or upgrade was not complete. Redirect to install page.\", LOG_WARNING);\n\theader(\"Location: \".DOL_URL_ROOT.\"/install/index.php\");\n\texit;\n}\n// If an upgrade process is required, we call the install page.\nif ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))\n|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))\n{\n\t$versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;\n\trequire_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';\n\t$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);\n\t$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);\n\t$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);\n\tif ($rescomp > 0) // Programs have a version higher than database. We did not add \"&& $rescomp < 3\" because we want upgrade process for build upgrades\n\t{\n\t\tdol_syslog(\"main.inc: database version \".$versiontocompare.\" is lower than programs version \".DOL_VERSION.\". Redirect to install page.\", LOG_WARNING);\n\t\theader(\"Location: \".DOL_URL_ROOT.\"/install/index.php\");\n\t\texit;\n\t}\n}", "// Creation of a token against CSRF vulnerabilities\nif (! defined('NOTOKENRENEWAL'))\n{\n\t// roulement des jetons car cree a chaque appel\n\tif (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];", "\t// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']\n\t$token = dol_hash(uniqid(mt_rand(),TRUE)); // Generates a hash of a random number\n\t$_SESSION['newtoken'] = $token;\n}\nif ((! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))\n\t|| defined('CSRFCHECK_WITH_TOKEN'))\t// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set\n{\n\tif ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET\n\t{\n\t\tprint \"Access refused by CSRF protection in main.inc.php. Token not provided.\\n\";\n\t\tprint \"If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \\$dolibarr_nocsrfcheck=1 into your conf.php file).\\n\";\n\t\tdie;\n\t}\n\tif ($_SERVER['REQUEST_METHOD'] === 'POST') // This test must be after loading $_SESSION['token'].\n\t{\n\t\tif (GETPOST('token', 'alpha') != $_SESSION['token'])\n\t\t{\n\t\t\tdol_syslog(\"Invalid token in \".$_SERVER['HTTP_REFERER'].\", action=\".GETPOST('action','aZ09').\", _POST['token']=\".GETPOST('token','alpha').\", _SESSION['token']=\".$_SESSION['token'], LOG_WARNING);\n\t\t\t//print 'Unset POST by CSRF protection in main.inc.php.';\t// Do not output anything because this create problems when using the BACK button on browsers.\n\t\t\tunset($_POST);\n\t\t}\n\t}\n}", "// Disable modules (this must be after session_start and after conf has been loaded)\nif (GETPOST('disablemodules','alpha')) $_SESSION[\"disablemodules\"]=GETPOST('disablemodules','alpha');\nif (! empty($_SESSION[\"disablemodules\"]))\n{\n\t$disabled_modules=explode(',',$_SESSION[\"disablemodules\"]);\n\tforeach($disabled_modules as $module)\n\t{\n\t\tif ($module)\n\t\t{\n\t\t\tif (empty($conf->$module)) $conf->$module=new stdClass();\n\t\t\t$conf->$module->enabled=false;\n\t\t\tif ($module == 'fournisseur')\t\t// Special case\n\t\t\t{\n\t\t\t\t$conf->supplier_order->enabled=0;\n\t\t\t\t$conf->supplier_invoice->enabled=0;\n\t\t\t}\n\t\t}\n\t}\n}", "/*\n * Phase authentication / login\n */\n$login='';\nif (! defined('NOLOGIN'))\n{\n\t// $authmode lists the different means of identification to be tested in order of preference.\n\t// Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'", "\tif (defined('MAIN_AUTHENTICATION_MODE'))\n\t{\n\t\t$dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');\n\t}\n\telse\n\t{\n\t\t// Authentication mode\n\t\tif (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';\n\t\t// Authentication mode: forceuser\n\t\tif ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';\n\t}\n\t// Set authmode\n\t$authmode=explode(',',$dolibarr_main_authentication);", "\t// No authentication mode\n\tif (! count($authmode))\n\t{\n\t\t$langs->load('main');\n\t\tdol_print_error('',$langs->trans(\"ErrorConfigParameterNotDefined\",'dolibarr_main_authentication'));\n\t\texit;\n\t}", "\t// If login request was already post, we retrieve login from the session\n\t// Call module if not realized that his request.\n\t// At the end of this phase, the variable $login is defined.\n\t$resultFetchUser='';\n\t$test=true;\n\tif (! isset($_SESSION[\"dol_login\"]))\n\t{\n\t\t// It is not already authenticated and it requests the login / password\n\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';", "\t\t$dol_dst_observed=GETPOST(\"dst_observed\",'int',3);\n\t\t$dol_dst_first=GETPOST(\"dst_first\",'int',3);\n\t\t$dol_dst_second=GETPOST(\"dst_second\",'int',3);\n\t\t$dol_screenwidth=GETPOST(\"screenwidth\",'int',3);\n\t\t$dol_screenheight=GETPOST(\"screenheight\",'int',3);\n\t\t$dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);\n\t\t$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);\n\t\t$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);\n\t\t$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);\n\t\t$dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);\n\t\t//dol_syslog(\"POST key=\".join(array_keys($_POST),',').' value='.join($_POST,','));", "\t\t// If in demo mode, we check we go to home page through the public/demo/index.php page\n\t\tif (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') // We ask index page\n\t\t{\n\t\t\tif (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))\n\t\t\t{\n\t\t\t\tdol_syslog(\"Call index page from another url than demo page (call is done from page \".$_SERVER['HTTP_REFERER'].\")\");\n\t\t\t\t$url='';\n\t\t\t\t$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');\n\t\t\t\t$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');\n\t\t\t\t$url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');\n\t\t\t\t$url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');\n\t\t\t\t$url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');\n\t\t\t\t$url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');\n\t\t\t\theader(\"Location: \".$url);\n\t\t\t\texit;\n\t\t\t}\n\t\t}", "\t\t// Verification security graphic code\n\t\tif (GETPOST(\"username\",\"alpha\",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))\n\t\t{\n\t\t\t$sessionkey = 'dol_antispam_value';\n\t\t\t$ok=(array_key_exists($sessionkey, $_SESSION) === TRUE && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));", "\t\t\t// Check code\n\t\t\tif (! $ok)\n\t\t\t{\n\t\t\t\tdol_syslog('Bad value for code, connexion refused');\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorBadValueForCode\");\n\t\t\t\t$test=false;", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST(\"username\",\"alpha\",2);\n\t\t\t\t// Call of triggers\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t\t\t$interface=new Interfaces($db);\n\t\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);\n\t\t\t\tif ($result < 0) {\n\t\t\t\t\t$error++;\n\t\t\t\t}\n\t\t\t\t// End Call of triggers", "\t\t\t\t// Hooks on failed login\n\t\t\t\t$action='';\n\t\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\t\tif ($reshook < 0) $error++;", "\t\t\t\t// Note: exit is done later\n\t\t\t}\n\t\t}", "\t\t$usertotest\t\t= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST(\"username\",\"alpha\",2));\n\t\t$passwordtotest\t= GETPOST('password','none',2);\n\t\t$entitytotest\t= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));", "\t\t// Define if we received data to test the login.\n\t\t$goontestloop=false;\n\t\tif (isset($_SERVER[\"REMOTE_USER\"]) && in_array('http',$authmode)) $goontestloop=true;\n\t\tif ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;\n\t\tif (GETPOST(\"username\",\"alpha\",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;", "\t\tif (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.\n\t\t{\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';\n\t\t\t$langs=new Translate(\"\",$conf);\n\t\t\t$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));\n\t\t\tif (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');\n\t\t\t$langs->setDefaultLang($langcode);\n\t\t}", "\t\t// Validation of login/pass/entity\n\t\t// If ok, the variable login will be returned\n\t\t// If error, we will put error message in session under the name dol_loginmesg\n\t\tif ($test && $goontestloop)\n\t\t{\n\t\t\t$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);\n\t\t\tif ($login)\n\t\t\t{\n\t\t\t\t$dol_authmode=$conf->authmode;\t// This properties is defined only when logged, to say what mode was successfully used\n\t\t\t\t$dol_tz=$_POST[\"tz\"];\n\t\t\t\t$dol_tz_string=$_POST[\"tz_string\"];\n\t\t\t\t$dol_tz_string=preg_replace('/\\s*\\(.+\\)$/','',$dol_tz_string);\n\t\t\t\t$dol_tz_string=preg_replace('/,/','/',$dol_tz_string);\n\t\t\t\t$dol_tz_string=preg_replace('/\\s/','_',$dol_tz_string);\n\t\t\t\t$dol_dst=0;\n\t\t\t\tif (isset($_POST[\"dst_first\"]) && isset($_POST[\"dst_second\"]))\n\t\t\t\t{\n\t\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';\n\t\t\t\t\t$datenow=dol_now();\n\t\t\t\t\t$datefirst=dol_stringtotime($_POST[\"dst_first\"]);\n\t\t\t\t\t$datesecond=dol_stringtotime($_POST[\"dst_second\"]);\n\t\t\t\t\tif ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;\n\t\t\t\t}\n\t\t\t\t//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;\n\t\t\t}", "\t\t\tif (! $login)\n\t\t\t{\n\t\t\t\tdol_syslog('Bad password, connexion refused',LOG_DEBUG);\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t// Bad password. No authmode has found a good password.\n\t\t\t\t// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions\n\t\t\t\tif (empty($_SESSION[\"dol_loginmesg\"])) $_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorBadLoginPassword\");", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg=$langs->trans(\"ErrorBadLoginPassword\").' - login='.GETPOST(\"username\",\"alpha\",2);\n\t\t\t\t// Call of triggers\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';\n\t\t\t\t$interface=new Interfaces($db);\n\t\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST(\"username\",\"alpha\",2));\n\t\t\t\tif ($result < 0) {\n\t\t\t\t\t$error++;\n\t\t\t\t}\n\t\t\t\t// End Call of triggers", "\t\t\t\t// Hooks on failed login\n\t\t\t\t$action='';\n\t\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\t\tif ($reshook < 0) $error++;", "\t\t\t\t// Note: exit is done in next chapter\n\t\t\t}\n\t\t}", "\t\t// End test login / passwords\n\t\tif (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))\t// With LDAP we refused empty password because some LDAP are \"opened\" for anonymous access so connexion is a success.\n\t\t{\n\t\t\t// No data to test login, so we show the login page\n\t\t\tdol_syslog(\"--- Access to \".$_SERVER[\"PHP_SELF\"].\" showing the login form and exit\");\n\t\t\tif (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';\n\t\t\telse dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));\n\t\t\texit;\n\t\t}", "\t\t$resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));\n\t\tif ($resultFetchUser <= 0)\n\t\t{\n\t\t\tdol_syslog('User not found, connexion refused');\n\t\t\tsession_destroy();\n\t\t\tsession_name($sessionname);\n\t\t\tsession_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie\n\t\t\tsession_start(); // Fixing the bug of register_globals here is useless since session is empty", "\t\t\tif ($resultFetchUser == 0)\n\t\t\t{\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorCantLoadUserFromDolibarrDatabase\",$login);", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;\n\t\t\t}\n\t\t\tif ($resultFetchUser < 0)\n\t\t\t{\n\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$user->error;", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg=$user->error;\n\t\t\t}", "\t\t\t// Call triggers\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t\t$interface=new Interfaces($db);\n\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);\n\t\t\tif ($result < 0) {\n\t\t\t\t$error++;\n\t\t\t}\n\t\t\t// End call triggers", "\t\t\t// Hooks on failed login\n\t\t\t$action='';\n\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\tif ($reshook < 0) $error++;", "\t\t\t$paramsurl=array();\n\t\t\tif (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');\n\t\t\tif (GETPOST('nojs','int')) $paramsurl[]='nojs='.GETPOST('nojs','int');\n\t\t\tif (GETPOST('lang','aZ09')) $paramsurl[]='lang='.GETPOST('lang','aZ09');\n\t\t\theader('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));\n\t\t\texit;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// We are already into an authenticated session\n\t\t$login=$_SESSION[\"dol_login\"];\n\t\t$entity=$_SESSION[\"dol_entity\"];\n\t\tdol_syslog(\"- This is an already logged session. _SESSION['dol_login']=\".$login.\" _SESSION['dol_entity']=\".$entity, LOG_DEBUG);", "\t\t$resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));\n\t\tif ($resultFetchUser <= 0)\n\t\t{\n\t\t\t// Account has been removed after login\n\t\t\tdol_syslog(\"Can't load user even if session logged. _SESSION['dol_login']=\".$login, LOG_WARNING);\n\t\t\tsession_destroy();\n\t\t\tsession_name($sessionname);\n\t\t\tsession_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie\n\t\t\tsession_start(); // Fixing the bug of register_globals here is useless since session is empty", "\t\t\tif ($resultFetchUser == 0)\n\t\t\t{\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorCantLoadUserFromDolibarrDatabase\",$login);", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;\n\t\t\t}\n\t\t\tif ($resultFetchUser < 0)\n\t\t\t{\n\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$user->error;", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg=$user->error;\n\t\t\t}", "\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t// Call triggers\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t\t$interface=new Interfaces($db);\n\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);\n\t\t\tif ($result < 0) {\n\t\t\t\t$error++;\n\t\t\t}\n\t\t\t// End call triggers", "\t\t\t// Hooks on failed login\n\t\t\t$action='';\n\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\tif ($reshook < 0) $error++;", "\t\t\t$paramsurl=array();\n\t\t\tif (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');\n\t\t\tif (GETPOST('nojs','int')) $paramsurl[]='nojs='.GETPOST('nojs','int');\n\t\t\tif (GETPOST('lang','aZ09')) $paramsurl[]='lang='.GETPOST('lang','aZ09');\n\t\t\theader('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));\n\t\t\texit;\n\t\t}\n\t\telse\n\t\t{\n\t\t // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context\n\t\t $hookmanager->initHooks(array('main'));", "\t\t // Code for search criteria persistence.\n\t\t if (! empty($_GET['save_lastsearch_values'])) // Keep $_GET here\n\t\t {\n\t\t\t $relativepathstring = preg_replace('/\\?.*$/','',$_SERVER[\"HTTP_REFERER\"]);\n\t\t\t $relativepathstring = preg_replace('/^https?:\\/\\/[^\\/]*/','',$relativepathstring); // Get full path except host server\n\t\t\t // Clean $relativepathstring\n \t\t\t if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);\n\t\t\t $relativepathstring = preg_replace('/^\\//', '', $relativepathstring);\n\t\t\t $relativepathstring = preg_replace('/^custom\\//', '', $relativepathstring);\n\t\t\t //var_dump($relativepathstring);", "\t\t\t // We click on a link that leave a page we have to save search criteria. We save them from tmp to no tmp\n\t\t\t if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))\n\t\t\t {\n\t\t\t\t $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];\n\t\t\t\t unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);\n\t\t\t }\n\t\t }", "\t\t $action = '';\n\t\t $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);\n\t\t if ($reshook < 0) {\n\t\t\t setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');\n\t\t }\n\t\t}\n\t}", "\t// Is it a new session that has started ?\n\t// If we are here, this means authentication was successfull.\n\tif (! isset($_SESSION[\"dol_login\"]))\n\t{\n\t\t// New session for this login has started.\n\t\t$error=0;", "\t\t// Store value into session (values always stored)\n\t\t$_SESSION[\"dol_login\"]=$user->login;\n\t\t$_SESSION[\"dol_authmode\"]=isset($dol_authmode)?$dol_authmode:'';\n\t\t$_SESSION[\"dol_tz\"]=isset($dol_tz)?$dol_tz:'';\n\t\t$_SESSION[\"dol_tz_string\"]=isset($dol_tz_string)?$dol_tz_string:'';\n\t\t$_SESSION[\"dol_dst\"]=isset($dol_dst)?$dol_dst:'';\n\t\t$_SESSION[\"dol_dst_observed\"]=isset($dol_dst_observed)?$dol_dst_observed:'';\n\t\t$_SESSION[\"dol_dst_first\"]=isset($dol_dst_first)?$dol_dst_first:'';\n\t\t$_SESSION[\"dol_dst_second\"]=isset($dol_dst_second)?$dol_dst_second:'';\n\t\t$_SESSION[\"dol_screenwidth\"]=isset($dol_screenwidth)?$dol_screenwidth:'';\n\t\t$_SESSION[\"dol_screenheight\"]=isset($dol_screenheight)?$dol_screenheight:'';\n\t\t$_SESSION[\"dol_company\"]=$conf->global->MAIN_INFO_SOCIETE_NOM;\n\t\t$_SESSION[\"dol_entity\"]=$conf->entity;\n\t\t// Store value into session (values stored only if defined)\n\t\tif (! empty($dol_hide_topmenu)) $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;\n\t\tif (! empty($dol_hide_leftmenu)) $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;\n\t\tif (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;\n\t\tif (! empty($dol_no_mouse_hover)) $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;\n\t\tif (! empty($dol_use_jmobile)) $_SESSION['dol_use_jmobile']=$dol_use_jmobile;", "\t\tdol_syslog(\"This is a new started user session. _SESSION['dol_login']=\".$_SESSION[\"dol_login\"].\" Session id=\".session_id());", "\t\t$db->begin();", "\t\t$user->update_last_login_date();", "\t\t$loginfo = 'TZ='.$_SESSION[\"dol_tz\"].';TZString='.$_SESSION[\"dol_tz_string\"].';Screen='.$_SESSION[\"dol_screenwidth\"].'x'.$_SESSION[\"dol_screenheight\"];", "\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t$user->trigger_mesg = $loginfo;\n\t\t// Call triggers\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t$interface=new Interfaces($db);\n\t\t$result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);\n\t\tif ($result < 0) {\n\t\t\t$error++;\n\t\t}\n\t\t// End call triggers", "\t\t// Hooks on successfull login\n\t\t$action='';\n\t\t$hookmanager->initHooks(array('login'));\n\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);\n\t\t$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\tif ($reshook < 0) $error++;", "\t\tif ($error)\n\t\t{\n\t\t\t$db->rollback();\n\t\t\tsession_destroy();\n\t\t\tdol_print_error($db,'Error in some hooks afterLogin (or old trigger USER_LOGIN)');\n\t\t\texit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$db->commit();\n\t\t}", "\t\t// Change landing page if defined.\n\t\t$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);\n\t\tif (! empty($landingpage)) // Example: /index.php\n\t\t{\n\t\t\t$newpath=dol_buildpath($landingpage, 1);\n\t\t\tif ($_SERVER[\"PHP_SELF\"] != $newpath) // not already on landing page (avoid infinite loop)\n\t\t\t{\n\t\t\t\theader('Location: '.$newpath);\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\t}", "\n\t// If user admin, we force the rights-based modules\n\tif ($user->admin)\n\t{\n\t\t$user->rights->user->user->lire=1;\n\t\t$user->rights->user->user->creer=1;\n\t\t$user->rights->user->user->password=1;\n\t\t$user->rights->user->user->supprimer=1;\n\t\t$user->rights->user->self->creer=1;\n\t\t$user->rights->user->self->password=1;\n\t}", "\t/*\n * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)\n */", "\t// Set liste_limit\n\tif (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))\t$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;\t// Can be 0\n\tif (isset($user->conf->PRODUIT_LIMIT_SIZE))\t$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;\t// Can be 0", "\t// Replace conf->css by personalized value if theme not forced\n\tif (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))\n\t{\n\t\t$conf->theme=$user->conf->MAIN_THEME;\n\t\t$conf->css = \"/theme/\".$conf->theme.\"/style.css.php\";\n\t}\n}", "// Case forcing style from url\nif (GETPOST('theme','alpha'))\n{\n\t$conf->theme=GETPOST('theme','alpha',1);\n\t$conf->css = \"/theme/\".$conf->theme.\"/style.css.php\";\n}", "\n// Set javascript option\nif (! GETPOST('nojs','int')) // If javascript was not disabled on URL\n{\n\tif (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))\n\t{\n\t\t$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;\n\t}\n}\nelse $conf->use_javascript_ajax=0;\n// Set MAIN_OPTIMIZEFORTEXTBROWSER\nif (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER)) // If we must enable text browser\n{\n\t$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;\n}\nelseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))\n{\n\t$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;\n}", "// Set terminal output option according to conf->browser.\nif (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu=1;\nif (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu=1;\nif (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1;\nif (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover=1;\nif (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile=1;\nif (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;\nif ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')\n\t|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)\n\t|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)\n)\n{\n\t$conf->dol_optimize_smallscreen=1;\n}\n// If we force to use jmobile, then we reenable javascript\nif (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;\n// Replace themes bugged with jmobile with eldy\nif (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))\n{\n\t$conf->theme='eldy';\n\t$conf->css = \"/theme/\".$conf->theme.\"/style.css.php\";\n}\n//var_dump($conf->browser->phone);", "if (! defined('NOREQUIRETRAN'))\n{\n\tif (! GETPOST('lang','aZ09'))\t// If language was not forced on URL\n\t{\n\t\t// If user has chosen its own language\n\t\tif (! empty($user->conf->MAIN_LANG_DEFAULT))\n\t\t{\n\t\t\t// If different than current language\n\t\t\t//print \">>>\".$langs->getDefaultLang().\"-\".$user->conf->MAIN_LANG_DEFAULT;\n\t\t\tif ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)\n\t\t\t{\n\t\t\t\t$langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);\n\t\t\t}\n\t\t}\n\t}\n}", "if (! defined('NOLOGIN'))\n{\n\t// If the login is not recovered, it is identified with an account that does not exist.\n\t// Hacking attempt?\n\tif (! $user->login) accessforbidden();", "\t// Check if user is active\n\tif ($user->statut < 1)\n\t{\n\t\t// If not active, we refuse the user\n\t\t$langs->load(\"other\");\n\t\tdol_syslog(\"Authentification ko as login is disabled\");\n\t\taccessforbidden($langs->trans(\"ErrorLoginDisabled\"));\n\t\texit;\n\t}", "\t// Load permissions\n\t$user->getrights();\n}", "\ndol_syslog(\"--- Access to \".$_SERVER[\"PHP_SELF\"].' - action='.GETPOST('action','az09').', massaction='.GETPOST('massaction','az09'));\n//Another call for easy debugg\n//dol_syslog(\"Access to \".$_SERVER[\"PHP_SELF\"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));", "// Load main languages files\nif (! defined('NOREQUIRETRAN'))\n{\n\t$langs->load(\"main\");\n\t$langs->load(\"dict\");\n}", "// Define some constants used for style of arrays\n$bc=array(0=>'class=\"impair\"',1=>'class=\"pair\"');\n$bcdd=array(0=>'class=\"drag drop oddeven\"',1=>'class=\"drag drop oddeven\"');\n$bcnd=array(0=>'class=\"nodrag nodrop nohover\"',1=>'class=\"nodrag nodrop nohoverpair\"');\t\t// Used for tr to add new lines\n$bctag=array(0=>'class=\"impair tagtr\"',1=>'class=\"pair tagtr\"');", "// Define messages variables\n$mesg=''; $warning=''; $error=0;\n// deprecated, see setEventMessages() and dol_htmloutput_events()\n$mesgs=array(); $warnings=array(); $errors=array();", "// Constants used to defined number of lines in textarea\nif (empty($conf->browser->firefox))\n{\n\tdefine('ROWS_1',1);\n\tdefine('ROWS_2',2);\n\tdefine('ROWS_3',3);\n\tdefine('ROWS_4',4);\n\tdefine('ROWS_5',5);\n\tdefine('ROWS_6',6);\n\tdefine('ROWS_7',7);\n\tdefine('ROWS_8',8);\n\tdefine('ROWS_9',9);\n}\nelse\n{\n\tdefine('ROWS_1',0);\n\tdefine('ROWS_2',1);\n\tdefine('ROWS_3',2);\n\tdefine('ROWS_4',3);\n\tdefine('ROWS_5',4);\n\tdefine('ROWS_6',5);\n\tdefine('ROWS_7',6);\n\tdefine('ROWS_8',7);\n\tdefine('ROWS_9',8);\n}", "$heightforframes=48;", "// Init menu manager\nif (! defined('NOREQUIREMENU'))\n{\n\tif (empty($user->societe_id)) // If internal user or not defined\n\t{\n\t\t$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);\n\t}\n\telse // If external user\n\t{\n\t\t$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);\n\t}", "\t// Load the menu manager (only if not already done)\n\t$file_menu=$conf->standard_menu;\n\tif (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha'); // example: menu=eldy_menu.php\n\tif (! class_exists('MenuManager'))\n\t{\n\t\t$menufound=0;\n\t\t$dirmenus=array_merge(array(\"/core/menus/\"),(array) $conf->modules_parts['menus']);\n\t\tforeach($dirmenus as $dirmenu)\n\t\t{\n\t\t\t$menufound=dol_include_once($dirmenu.\"standard/\".$file_menu);\n\t\t\tif (class_exists('MenuManager')) break;\n\t\t}\n\t\tif (! class_exists('MenuManager'))\t// If failed to include, we try with standard eldy_menu.php\n\t\t{\n\t\t\tdol_syslog(\"You define a menu manager '\".$file_menu.\"' that can not be loaded.\", LOG_WARNING);\n\t\t\t$file_menu='eldy_menu.php';\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.\"/core/menus/standard/\".$file_menu;\n\t\t}\n\t}\n\t$menumanager = new MenuManager($db, empty($user->societe_id)?0:1);\n\t$menumanager->loadMenu();\n}", "", "// Functions", "if (! function_exists(\"llxHeader\"))\n{\n\t/**\n\t *\tShow HTML header HTML + BODY + Top menu + left menu + DIV\n\t *\n\t * @param \tstring \t$head\t\t\t\tOptionnal head lines\n\t * @param \tstring \t$title\t\t\t\tHTML title\n\t * @param\tstring\t$help_url\t\t\tUrl links to help page\n\t * \t\t \tSyntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage\n\t * \tFor other external page: http://server/url\n\t * @param\tstring\t$target\t\t\t\tTarget to use on links\n\t * @param \tint \t$disablejs\t\t\tMore content into html header\n\t * @param \tint \t$disablehead\t\tMore content into html header\n\t * @param \tarray \t$arrayofjs\t\t\tArray of complementary js files\n\t * @param \tarray \t$arrayofcss\t\t\tArray of complementary css files\n\t * @param\tstring\t$morequerystring\tQuery string to add to the link \"print\" to get same parameters (use only if autodetect fails)\n\t * @param string $morecssonbody More CSS on body tag.\n\t * @param\tstring\t$replacemainareaby\tReplace call to main_area() by a print of this string\n\t * @return\tvoid\n\t */\n\tfunction llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')\n\t{\n\t\tglobal $conf;", "\t\t// html header\n\t\ttop_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);", "\t\tprint '<body id=\"mainbody\"'.($morecssonbody?' class=\"'.$morecssonbody.'\"':'').'>' . \"\\n\";", "\t\t// top menu and left menu area\n\t\tif (empty($conf->dol_hide_topmenu))\n\t\t{\n\t\t\ttop_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);\n\t\t}", "\t\tif (empty($conf->dol_hide_leftmenu))\n\t\t{\n\t\t\tleft_menu('', $help_url, '', '', 1, $title, 1);\n\t\t}", "\t\t// main area\n\t\tif ($replacemainareaby)\n\t\t{\n\t\t\tprint $replacemainareaby;\n\t\t\treturn;\n\t\t}\n\t\tmain_area($title);\n\t}\n}", "\n/**\n * Show HTTP header\n *\n * @param string $contenttype Content type. For example, 'text/html'\n * @param\tint\t\t$forcenocache\tForce disabling of cache for the page\n * @return\tvoid\n */\nfunction top_httphead($contenttype='text/html', $forcenocache=0)\n{\n\tglobal $conf;", "\tif ($contenttype == 'text/html' ) header(\"Content-Type: text/html; charset=\".$conf->file->character_set_client);\n\telse header(\"Content-Type: \".$contenttype);\n\t// Security options\n\theader(\"X-Content-Type-Options: nosniff\"); // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)\n\theader(\"X-Frame-Options: SAMEORIGIN\"); // Frames allowed only if on same domain (stop some XSS attacks)\n\tif (! empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))\n\t{\n\t\t// For example, to restrict script, object, frames or img to some domains\n\t\t// script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; child-src https://youtube.com; img-src: https://static.example.com\n\t\t// For example, to restrict everything to one domain, except object, ...\n\t\t// default-src https://cdn.example.net; object-src 'none'\n\t\theader(\"Content-Security-Policy: \".$conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY);\n\t}\n\tif ($forcenocache)\n\t{\n\t\theader(\"Cache-Control: no-cache, no-store, must-revalidate, max-age=0\");\n\t}\n}", "/**\n * Ouput html header of a page.\n * This code is also duplicated into security2.lib.php::dol_loginfunction\n *\n * @param \tstring \t$head\t\t\t Optionnal head lines\n * @param \tstring \t$title\t\t\t HTML title\n * @param \tint \t$disablejs\t\t Disable js output\n * @param \tint \t$disablehead\t Disable head output\n * @param \tarray \t$arrayofjs\t\t Array of complementary js files\n * @param \tarray \t$arrayofcss\t\t Array of complementary css files\n * @param \tint \t$disablejmobile\t Disable jmobile (No more used)\n * @param int $disablenofollow Disable no follow tag\n * @return\tvoid\n */\nfunction top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)\n{\n\tglobal $user, $conf, $langs, $db;", "\ttop_httphead();", "\tif (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';\t// If not defined, eldy by default", "\tif (! empty($conf->global->MAIN_ACTIVATE_HTML4)) {\n\t\t$doctype = '<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">';\n\t}else {\n\t\t$doctype = '<!doctype html>';\n\t}\n\tprint $doctype.\"\\n\";\n\tif (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang=\"'.substr($langs->defaultlang,0,2).'\" manifest=\"'.DOL_URL_ROOT.'/cache.manifest\">'.\"\\n\";\n\telse print '<html lang=\"'.substr($langs->defaultlang,0,2).'\">'.\"\\n\";\n\t//print '<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\">'.\"\\n\";\n\tif (empty($disablehead))\n\t{\n\t\t$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);", "\t\tprint \"<head>\\n\";\n\t\tif (GETPOST('dol_basehref','alpha')) print '<base href=\"'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'\">'.\"\\n\";\n\t\t// Displays meta\n\t\tprint '<meta name=\"robots\" content=\"noindex'.($disablenofollow?'':',nofollow').'\">'.\"\\n\";\t// Do not index\n\t\tprint '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">'.\"\\n\";\t\t// Scale for mobile device\n\t\tprint '<meta name=\"author\" content=\"Dolibarr Development Team\">'.\"\\n\";\n\t\t// Favicon\n\t\t$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);\n\t\tif (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;\n\t\tif (empty($conf->dol_use_jmobile)) print '<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"'.$favicon.'\"/>'.\"\\n\";\t// Not required into an Android webview\n\t\t//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel=\"top\" title=\"'.$langs->trans(\"Home\").'\" href=\"'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'\">'.\"\\n\";\n\t\t//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel=\"copyright\" title=\"GNU General Public License\" href=\"http://www.gnu.org/copyleft/gpl.html#SEC1\">'.\"\\n\";\n\t\t//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel=\"author\" title=\"Dolibarr Development Team\" href=\"https://www.dolibarr.org\">'.\"\\n\";", "\t\t// Displays title\n\t\t$appli=constant('DOL_APPLICATION_TITLE');\n\t\tif (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;", "\t\tif ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';\n\t\telse if ($title) print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';\n\t\telse print \"<title>\".dol_htmlentities($appli).\"</title>\";\n\t\tprint \"\\n\";", "\t\tif (GETPOST('version','int')) $ext='version='.GETPOST('version','int');\t// usefull to force no cache on css/js\n\t\tif (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);", "\t\t$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;\n\t\t$themeparam.=($ext?'&amp;'.$ext:'');\n\t\tif (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];\n\t\tif (GETPOST('dol_hide_topmenu','int')) { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }\n\t\tif (GETPOST('dol_hide_leftmenu','int')) { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }\n\t\tif (GETPOST('dol_optimize_smallscreen','int')) { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }\n\t\tif (GETPOST('dol_no_mouse_hover','int')) { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }\n\t\tif (GETPOST('dol_use_jmobile','int')) { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }", "\t\tif (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)\n\t\t{\n\t\t\tprint '<!-- Includes CSS for JQuery (Ajax library) -->'.\"\\n\";\n\t\t\t$jquerytheme = 'base';\n\t\t\tif (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;\n\t\t\tif (constant('JS_JQUERY_UI')) print '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'\">'.\"\\n\"; // JQuery\n\t\t\telse print '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'\">'.\"\\n\"; // JQuery\n\t\t\tif (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'\">'.\"\\n\"; // JNotify\n\t\t\tif (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) // jQuery plugin \"mutiselect\", \"multiple-select\", \"select2\"...\n\t\t\t{\n\t\t\t\t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;\n\t\t\t\tprint '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'\">'.\"\\n\";\n\t\t\t}\n\t\t}", "\t\tif (! defined('DISABLE_FONT_AWSOME'))\n\t\t{\n\t\t\tprint '<!-- Includes CSS for font awesome -->'.\"\\n\";\n\t\t\tprint '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'\">'.\"\\n\";\n\t\t}", "\t\tprint '<!-- Includes CSS for Dolibarr theme -->'.\"\\n\";\n\t\t// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'\n\t\t$themepath=dol_buildpath($conf->css,1);\n\t\t$themesubdir='';\n\t\tif (! empty($conf->modules_parts['theme']))\t// This slow down\n\t\t{\n\t\t\tforeach($conf->modules_parts['theme'] as $reldir)\n\t\t\t{\n\t\t\t\tif (file_exists(dol_buildpath($reldir.$conf->css, 0)))\n\t\t\t\t{\n\t\t\t\t\t$themepath=dol_buildpath($reldir.$conf->css, 1);\n\t\t\t\t\t$themesubdir=$reldir;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;\n\t\tprint '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.$themepath.$themeparam.'\">'.\"\\n\";\n\t\tif (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'.\"\\n\".'<link rel=\"stylesheet\" type=\"text/css\" href=\"filethatdoesnotexiststosolvechromeflashbug\">'.\"\\n\";", "\t\t// CSS forced by modules (relative url starting with /)\n\t\tif (! empty($conf->modules_parts['css']))\n\t\t{\n\t\t\t$arraycss=(array) $conf->modules_parts['css'];\n\t\t\tforeach($arraycss as $modcss => $filescss)\n\t\t\t{\n\t\t\t\t$filescss=(array) $filescss;\t// To be sure filecss is an array\n\t\t\t\tforeach($filescss as $cssfile)\n\t\t\t\t{\n\t\t\t\t\tif (empty($cssfile)) dol_syslog(\"Warning: module \".$modcss.\" declared a css path file into its descriptor that is empty.\", LOG_WARNING);\n\t\t\t\t\t// cssfile is a relative path\n\t\t\t\t\tprint '<!-- Includes CSS added by module '.$modcss. ' -->'.\"\\n\".'<link rel=\"stylesheet\" type=\"text/css\" href=\"'.dol_buildpath($cssfile,1);\n\t\t\t\t\t// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.\n\t\t\t\t\tif (!preg_match('/\\.css$/i',$cssfile)) print $themeparam;\n\t\t\t\t\tprint '\">'.\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// CSS forced by page in top_htmlhead call (relative url starting with /)\n\t\tif (is_array($arrayofcss))\n\t\t{\n\t\t\tforeach($arrayofcss as $cssfile)\n\t\t\t{\n\t\t\t\tprint '<!-- Includes CSS added by page -->'.\"\\n\".'<link rel=\"stylesheet\" type=\"text/css\" title=\"default\" href=\"'.dol_buildpath($cssfile,1);\n\t\t\t\t// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.\n\t\t\t\tif (!preg_match('/\\.css$/i',$cssfile)) print $themeparam;\n\t\t\t\tprint '\">'.\"\\n\";\n\t\t\t}\n\t\t}", "\t\t// Output standard javascript links\n\t\tif (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\t// JQuery. Must be before other includes\n\t\t\tprint '<!-- Includes JS for JQuery -->'.\"\\n\";\n\t\t\tif (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type=\"text/javascript\" src=\"'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\telse print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\tif (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))\n\t\t\t{\n\t\t\t\tif (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type=\"text/javascript\" src=\"'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\telse print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t}\n\t\t\tif (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type=\"text/javascript\" src=\"'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\telse print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\tif (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t// jQuery jnotify\n\t\t\tif (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))\n\t\t\t{\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t}\n\t\t\t// Flot\n\t\t\tif (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))\n\t\t\t{\n\t\t\t\tif (constant('JS_JQUERY_FLOT'))\n\t\t\t\t{\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t// jQuery jeditable\n\t\t\tif (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))\n\t\t\t{\n\t\t\t\tprint '<!-- JS to manage editInPlace feature -->'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\">'.\"\\n\";\n\t\t\t\tprint 'var urlSaveInPlace = \\''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\\';'.\"\\n\";\n\t\t\t\tprint 'var urlLoadInPlace = \\''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\\';'.\"\\n\";\n\t\t\t\tprint 'var tooltipInPlace = \\''.$langs->transnoentities('ClickToEdit').'\\';'.\"\\n\";\t// Added in title attribute of span\n\t\t\t\tprint 'var placeholderInPlace = \\'&nbsp;\\';'.\"\\n\";\t// If we put another string than $langs->trans(\"ClickToEdit\") here, nothing is shown. If we put empty string, there is error, Why ?\n\t\t\t\tprint 'var cancelInPlace = \\''.$langs->trans('Cancel').'\\';'.\"\\n\";\n\t\t\t\tprint 'var submitInPlace = \\''.$langs->trans('Ok').'\\';'.\"\\n\";\n\t\t\t\tprint 'var indicatorInPlace = \\'<img src=\"'.DOL_URL_ROOT.\"/theme/\".$conf->theme.\"/img/working.gif\".'\">\\';'.\"\\n\";\n\t\t\t\tprint 'var withInPlace = 300;';\t\t// width in pixel for default string edit\n\t\t\t\tprint '</script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t}\n // jQuery Timepicker\n if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))\n {\n \tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n \tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'\"></script>'.\"\\n\";\n }\n if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) // jQuery plugin \"mutiselect\", \"multiple-select\", \"select2\", ...\n {\n \t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;\n \tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\t// We include full because we need the support of containerCssClass\n }\n }", " if (! $disablejs && ! empty($conf->use_javascript_ajax))\n {\n // CKEditor\n if (! empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && ! defined('DISABLE_CKEDITOR'))\n {\n print '<!-- Includes JS for CKEditor -->'.\"\\n\";\n $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';\n $jsckeditor='ckeditor.js';\n if (constant('JS_CKEDITOR'))\t// To use external ckeditor 4 js lib\n {\n \t$pathckeditor=constant('JS_CKEDITOR');\n }\n print '<script type=\"text/javascript\">';\n print 'var CKEDITOR_BASEPATH = \\''.$pathckeditor.'\\';'.\"\\n\";\n print 'var ckeditorConfig = \\''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\\';'.\"\\n\";\t\t// $themesubdir='' in standard usage\n print 'var ckeditorFilebrowserBrowseUrl = \\''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\\';'.\"\\n\";\n print 'var ckeditorFilebrowserImageBrowseUrl = \\''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\\';'.\"\\n\";\n print '</script>'.\"\\n\";\n print '<script type=\"text/javascript\" src=\"'.$pathckeditor.$jsckeditor.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n }", " // Browser notifications\n if (! defined('DISABLE_BROWSER_NOTIF'))\n {\n $enablebrowsernotif=false;\n if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;\n if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;\n if ($enablebrowsernotif)\n {\n print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'.\"\\n\";\n print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n }\n }", " // Global js function\n print '<!-- Includes JS of Dolibarr -->'.\"\\n\";\n print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'\"></script>'.\"\\n\";", " // JS forced by modules (relative url starting with /)\n if (! empty($conf->modules_parts['js']))\t\t// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))\n \t{\n \t\t$arrayjs=(array) $conf->modules_parts['js'];\n\t foreach($arrayjs as $modjs => $filesjs)\n\t {\n \t\t\t$filesjs=(array) $filesjs;\t// To be sure filejs is an array\n\t\t foreach($filesjs as $jsfile)\n\t\t {\n\t \t \t\t// jsfile is a relative path\n\t \t \tprint '<!-- Include JS added by module '.$modjs. '-->'.\"\\n\".'<script type=\"text/javascript\" src=\"'.dol_buildpath($jsfile,1).'\"></script>'.\"\\n\";\n\t\t }\n\t }\n \t}\n // JS forced by page in top_htmlhead (relative url starting with /)\n if (is_array($arrayofjs))\n {\n print '<!-- Includes JS added by page -->'.\"\\n\";\n foreach($arrayofjs as $jsfile)\n {\n if (preg_match('/^http/i',$jsfile))\n {\n print '<script type=\"text/javascript\" src=\"'.$jsfile.'\"></script>'.\"\\n\";\n }\n else\n {\n if (! preg_match('/^\\//',$jsfile)) $jsfile='/'.$jsfile;\t// For backward compatibility\n print '<script type=\"text/javascript\" src=\"'.dol_buildpath($jsfile,1).'\"></script>'.\"\\n\";\n }\n }\n }\n }", " if (! empty($head)) print $head.\"\\n\";\n if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER.\"\\n\";", " print \"</head>\\n\\n\";\n }", " $conf->headerdone=1;\t// To tell header was output\n}", "\n/**\n * Show an HTML header + a BODY + The top menu bar\n *\n * @param string\t$head \t\t\tLines in the HEAD\n * @param string\t$title \t\t\tTitle of web page\n * @param string\t$target \t\t\tTarget to use in menu links (Example: '' or '_top')\n *\t@param\t\tint\t\t$disablejs\t\t\tDo not output links to js (Ex: qd fonction utilisee par sous formulaire Ajax)\n *\t@param\t\tint\t\t$disablehead\t\tDo not output head section\n *\t@param\t\tarray\t$arrayofjs\t\t\tArray of js files to add in header\n *\t@param\t\tarray\t$arrayofcss\t\t\tArray of css files to add in header\n * @param\t\tstring\t$morequerystring\tQuery string to add to the link \"print\" to get same parameters (use only if autodetect fails)\n * @param string\t$helppagename \tName of wiki page for help ('' by default).\n * \t\t\t\t \t\t Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage\n * \t\t\t\t\t\t\t\t\t For other external page: http://server/url\n * @return\t\tvoid\n */\nfunction top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')\n{\n\tglobal $user, $conf, $langs, $db;\n\tglobal $dolibarr_main_authentication, $dolibarr_main_demo;\n\tglobal $hookmanager,$menumanager;", "\t$searchform='';\n\t$bookmarks='';", "\t// Instantiate hooks of thirdparty module\n\t$hookmanager->initHooks(array('toprightmenu'));", "\t$toprightmenu='';", "\t// For backward compatibility with old modules\n\tif (empty($conf->headerdone))\n\t{\n\t\ttop_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);\n\t\tprint '<body id=\"mainbody\">';\n\t}", "\t/*\n * Top menu\n */\n\tif (empty($conf->dol_hide_topmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))\n\t{\n\t\tprint \"\\n\".'<!-- Start top horizontal -->'.\"\\n\";", "\t\tprint '<div class=\"side-nav-vert\"><div id=\"id-top\">';", "\t\t// Show menu entries\n\t\tprint '<div id=\"tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'\" class=\"tmenu\">'.\"\\n\";\n\t\t$menumanager->atarget=$target;\n\t\t$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \\n\n\t\tprint \"</div>\\n\";", "\t\t// Define link to login card\n\t\t$appli=constant('DOL_APPLICATION_TITLE');\n\t\tif (! empty($conf->global->MAIN_APPLICATION_TITLE))\n\t\t{\n\t\t\t$appli=$conf->global->MAIN_APPLICATION_TITLE;\n\t\t\tif (preg_match('/\\d\\.\\d/', $appli))\n\t\t\t{\n\t\t\t\tif (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=\" (\".DOL_VERSION.\")\";\t// If new title contains a version that is different than core\n\t\t\t}\n\t\t\telse $appli.=\" \".DOL_VERSION;\n\t\t}\n\t\telse $appli.=\" \".DOL_VERSION;", "\t\tif (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.=\"<br>\".$langs->trans(\"LevelOfFeature\").': '.$conf->global->MAIN_FEATURES_LEVEL;", "\t\t$logouttext='';\n\t\tif (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))\n\t\t{\n\t\t\t//$logouthtmltext=$appli.'<br>';\n\t\t\tif ($_SESSION[\"dol_authmode\"] != 'forceuser' && $_SESSION[\"dol_authmode\"] != 'http')\n\t\t\t{\n\t\t\t\t$logouthtmltext.=$langs->trans(\"Logout\").'<br>';", "\t\t\t\t$logouttext .='<a href=\"'.DOL_URL_ROOT.'/user/logout.php\">';\n\t\t\t\t//$logouttext .= img_picto($langs->trans('Logout').\":\".$langs->trans('Logout'), 'logout_top.png', 'class=\"login\"', 0, 0, 1);\n\t\t\t\t$logouttext .='<span class=\"fa fa-sign-out atoplogin\"></span>';\n\t\t\t\t$logouttext .='</a>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$logouthtmltext.=$langs->trans(\"NoLogoutProcessWithAuthMode\",$_SESSION[\"dol_authmode\"]);\n\t\t\t\t$logouttext .= img_picto($langs->trans('Logout').\":\".$langs->trans('Logout'), 'logout_top.png', 'class=\"login\"', 0, 0, 1);\n\t\t\t}\n\t\t}", "\t\tprint '<div class=\"login_block\">'.\"\\n\";", "\t\t// Add login user link\n\t\t$toprightmenu.='<div class=\"login_block_user\">';", "\t\t// Login name with photo and tooltip\n\t\t$mode=-1;\n\t\t$toprightmenu.='<div class=\"inline-block nowrap\"><div class=\"inline-block login_block_elem login_block_elem_name\" style=\"padding: 0px;\">';\n\t\t$toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');\n\t\t$toprightmenu.='</div></div>';", "\t\t$toprightmenu.='</div>'.\"\\n\";", "\t\t$toprightmenu.='<div class=\"login_block_other\">';", "\t\t// Execute hook printTopRightMenu (hooks should output string like '<div class=\"login\"><a href=\"\">mylink</a></div>')\n\t\t$parameters=array();\n\t\t$result=$hookmanager->executeHooks('printTopRightMenu',$parameters); // Note that $action and $object may have been modified by some hooks\n\t\tif (is_numeric($result))\n\t\t{\n\t\t\tif (empty($result)) $toprightmenu.=$hookmanager->resPrint;\t\t// add\n\t\t\telse $toprightmenu=$hookmanager->resPrint;\t\t\t\t\t\t// replace\n\t\t}\n\t\telse $toprightmenu.=$result;\t// For backward compatibility", "\t\t// Link to module builder\n\t\tif (! empty($conf->modulebuilder->enabled))\n\t\t{\n\t\t\t$text ='<a href=\"'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools\" target=\"_modulebuilder\">';\n\t\t\t//$text.= img_picto(\":\".$langs->trans(\"ModuleBuilder\"), 'printer_top.png', 'class=\"printer\"');\n\t\t\t$text.='<span class=\"fa fa-bug atoplogin\"></span>';\n\t\t\t$text.='</a>';\n\t\t\t$toprightmenu.=@Form::textwithtooltip('',$langs->trans(\"ModuleBuilder\"),2,1,$text,'login_block_elem',2);\n\t\t}", "\t\t// Link to print main content area\n\t\tif (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && empty($conf->browser->phone))\n\t\t{\n\t\t\t$qs=dol_escape_htmltag($_SERVER[\"QUERY_STRING\"]);", "\t\t\tif (is_array($_POST))\n\t\t\t{\n\t\t\t\tforeach($_POST as $key=>$value) {\n\t\t\t\t\tif ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;\n\t\t\t$text ='<a href=\"'.dol_escape_htmltag($_SERVER[\"PHP_SELF\"]).'?'.$qs.($qs?'&':'').'optioncss=print\" target=\"_blank\">';\n\t\t\t//$text.= img_picto(\":\".$langs->trans(\"PrintContentArea\"), 'printer_top.png', 'class=\"printer\"');\n\t\t\t$text.='<span class=\"fa fa-print atoplogin\"></span>';\n\t\t\t$text.='</a>';\n\t\t\t$toprightmenu.=@Form::textwithtooltip('',$langs->trans(\"PrintContentArea\"),2,1,$text,'login_block_elem',2);\n\t\t}", "\t\t// Link to Dolibarr wiki pages\n\t\tif (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))\n\t\t{\n\t\t\t$langs->load(\"help\");", "\t\t\t$helpbaseurl='';\n\t\t\t$helppage='';\n\t\t\t$mode='';", "\t\t\tif (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:DocumentaciΓ³n_usuarios';", "\t\t\t// Get helpbaseurl, helppage and mode from helppagename and langs\n\t\t\t$arrayres=getHelpParamFor($helppagename,$langs);\n\t\t\t$helpbaseurl=$arrayres['helpbaseurl'];\n\t\t\t$helppage=$arrayres['helppage'];\n\t\t\t$mode=$arrayres['mode'];", "\t\t\t// Link to help pages\n\t\t\tif ($helpbaseurl && $helppage)\n\t\t\t{\n\t\t\t\t$text='';\n\t\t\t\t$title=$appli.'<br>';\n\t\t\t\t$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');\n\t\t\t\tif ($mode == 'wiki') $title.=' - '.$langs->trans(\"PageWiki\").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';\n\t\t\t\t$text.='<a class=\"help\" target=\"_blank\" rel=\"noopener\" href=\"';\n\t\t\t\tif ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));\n\t\t\t\telse $text.=sprintf($helpbaseurl,$helppage);\n\t\t\t\t$text.='\">';\n\t\t\t\t//$text.=img_picto('', 'helpdoc_top').' ';\n\t\t\t\t$text.='<span class=\"fa fa-question-circle atoplogin\"></span>';\n\t\t\t\t//$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');\n\t\t\t\t//if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';\n\t\t\t\t$text.='</a>';\n\t\t\t\t//$toprightmenu.='</div>'.\"\\n\";\n\t\t\t\t$toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);\n\t\t\t}\n\t\t}", "\t\t// Logout link\n\t\t$toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);", "\t\t$toprightmenu.='</div>';", "\t\tprint $toprightmenu;", "\t\tprint \"</div>\\n\";\n\t\tprint '</div></div>';\n", "\t\t//unset($form);\n", "\t\tprint '<div style=\"clear: both;\"></div>';\n\t\tprint \"<!-- End top horizontal menu -->\\n\\n\";\n\t}", "\tif (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id=\"id-container\" class=\"id-container'.($morecss?' '.$morecss:'').'\">';\n}", "\n/**\n * Show left menu bar\n *\n * @param array\t$menu_array_before \t \tTable of menu entries to show before entries of menu handler. This param is deprectaed and must be provided to ''.\n * @param string\t$helppagename \t \tName of wiki page for help ('' by default).\n * \t\t\t\t \t\t \tSyntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage\n * \t\t\t\t\t\t\t\t\t \t\t For other external page: http://server/url\n * @param string\t$notused \t\tDeprecated. Used in past to add content into left menu. Hooks can be used now.\n * @param array\t$menu_array_after Table of menu entries to show after entries of menu handler\n * @param int\t\t$leftmenuwithoutmainarea Must be set to 1. 0 by default for backward compatibility with old modules.\n * @param string\t$title Title of web page\n * @param string $acceptdelayedhtml 1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)\n * @return\tvoid\n */\nfunction left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)\n{\n\tglobal $user, $conf, $langs, $db, $form;\n\tglobal $hookmanager, $menumanager;", "\t$searchform='';\n\t$bookmarks='';", "\tif (! empty($menu_array_before)) dol_syslog(\"Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.\", LOG_WARNING);", "\tif (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))\n\t{\n\t\t// Instantiate hooks of thirdparty module\n\t\t$hookmanager->initHooks(array('searchform','leftblock'));", "\t\tprint \"\\n\".'<!-- Begin side-nav id-left -->'.\"\\n\".'<div class=\"side-nav\"><div id=\"id-left\">'.\"\\n\";", "\t\tif ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;\t// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?", "\t\tprint \"\\n\";\n\t\tif ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))\n\t\t{\n\t\t\tif (! is_object($form)) $form=new Form($db);\n\t\t\t$selected=-1;\n\t\t\t$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans(\"Search\"), 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (! is_object($form)) $form=new Form($db);\n\t\t\t$selected=-1;\n\t\t\t$usedbyinclude=1;\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';", "\t\t\tforeach($arrayresult as $key => $val)\n\t\t\t{\n\t\t\t\t//$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));\n\t\t\t\t$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));\n\t\t\t}\n\t\t}", "\t\t// Execute hook printSearchForm\n\t\t$parameters=array('searchform'=>$searchform);\n\t\t$reshook=$hookmanager->executeHooks('printSearchForm',$parameters); // Note that $action and $object may have been modified by some hooks\n\t\tif (empty($reshook))\n\t\t{\n\t\t\t$searchform.=$hookmanager->resPrint;\n\t\t}\n\t\telse $searchform=$hookmanager->resPrint;", "\t\t// Force special value for $searchform\n\t\tif (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\t$urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';\n\t\t\t$searchform='<div class=\"blockvmenuimpair blockvmenusearchphone\"><div id=\"divsearchforms1\"><a href=\"'.$urltosearch.'\" alt=\"'.dol_escape_htmltag($langs->trans(\"ShowSearchFields\")).'\">'.$langs->trans(\"Search\").'...</a></div></div>';\n\t\t}\n\t\telseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))\n\t\t{\n\t\t\t$searchform='<div class=\"blockvmenuimpair blockvmenusearchphone\"><div id=\"divsearchforms1\"><a href=\"#\" alt=\"'.dol_escape_htmltag($langs->trans(\"ShowSearchFields\")).'\">'.$langs->trans(\"Search\").'...</a></div><div id=\"divsearchforms2\" style=\"display: none\">'.$searchform.'</div>';\n\t\t\t$searchform.='<script type=\"text/javascript\">\n \tjQuery(document).ready(function () {\n \t\tjQuery(\"#divsearchforms1\").click(function(){\n\t jQuery(\"#divsearchforms2\").toggle();\n\t });\n \t});\n </script>' . \"\\n\";\n\t\t\t$searchform.='</div>';\n\t\t}", "\t\t// Define $bookmarks\n\t\tif (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)\n\t\t{\n\t\t\tinclude_once (DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php');\n\t\t\t$langs->load(\"bookmarks\");", "\t\t\t$bookmarks=printBookmarksList($db, $langs);\n\t\t}", "\t\t// Left column\n\t\tprint '<!-- Begin left menu -->'.\"\\n\";", "\t\tprint '<div class=\"vmenu\"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title=\"Left menu\"').'>'.\"\\n\\n\";", "\t\t// Show left menu with other forms\n\t\t$menumanager->menu_array = $menu_array_before;\n\t\t$menumanager->menu_array_after = $menu_array_after;\n\t\t$menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database", "\t\t// Dolibarr version + help + bug report link\n\t\tprint \"\\n\";\n\t\tprint \"<!-- Begin Help Block-->\\n\";\n\t\tprint '<div id=\"blockvmenuhelp\" class=\"blockvmenuhelp\">'.\"\\n\";", "\t\t// Version\n\t\tif (empty($conf->global->MAIN_HIDE_VERSION)) // Version is already on help picto and on login page.\n\t\t{\n\t\t\t$doliurl='https://www.dolibarr.org';\n\t\t\t//local communities\n\t\t\tif (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';\n\t\t\tif (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';\n\t\t\tif (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';\n\t\t\tif (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';\n\t\t\tif (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';", "\t\t\t$appli=constant('DOL_APPLICATION_TITLE');\n\t\t\tif (! empty($conf->global->MAIN_APPLICATION_TITLE))\n\t\t\t{\n\t\t\t\t$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';\n\t\t\t\tif (preg_match('/\\d\\.\\d/', $appli))\n\t\t\t\t{\n\t\t\t\t\tif (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=\" (\".DOL_VERSION.\")\";\t// If new title contains a version that is different than core\n\t\t\t\t}\n\t\t\t\telse $appli.=\" \".DOL_VERSION;\n\t\t\t}\n\t\t\telse $appli.=\" \".DOL_VERSION;\n\t\t\tprint '<div id=\"blockvmenuhelpapp\" class=\"blockvmenuhelp\">';\n\t\t\tif ($doliurl) print '<a class=\"help\" target=\"_blank\" rel=\"noopener\" href=\"'.$doliurl.'\">';\n\t\t\telse print '<span class=\"help\">';\n\t\t\tprint $appli;\n\t\t\tif ($doliurl) print '</a>';\n\t\t\telse print '</span>';\n\t\t\tprint '</div>'.\"\\n\";\n\t\t}", "\t\t// Link to bugtrack\n\t\tif (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';", "\t\t\t$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';\n\t\t\t$bugbaseurl.= '?title=';\n\t\t\t$bugbaseurl.= urlencode(\"Bug: \");\n\t\t\t$bugbaseurl.= '&body=';\n\t\t\t// TODO use .github/ISSUE_TEMPLATE.md to generate?\n\t\t\t$bugbaseurl .= urlencode(\"# Bug\\n\");\n\t\t\t$bugbaseurl .= urlencode(\"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"## Environment\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **Version**: \" . DOL_VERSION . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **OS**: \" . php_uname('s') . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **Web server**: \" . $_SERVER[\"SERVER_SOFTWARE\"] . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **PHP**: \" . php_sapi_name() . ' ' . phpversion() . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **Database**: \" . $db::LABEL . ' ' . $db->getVersion() . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **URL**: \" . $_SERVER[\"REQUEST_URI\"] . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"## Report\\n\");\n\t\t\tprint '<div id=\"blockvmenuhelpbugreport\" class=\"blockvmenuhelp\">';\n\t\t\tprint '<a class=\"help\" target=\"_blank\" rel=\"noopener\" href=\"'.$bugbaseurl.'\">'.$langs->trans(\"FindBug\").'</a>';\n\t\t\tprint '</div>';\n\t\t}", "\t\tprint \"</div>\\n\";\n\t\tprint \"<!-- End Help Block-->\\n\";\n\t\tprint \"\\n\";", "\t\tprint \"</div>\\n\";\n\t\tprint \"<!-- End left menu -->\\n\";\n\t\tprint \"\\n\";", "\t\t// Execute hook printLeftBlock\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('printLeftBlock',$parameters); // Note that $action and $object may have been modified by some hooks\n\t\tprint $hookmanager->resPrint;", "\t\tprint '</div></div> <!-- End side-nav id-left -->';\t// End div id=\"side-nav\" div id=\"id-left\"\n\t}", "\tprint \"\\n\";\n\tprint '<!-- Begin right area -->'.\"\\n\";", "\tif (empty($leftmenuwithoutmainarea)) main_area($title);\n}", "\n/**\n * Begin main area\n *\n * @param\tstring\t$title\t\tTitle\n * @return\tvoid\n */\nfunction main_area($title='')\n{\n\tglobal $conf, $langs;", "\tif (empty($conf->dol_hide_leftmenu)) print '<div id=\"id-right\">';", "\tprint \"\\n\";", "\tprint '<!-- Begin div class=\"fiche\" -->'.\"\\n\".'<div class=\"fiche\">'.\"\\n\";", "\tif (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans(\"WarningYouAreInMaintenanceMode\",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));\n}", "\n/**\n * Return helpbaseurl, helppage and mode\n *\n * @param\tstring\t\t$helppagename\t\tPage name ('EN:xxx,ES:eee,FR:fff...' or 'http://localpage')\n * @param Translate\t$langs\t\t\t\tLanguage\n * @return\tarray\t\tArray of help urls\n */\nfunction getHelpParamFor($helppagename,$langs)\n{\n\t$helpbaseurl='';\n\t$helppage='';\n\t$mode='';", "\tif (preg_match('/^http/i',$helppagename))\n\t{\n\t\t// If complete URL\n\t\t$helpbaseurl='%s';\n\t\t$helppage=$helppagename;\n\t\t$mode='local';\n\t}\n\telse\n\t{\n\t\t// If WIKI URL\n\t\tif (preg_match('/^es/i',$langs->defaultlang))\n\t\t{\n\t\t\t$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';\n\t\t\tif (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];\n\t\t}\n\t\tif (preg_match('/^fr/i',$langs->defaultlang))\n\t\t{\n\t\t\t$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';\n\t\t\tif (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];\n\t\t}\n\t\tif (empty($helppage))\t// If help page not already found\n\t\t{\n\t\t\t$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';\n\t\t\tif (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];\n\t\t}\n\t\t$mode='wiki';\n\t}\n\treturn array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);\n}", "\n/**\n * Show a search area.\n * Used when the javascript quick search is not used.\n *\n * @param string\t$urlaction Url post\n * @param string\t$urlobject Url of the link under the search box\n * @param string\t$title Title search area\n * @param string\t$htmlmorecss Add more css\n * @param string\t$htmlinputname Field Name input form\n * @param\tstring\t$accesskey\t\t\tAccesskey\n * @param string $prefhtmlinputname Complement for id to avoid multiple same id in the page\n * @param\tstring\t$img\t\t\t\tImage to use\n * @param\tstring\t$showtitlebefore\tShow title before input text instead of into placeholder. This can be set when output is dedicated for text browsers.\n * @return\tstring\n */\nfunction printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='', $showtitlebefore=0)\n{\n\tglobal $conf,$langs,$user;", "\t$ret='';\n\t$ret.='<form action=\"'.$urlaction.'\" method=\"post\" class=\"searchform\">';\n\t$ret.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t$ret.='<input type=\"hidden\" name=\"mode\" value=\"search\">';\n\t$ret.='<input type=\"hidden\" name=\"savelogin\" value=\"'.dol_escape_htmltag($user->login).'\">';\n\tif ($showtitlebefore) $ret.=$title.' ';\n\t$ret.='<input type=\"text\" class=\"flat '.$htmlmorecss.'\"';\n\t$ret.=' style=\"text-indent: 22px; background-image: url(\\''.$img.'\\'); background-repeat: no-repeat; background-position: 3px;\"';\n\t$ret.=($accesskey?' accesskey=\"'.$accesskey.'\"':'');\n\t$ret.=' placeholder=\"'.strip_tags($title).'\"';\n\t$ret.=' name=\"'.$htmlinputname.'\" id=\"'.$prefhtmlinputname.$htmlinputname.'\" />';\n\t$ret.='<input type=\"submit\" class=\"button\" style=\"padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px\" value=\"'.$langs->trans(\"Go\").'\">';\n\t$ret.=\"</form>\\n\";\n\treturn $ret;\n}", "\nif (! function_exists(\"llxFooter\"))\n{\n\t/**\n\t * Show HTML footer\n\t * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.\n\t * If global var $delayedhtmlcontent was filled, we output it just before closing the body.\n\t *\n\t * @param\tstring\t$comment \t\t\t\tA text to add as HTML comment into HTML generated page\n\t * @param\tstring\t$zone\t\t\t\t\t\t'private' (for private pages) or 'public' (for public pages)\n\t * @param\tint\t\t$disabledoutputofmessages\tClear all messages stored into session without diplaying them\n\t * @return\tvoid\n\t */\n\tfunction llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)\n\t{\n\t\tglobal $conf, $langs, $user, $object;\n\t\tglobal $delayedhtmlcontent;", "\t\t$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);", "\t\t// Global html output events ($mesgs, $errors, $warnings)\n\t\tdol_htmloutput_events($disabledoutputofmessages);", "\t\t// Code for search criteria persistence.\n\t\t// Save $user->lastsearch_values if defined (define on list pages when a form field search_xxx exists)\n\t\tif (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))\n\t\t{\n\t\t\t// Clean data\n\t\t\tforeach($user->lastsearch_values_tmp as $key => $val)\n\t\t\t{\n\t\t\t\tunset($_SESSION['lastsearch_values_tmp_'.$key]);\t\t\t// Clean arry to rebuild it just after\n\t\t\t\tif (count($val) && empty($_POST['button_removefilter']))\t// If there is search criteria to save and we did not click on 'Clear filter' button\n\t\t\t\t{\n\t\t\t\t\tif (empty($val['sortfield'])) unset($val['sortfield']);\n\t\t\t\t\tif (empty($val['sortorder'])) unset($val['sortorder']);\n\t\t\t\t\tdol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0).\" (systematic recording of last search criteria)\");\n\t\t\t\t\t$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);\n\t\t\t\t\tunset($_SESSION['lastsearch_values_'.$key]);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t// Core error message\n\t\tif (! empty($conf->global->MAIN_CORE_ERROR))\n\t\t{\n\t\t\t// Ajax version\n\t\t\tif ($conf->use_javascript_ajax)\n\t\t\t{\n\t\t\t\t$title = img_warning().' '.$langs->trans('CoreErrorTitle');\n\t\t\t\tprint ajax_dialog($title, $langs->trans('CoreErrorMessage'));\n\t\t\t}\n\t\t\t// html version\n\t\t\telse\n\t\t\t{\n\t\t\t\t$msg = img_warning().' '.$langs->trans('CoreErrorMessage');\n\t\t\t\tprint '<div class=\"error\">'.$msg.'</div>';\n\t\t\t}", "\t\t\t//define(\"MAIN_CORE_ERROR\",0); // Constant was defined and we can't change value of a constant\n\t\t}", "\t\tprint \"\\n\\n\";", "\t\tprint '</div> <!-- End div class=\"fiche\" -->'.\"\\n\"; // End div fiche", "\t\tif (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'.\"\\n\"; // End div id-right", "\t\tif (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'.\"\\n\";\t// End div container", "\t\tprint \"\\n\";\n\t\tif ($comment) print '<!-- '.$comment.' -->'.\"\\n\";", "\t\tprintCommonFooter($zone);", "\t\tif (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;", "\t\tif (! empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\tprint \"\\n\".'<!-- Includes JS Footer of Dolibarr -->'.\"\\n\";\n\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'\"></script>'.\"\\n\";\n\t\t}", "\t\t// Wrapper to add log when clicking on download or preview\n\t\tif (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)\n\t\t{\n\t\t\tif (in_array($object->element, array('facture'))) // Restrict for the moment to element 'facture'\n\t\t\t{\n\t\t\t\tprint \"\\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\\n\";\n\t\t\t\t?>\n \t\t\t<script type=\"text/javascript\">\n \t\t\tjQuery(document).ready(function () {\n \t\t\t\t$('a.documentpreview').click(function() {\n \t\t\t\t\t$.post('<?php echo DOL_URL_ROOT.\"/blockedlog/ajax/block-add.php\" ?>'\n \t\t\t\t\t\t\t, {\n \t\t\t\t\t\t\t\tid:<?php echo $object->id; ?>\n \t\t\t\t\t\t\t\t, element:'<?php echo $object->element ?>'\n \t\t\t\t\t\t\t\t, action:'DOC_PREVIEW'\n \t\t\t\t\t\t\t}\n \t\t\t\t\t);\n \t\t\t\t});\n \t\t\t\t$('a.documentdownload').click(function() {\n \t\t\t\t\t$.post('<?php echo DOL_URL_ROOT.\"/blockedlog/ajax/block-add.php\" ?>'\n \t\t\t\t\t\t\t, {\n \t\t\t\t\t\t\t\tid:<?php echo $object->id; ?>\n \t\t\t\t\t\t\t\t, element:'<?php echo $object->element ?>'\n \t\t\t\t\t\t\t\t, action:'DOC_DOWNLOAD'\n \t\t\t\t\t\t\t}\n \t\t\t\t\t);\n \t\t\t\t});\n \t\t\t});\n \t\t\t</script>\n\t\t\t\t<?php\n\t\t\t}\n\t \t}", "\t\t// A div for the address popup\n\t\tprint \"\\n<!-- A div to allow dialog popup -->\\n\";\n\t\tprint '<div id=\"dialogforpopup\" style=\"display: none;\"></div>'.\"\\n\";", "\t\tprint \"</body>\\n\";\n\t\tprint \"</html>\\n\";\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>\n * Copyright (C) 2003 Xavier Dutoit <doli@sydesy.com>\n * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>\n * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>\n * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>\n * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@capnetworks.com>\n * Copyright (C) 2011-2014 Philippe Grand <philippe.grand@atoo-net.com>\n * Copyright (C) 2008 Matteli\n * Copyright (C) 2011-2016 Juanjo Menent <jmenent@2byte.es>\n * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>\n * Copyright (C) 2014-2015 Marcos GarcΓ­a <marcosgdf@gmail.com>\n * Copyright (C) 2015 RaphaΓ«l Doursenaud <rdoursenaud@gpcsolutions.fr>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n *\t\\file htdocs/main.inc.php\n *\t\\ingroup\tcore\n *\t\\brief File that defines environment for Dolibarr GUI pages only (file not required by scripts)\n */", "//@ini_set('memory_limit', '128M');\t// This may be useless if memory is hard limited by your PHP", "// For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.\n$micro_start_time=0;\nif (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))\n{\n\tlist($usec, $sec) = explode(\" \", microtime());\n\t$micro_start_time=((float) $usec + (float) $sec);\n\t// Add Xdebug code coverage\n\t//define('XDEBUGCOVERAGE',1);\n\tif (defined('XDEBUGCOVERAGE')) {\n\t\txdebug_start_code_coverage();\n\t}\n}", "// Removed magic_quotes\nif (function_exists('get_magic_quotes_gpc'))\t// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5\n{\n\tif (get_magic_quotes_gpc())\n\t{\n\t\t// Forcing parameter setting magic_quotes_gpc and cleaning parameters\n\t\t// (Otherwise he would have for each position, condition\n\t\t// Reading stripslashes variable according to state get_magic_quotes_gpc).\n\t\t// Off mode recommended (just do $db->escape for insert / update).\n\t\tfunction stripslashes_deep($value)\n\t\t{\n\t\t\treturn (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));\n\t\t}\n\t\t$_GET = array_map('stripslashes_deep', $_GET);\n\t\t$_POST = array_map('stripslashes_deep', $_POST);\n\t\t$_FILES = array_map('stripslashes_deep', $_FILES);\n\t\t//$_COOKIE = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql\n\t\t@set_magic_quotes_runtime(0);\n\t}\n}", "/**\n * Security: SQL Injection and XSS Injection (scripts) protection (Filters on GET, POST, PHP_SELF).\n *\n * @param\t\tstring\t\t$val\t\tValue", " * @param\t\tstring\t\t$type\t\t1=GET, 0=POST, 2=PHP_SELF, 3=GET without sql reserved keywords (the less tolerant test)", " * @return\t\tint\t\t\t\t\t\t>0 if there is an injection, 0 if none\n */\nfunction test_sql_and_script_inject($val, $type)\n{\n\t$inj = 0;\n\t// For SQL Injection (only GET are used to be included into bad escaped SQL requests)", "\tif ($type == 1 || $type == 3)\n\t{", "\t\t$inj += preg_match('/delete\\s+from/i',\t $val);\n\t\t$inj += preg_match('/create\\s+table/i',\t $val);\n\t\t$inj += preg_match('/insert\\s+into/i', \t $val);\n\t\t$inj += preg_match('/select\\s+from/i', \t $val);\n\t\t$inj += preg_match('/into\\s+(outfile|dumpfile)/i', $val);", "\t\t$inj += preg_match('/user\\s*\\(/i', $val);\t\t\t\t\t\t// avoid to use function user() that return current database login\n\t\t$inj += preg_match('/information_schema/i', $val);\t\t\t\t// avoid to use request that read information_schema database\n\t}\n\tif ($type == 3)\n\t{\n\t\t$inj += preg_match('/select|update|delete|replace|group\\s+by|concat|count|from/i',\t $val);\n\t}\n\tif ($type != 2)\t// Not common key strings, so we can check them both on GET and POST\n\t{\n\t\t$inj += preg_match('/updatexml\\(/i', \t $val);", "\t\t$inj += preg_match('/update.+set.+=/i', $val);\n\t\t$inj += preg_match('/union.+select/i', \t $val);\n\t\t$inj += preg_match('/(\\.\\.%2f)+/i',\t\t $val);\n\t}\n\t// For XSS Injection done by adding javascript with script\n\t// This is all cases a browser consider text is javascript:\n\t// When it found '<script', 'javascript:', '<style', 'onload\\s=' on body tag, '=\"&' on a tag size with old browsers\n\t// All examples on page: http://ha.ckers.org/xss.html#XSScalc\n\t// More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet\n\t$inj += preg_match('/<script/i', $val);\n\t$inj += preg_match('/<iframe/i', $val);\n\t$inj += preg_match('/<audio/i', $val);\n\t$inj += preg_match('/Set\\.constructor/i', $val);\t// ECMA script 6\n\tif (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);\n\t$inj += preg_match('/base[\\s]+href/si', $val);\n\t$inj += preg_match('/<.*onmouse/si', $val); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>\n\t$inj += preg_match('/onerror\\s*=/i', $val); // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>\n\t$inj += preg_match('/onfocus\\s*=/i', $val); // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>\n\t$inj += preg_match('/onload\\s*=/i', $val); // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>\n\t$inj += preg_match('/onloadstart\\s*=/i', $val); // onload can be set on audio tag <audio onloadstart=alert(1)>\n\t$inj += preg_match('/onclick\\s*=/i', $val); // onclick can be set on img text html tag like <img onclick = alert(1)>\n\t$inj += preg_match('/onscroll\\s*=/i', $val); // onscroll can be on textarea\n\t//$inj += preg_match('/on[A-Z][a-z]+\\*=/', $val); // To lock event handlers onAbort(), ...\n\t$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);\t\t// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'\n\t//if ($type == 1)\n\t//{\n\t\t$inj += preg_match('/javascript:/i', $val);\n\t\t$inj += preg_match('/vbscript:/i', $val);\n\t//}\n\t// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)\n\tif ($type == 1) $inj += preg_match('/\"/i', $val);\t\t// We refused \" in GET parameters value\n\tif ($type == 2) $inj += preg_match('/[;\"]/', $val);\t\t// PHP_SELF is a file system path. It can contains spaces.\n\treturn $inj;\n}", "/**\n * Return true if security check on parameters are OK, false otherwise.\n *\n * @param\t\tstring\t\t\t$var\t\tVariable name\n * @param\t\tstring\t\t\t$type\t\t1=GET, 0=POST, 2=PHP_SELF\n * @return\t\tboolean|null\t\t\t\ttrue if there is no injection. Stop code if injection found.\n */\nfunction analyseVarsForSqlAndScriptsInjection(&$var, $type)\n{\n\tif (is_array($var))\n\t{\n\t\tforeach ($var as $key => $value)\t// Warning, $key may also be used for attacks\n\t\t{\n\t\t\tif (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))\n\t\t\t{\n\t\t\t\t//$var[$key] = $value;\t// This is useless\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprint 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER[\"REQUEST_URI\"]).')';\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn (test_sql_and_script_inject($var, $type) <= 0);\n\t}\n}", "\n// Check consistency of NOREQUIREXXX DEFINES\nif ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU'))\n{\n\tprint 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';\n\texit;\n}", "// Sanity check on URL\nif (! empty($_SERVER[\"PHP_SELF\"]))\n{\n\t$morevaltochecklikepost=array($_SERVER[\"PHP_SELF\"]);\n\tanalyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);\n}\n// Sanity check on GET parameters\nif (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER[\"QUERY_STRING\"]))\n{\n\t$morevaltochecklikeget=array($_SERVER[\"QUERY_STRING\"]);\n\tanalyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);\n}\n// Sanity check on POST\nif (! defined('NOSCANPOSTFORINJECTION'))\n{\n\tanalyseVarsForSqlAndScriptsInjection($_POST,0);\n}", "// This is to make Dolibarr working with Plesk\nif (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')\n{\n\tset_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');\n}", "// Include the conf.php and functions.lib.php\nrequire_once 'filefunc.inc.php';", "// If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.\n// This is used for example by form of boxes to save personalization of some options.\n// DOL_AUTOSET_COOKIE=cookiename:val1,val2 and cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))\nif (! empty($_POST[\"DOL_AUTOSET_COOKIE\"]))\n{\n\t$tmpautoset=explode(':',$_POST[\"DOL_AUTOSET_COOKIE\"],2);\n\t$tmplist=explode(',',$tmpautoset[1]);\n\t$cookiearrayvalue=array();\n\tforeach ($tmplist as $tmpkey)\n\t{\n\t\t$postkey=$tmpautoset[0].'_'.$tmpkey;\n\t\t//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);\n\t\tif (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];\n\t}\n\t$cookiename=$tmpautoset[0];\n\t$cookievalue=json_encode($cookiearrayvalue);\n\t//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);\n\tsetcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);\t// keep cookie 1 year and add tag httponly\n\tif (empty($cookievalue)) unset($_COOKIE[$cookiename]);\n}", "\n// Init session. Name of session is specific to Dolibarr instance.\n// Note: the function dol_getprefix may have been redefined to return a different key to manage another area to protect.\n$prefix=dol_getprefix('');", "$sessionname='DOLSESSID_'.$prefix;\n$sessiontimeout='DOLSESSTIMEOUT_'.$prefix;\nif (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);\nsession_name($sessionname);\nsession_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.\n// This create lock, released when session_write_close() or end of page.\n// We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.\nif (! defined('NOSESSION'))\n{\n\tsession_start();\n\tif (ini_get('register_globals')) // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION\n\t{\n\t\tforeach ($_SESSION as $key=>$value)\n\t\t{\n\t\t\tif (isset($GLOBALS[$key])) unset($GLOBALS[$key]);\n\t\t}\n\t}\n}", "// Init the 5 global objects, this include will make the new and set properties for: $conf, $db, $langs, $user, $mysoc\nrequire_once 'master.inc.php';", "// Activate end of page function\nregister_shutdown_function('dol_shutdown');", "// Detection browser\nif (isset($_SERVER[\"HTTP_USER_AGENT\"]))\n{\n\t$tmp=getBrowserInfo($_SERVER[\"HTTP_USER_AGENT\"]);\n\t$conf->browser->name=$tmp['browsername'];\n\t$conf->browser->os=$tmp['browseros'];\n\t$conf->browser->version=$tmp['browserversion'];\n\t$conf->browser->layout=$tmp['layout']; // 'classic', 'phone', 'tablet'\n\t$conf->browser->phone=$tmp['phone'];\t // TODO deprecated, use ->layout\n\t$conf->browser->tablet=$tmp['tablet'];\t // TODO deprecated, use ->layout\n\t//var_dump($conf->browser);", "\tif ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;\n\tif ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;\n}", "// Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)\n// $_SERVER[\"HTTPS\"] is 'on' when link is https, otherwise $_SERVER[\"HTTPS\"] is empty or 'off'\nif (! empty($conf->file->main_force_https) && (empty($_SERVER[\"HTTPS\"]) || $_SERVER[\"HTTPS\"] != 'on'))\n{\n\t$newurl='';\n\tif (is_numeric($conf->file->main_force_https))\n\t{\n\t\tif ($conf->file->main_force_https == '1' && ! empty($_SERVER[\"SCRIPT_URI\"]))\t// If SCRIPT_URI supported by server\n\t\t{\n\t\t\tif (preg_match('/^http:/i',$_SERVER[\"SCRIPT_URI\"]) && ! preg_match('/^https:/i',$_SERVER[\"SCRIPT_URI\"]))\t// If link is http\n\t\t\t{\n\t\t\t\t$newurl=preg_replace('/^http:/i','https:',$_SERVER[\"SCRIPT_URI\"]);\n\t\t\t}\n\t\t}\n\t\telse\t// Check HTTPS environment variable (Apache/mod_ssl only)\n\t\t{\n\t\t\t$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER[\"REQUEST_URI\"];\n\t\t}\n\t}\n\telse\n\t{\n\t\t// Check HTTPS environment variable (Apache/mod_ssl only)\n\t\t$newurl=$conf->file->main_force_https.$_SERVER[\"REQUEST_URI\"];\n\t}\n\t// Start redirect\n\tif ($newurl)\n\t{\n\t\tdol_syslog(\"main.inc: dolibarr_main_force_https is on, we make a redirect to \".$newurl);\n\t\theader(\"Location: \".$newurl);\n\t\texit;\n\t}\n\telse\n\t{\n\t\tdol_syslog(\"main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done\", LOG_WARNING);\n\t}\n}", "\n// Loading of additional presentation includes\nif (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';\t // Need 660ko memory (800ko in 2.2)\nif (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';\t// Need 22ko memory", "// If install or upgrade process not done or not completely finished, we call the install page.\nif (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))\n{\n\tdol_syslog(\"main.inc: A previous install or upgrade was not complete. Redirect to install page.\", LOG_WARNING);\n\theader(\"Location: \".DOL_URL_ROOT.\"/install/index.php\");\n\texit;\n}\n// If an upgrade process is required, we call the install page.\nif ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))\n|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))\n{\n\t$versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;\n\trequire_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';\n\t$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);\n\t$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);\n\t$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);\n\tif ($rescomp > 0) // Programs have a version higher than database. We did not add \"&& $rescomp < 3\" because we want upgrade process for build upgrades\n\t{\n\t\tdol_syslog(\"main.inc: database version \".$versiontocompare.\" is lower than programs version \".DOL_VERSION.\". Redirect to install page.\", LOG_WARNING);\n\t\theader(\"Location: \".DOL_URL_ROOT.\"/install/index.php\");\n\t\texit;\n\t}\n}", "// Creation of a token against CSRF vulnerabilities\nif (! defined('NOTOKENRENEWAL'))\n{\n\t// roulement des jetons car cree a chaque appel\n\tif (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];", "\t// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']\n\t$token = dol_hash(uniqid(mt_rand(),TRUE)); // Generates a hash of a random number\n\t$_SESSION['newtoken'] = $token;\n}\nif ((! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))\n\t|| defined('CSRFCHECK_WITH_TOKEN'))\t// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set\n{\n\tif ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET\n\t{\n\t\tprint \"Access refused by CSRF protection in main.inc.php. Token not provided.\\n\";\n\t\tprint \"If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \\$dolibarr_nocsrfcheck=1 into your conf.php file).\\n\";\n\t\tdie;\n\t}\n\tif ($_SERVER['REQUEST_METHOD'] === 'POST') // This test must be after loading $_SESSION['token'].\n\t{\n\t\tif (GETPOST('token', 'alpha') != $_SESSION['token'])\n\t\t{\n\t\t\tdol_syslog(\"Invalid token in \".$_SERVER['HTTP_REFERER'].\", action=\".GETPOST('action','aZ09').\", _POST['token']=\".GETPOST('token','alpha').\", _SESSION['token']=\".$_SESSION['token'], LOG_WARNING);\n\t\t\t//print 'Unset POST by CSRF protection in main.inc.php.';\t// Do not output anything because this create problems when using the BACK button on browsers.\n\t\t\tunset($_POST);\n\t\t}\n\t}\n}", "// Disable modules (this must be after session_start and after conf has been loaded)\nif (GETPOST('disablemodules','alpha')) $_SESSION[\"disablemodules\"]=GETPOST('disablemodules','alpha');\nif (! empty($_SESSION[\"disablemodules\"]))\n{\n\t$disabled_modules=explode(',',$_SESSION[\"disablemodules\"]);\n\tforeach($disabled_modules as $module)\n\t{\n\t\tif ($module)\n\t\t{\n\t\t\tif (empty($conf->$module)) $conf->$module=new stdClass();\n\t\t\t$conf->$module->enabled=false;\n\t\t\tif ($module == 'fournisseur')\t\t// Special case\n\t\t\t{\n\t\t\t\t$conf->supplier_order->enabled=0;\n\t\t\t\t$conf->supplier_invoice->enabled=0;\n\t\t\t}\n\t\t}\n\t}\n}", "/*\n * Phase authentication / login\n */\n$login='';\nif (! defined('NOLOGIN'))\n{\n\t// $authmode lists the different means of identification to be tested in order of preference.\n\t// Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'", "\tif (defined('MAIN_AUTHENTICATION_MODE'))\n\t{\n\t\t$dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');\n\t}\n\telse\n\t{\n\t\t// Authentication mode\n\t\tif (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';\n\t\t// Authentication mode: forceuser\n\t\tif ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';\n\t}\n\t// Set authmode\n\t$authmode=explode(',',$dolibarr_main_authentication);", "\t// No authentication mode\n\tif (! count($authmode))\n\t{\n\t\t$langs->load('main');\n\t\tdol_print_error('',$langs->trans(\"ErrorConfigParameterNotDefined\",'dolibarr_main_authentication'));\n\t\texit;\n\t}", "\t// If login request was already post, we retrieve login from the session\n\t// Call module if not realized that his request.\n\t// At the end of this phase, the variable $login is defined.\n\t$resultFetchUser='';\n\t$test=true;\n\tif (! isset($_SESSION[\"dol_login\"]))\n\t{\n\t\t// It is not already authenticated and it requests the login / password\n\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';", "\t\t$dol_dst_observed=GETPOST(\"dst_observed\",'int',3);\n\t\t$dol_dst_first=GETPOST(\"dst_first\",'int',3);\n\t\t$dol_dst_second=GETPOST(\"dst_second\",'int',3);\n\t\t$dol_screenwidth=GETPOST(\"screenwidth\",'int',3);\n\t\t$dol_screenheight=GETPOST(\"screenheight\",'int',3);\n\t\t$dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);\n\t\t$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);\n\t\t$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);\n\t\t$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);\n\t\t$dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);\n\t\t//dol_syslog(\"POST key=\".join(array_keys($_POST),',').' value='.join($_POST,','));", "\t\t// If in demo mode, we check we go to home page through the public/demo/index.php page\n\t\tif (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') // We ask index page\n\t\t{\n\t\t\tif (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))\n\t\t\t{\n\t\t\t\tdol_syslog(\"Call index page from another url than demo page (call is done from page \".$_SERVER['HTTP_REFERER'].\")\");\n\t\t\t\t$url='';\n\t\t\t\t$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');\n\t\t\t\t$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');\n\t\t\t\t$url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');\n\t\t\t\t$url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');\n\t\t\t\t$url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');\n\t\t\t\t$url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');\n\t\t\t\theader(\"Location: \".$url);\n\t\t\t\texit;\n\t\t\t}\n\t\t}", "\t\t// Verification security graphic code\n\t\tif (GETPOST(\"username\",\"alpha\",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))\n\t\t{\n\t\t\t$sessionkey = 'dol_antispam_value';\n\t\t\t$ok=(array_key_exists($sessionkey, $_SESSION) === TRUE && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));", "\t\t\t// Check code\n\t\t\tif (! $ok)\n\t\t\t{\n\t\t\t\tdol_syslog('Bad value for code, connexion refused');\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorBadValueForCode\");\n\t\t\t\t$test=false;", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST(\"username\",\"alpha\",2);\n\t\t\t\t// Call of triggers\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t\t\t$interface=new Interfaces($db);\n\t\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);\n\t\t\t\tif ($result < 0) {\n\t\t\t\t\t$error++;\n\t\t\t\t}\n\t\t\t\t// End Call of triggers", "\t\t\t\t// Hooks on failed login\n\t\t\t\t$action='';\n\t\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\t\tif ($reshook < 0) $error++;", "\t\t\t\t// Note: exit is done later\n\t\t\t}\n\t\t}", "\t\t$usertotest\t\t= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST(\"username\",\"alpha\",2));\n\t\t$passwordtotest\t= GETPOST('password','none',2);\n\t\t$entitytotest\t= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));", "\t\t// Define if we received data to test the login.\n\t\t$goontestloop=false;\n\t\tif (isset($_SERVER[\"REMOTE_USER\"]) && in_array('http',$authmode)) $goontestloop=true;\n\t\tif ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;\n\t\tif (GETPOST(\"username\",\"alpha\",2) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;", "\t\tif (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.\n\t\t{\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';\n\t\t\t$langs=new Translate(\"\",$conf);\n\t\t\t$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));\n\t\t\tif (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');\n\t\t\t$langs->setDefaultLang($langcode);\n\t\t}", "\t\t// Validation of login/pass/entity\n\t\t// If ok, the variable login will be returned\n\t\t// If error, we will put error message in session under the name dol_loginmesg\n\t\tif ($test && $goontestloop)\n\t\t{\n\t\t\t$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);\n\t\t\tif ($login)\n\t\t\t{\n\t\t\t\t$dol_authmode=$conf->authmode;\t// This properties is defined only when logged, to say what mode was successfully used\n\t\t\t\t$dol_tz=$_POST[\"tz\"];\n\t\t\t\t$dol_tz_string=$_POST[\"tz_string\"];\n\t\t\t\t$dol_tz_string=preg_replace('/\\s*\\(.+\\)$/','',$dol_tz_string);\n\t\t\t\t$dol_tz_string=preg_replace('/,/','/',$dol_tz_string);\n\t\t\t\t$dol_tz_string=preg_replace('/\\s/','_',$dol_tz_string);\n\t\t\t\t$dol_dst=0;\n\t\t\t\tif (isset($_POST[\"dst_first\"]) && isset($_POST[\"dst_second\"]))\n\t\t\t\t{\n\t\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';\n\t\t\t\t\t$datenow=dol_now();\n\t\t\t\t\t$datefirst=dol_stringtotime($_POST[\"dst_first\"]);\n\t\t\t\t\t$datesecond=dol_stringtotime($_POST[\"dst_second\"]);\n\t\t\t\t\tif ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;\n\t\t\t\t}\n\t\t\t\t//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;\n\t\t\t}", "\t\t\tif (! $login)\n\t\t\t{\n\t\t\t\tdol_syslog('Bad password, connexion refused',LOG_DEBUG);\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t// Bad password. No authmode has found a good password.\n\t\t\t\t// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions\n\t\t\t\tif (empty($_SESSION[\"dol_loginmesg\"])) $_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorBadLoginPassword\");", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg=$langs->trans(\"ErrorBadLoginPassword\").' - login='.GETPOST(\"username\",\"alpha\",2);\n\t\t\t\t// Call of triggers\n\t\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';\n\t\t\t\t$interface=new Interfaces($db);\n\t\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST(\"username\",\"alpha\",2));\n\t\t\t\tif ($result < 0) {\n\t\t\t\t\t$error++;\n\t\t\t\t}\n\t\t\t\t// End Call of triggers", "\t\t\t\t// Hooks on failed login\n\t\t\t\t$action='';\n\t\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\t\tif ($reshook < 0) $error++;", "\t\t\t\t// Note: exit is done in next chapter\n\t\t\t}\n\t\t}", "\t\t// End test login / passwords\n\t\tif (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))\t// With LDAP we refused empty password because some LDAP are \"opened\" for anonymous access so connexion is a success.\n\t\t{\n\t\t\t// No data to test login, so we show the login page\n\t\t\tdol_syslog(\"--- Access to \".$_SERVER[\"PHP_SELF\"].\" showing the login form and exit\");\n\t\t\tif (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';\n\t\t\telse dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));\n\t\t\texit;\n\t\t}", "\t\t$resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));\n\t\tif ($resultFetchUser <= 0)\n\t\t{\n\t\t\tdol_syslog('User not found, connexion refused');\n\t\t\tsession_destroy();\n\t\t\tsession_name($sessionname);\n\t\t\tsession_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie\n\t\t\tsession_start(); // Fixing the bug of register_globals here is useless since session is empty", "\t\t\tif ($resultFetchUser == 0)\n\t\t\t{\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorCantLoadUserFromDolibarrDatabase\",$login);", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;\n\t\t\t}\n\t\t\tif ($resultFetchUser < 0)\n\t\t\t{\n\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$user->error;", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg=$user->error;\n\t\t\t}", "\t\t\t// Call triggers\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t\t$interface=new Interfaces($db);\n\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);\n\t\t\tif ($result < 0) {\n\t\t\t\t$error++;\n\t\t\t}\n\t\t\t// End call triggers", "\t\t\t// Hooks on failed login\n\t\t\t$action='';\n\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\tif ($reshook < 0) $error++;", "\t\t\t$paramsurl=array();\n\t\t\tif (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');\n\t\t\tif (GETPOST('nojs','int')) $paramsurl[]='nojs='.GETPOST('nojs','int');\n\t\t\tif (GETPOST('lang','aZ09')) $paramsurl[]='lang='.GETPOST('lang','aZ09');\n\t\t\theader('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));\n\t\t\texit;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// We are already into an authenticated session\n\t\t$login=$_SESSION[\"dol_login\"];\n\t\t$entity=$_SESSION[\"dol_entity\"];\n\t\tdol_syslog(\"- This is an already logged session. _SESSION['dol_login']=\".$login.\" _SESSION['dol_entity']=\".$entity, LOG_DEBUG);", "\t\t$resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));\n\t\tif ($resultFetchUser <= 0)\n\t\t{\n\t\t\t// Account has been removed after login\n\t\t\tdol_syslog(\"Can't load user even if session logged. _SESSION['dol_login']=\".$login, LOG_WARNING);\n\t\t\tsession_destroy();\n\t\t\tsession_name($sessionname);\n\t\t\tsession_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie\n\t\t\tsession_start(); // Fixing the bug of register_globals here is useless since session is empty", "\t\t\tif ($resultFetchUser == 0)\n\t\t\t{\n\t\t\t\t$langs->load('main');\n\t\t\t\t$langs->load('errors');", "\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$langs->trans(\"ErrorCantLoadUserFromDolibarrDatabase\",$login);", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;\n\t\t\t}\n\t\t\tif ($resultFetchUser < 0)\n\t\t\t{\n\t\t\t\t$_SESSION[\"dol_loginmesg\"]=$user->error;", "\t\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t\t$user->trigger_mesg=$user->error;\n\t\t\t}", "\t\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t\t// Call triggers\n\t\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t\t$interface=new Interfaces($db);\n\t\t\t$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);\n\t\t\tif ($result < 0) {\n\t\t\t\t$error++;\n\t\t\t}\n\t\t\t// End call triggers", "\t\t\t// Hooks on failed login\n\t\t\t$action='';\n\t\t\t$hookmanager->initHooks(array('login'));\n\t\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION[\"dol_loginmesg\"]);\n\t\t\t$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\t\tif ($reshook < 0) $error++;", "\t\t\t$paramsurl=array();\n\t\t\tif (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');\n\t\t\tif (GETPOST('nojs','int')) $paramsurl[]='nojs='.GETPOST('nojs','int');\n\t\t\tif (GETPOST('lang','aZ09')) $paramsurl[]='lang='.GETPOST('lang','aZ09');\n\t\t\theader('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));\n\t\t\texit;\n\t\t}\n\t\telse\n\t\t{\n\t\t // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context\n\t\t $hookmanager->initHooks(array('main'));", "\t\t // Code for search criteria persistence.\n\t\t if (! empty($_GET['save_lastsearch_values'])) // Keep $_GET here\n\t\t {\n\t\t\t $relativepathstring = preg_replace('/\\?.*$/','',$_SERVER[\"HTTP_REFERER\"]);\n\t\t\t $relativepathstring = preg_replace('/^https?:\\/\\/[^\\/]*/','',$relativepathstring); // Get full path except host server\n\t\t\t // Clean $relativepathstring\n \t\t\t if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);\n\t\t\t $relativepathstring = preg_replace('/^\\//', '', $relativepathstring);\n\t\t\t $relativepathstring = preg_replace('/^custom\\//', '', $relativepathstring);\n\t\t\t //var_dump($relativepathstring);", "\t\t\t // We click on a link that leave a page we have to save search criteria. We save them from tmp to no tmp\n\t\t\t if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))\n\t\t\t {\n\t\t\t\t $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];\n\t\t\t\t unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);\n\t\t\t }\n\t\t }", "\t\t $action = '';\n\t\t $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);\n\t\t if ($reshook < 0) {\n\t\t\t setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');\n\t\t }\n\t\t}\n\t}", "\t// Is it a new session that has started ?\n\t// If we are here, this means authentication was successfull.\n\tif (! isset($_SESSION[\"dol_login\"]))\n\t{\n\t\t// New session for this login has started.\n\t\t$error=0;", "\t\t// Store value into session (values always stored)\n\t\t$_SESSION[\"dol_login\"]=$user->login;\n\t\t$_SESSION[\"dol_authmode\"]=isset($dol_authmode)?$dol_authmode:'';\n\t\t$_SESSION[\"dol_tz\"]=isset($dol_tz)?$dol_tz:'';\n\t\t$_SESSION[\"dol_tz_string\"]=isset($dol_tz_string)?$dol_tz_string:'';\n\t\t$_SESSION[\"dol_dst\"]=isset($dol_dst)?$dol_dst:'';\n\t\t$_SESSION[\"dol_dst_observed\"]=isset($dol_dst_observed)?$dol_dst_observed:'';\n\t\t$_SESSION[\"dol_dst_first\"]=isset($dol_dst_first)?$dol_dst_first:'';\n\t\t$_SESSION[\"dol_dst_second\"]=isset($dol_dst_second)?$dol_dst_second:'';\n\t\t$_SESSION[\"dol_screenwidth\"]=isset($dol_screenwidth)?$dol_screenwidth:'';\n\t\t$_SESSION[\"dol_screenheight\"]=isset($dol_screenheight)?$dol_screenheight:'';\n\t\t$_SESSION[\"dol_company\"]=$conf->global->MAIN_INFO_SOCIETE_NOM;\n\t\t$_SESSION[\"dol_entity\"]=$conf->entity;\n\t\t// Store value into session (values stored only if defined)\n\t\tif (! empty($dol_hide_topmenu)) $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;\n\t\tif (! empty($dol_hide_leftmenu)) $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;\n\t\tif (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;\n\t\tif (! empty($dol_no_mouse_hover)) $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;\n\t\tif (! empty($dol_use_jmobile)) $_SESSION['dol_use_jmobile']=$dol_use_jmobile;", "\t\tdol_syslog(\"This is a new started user session. _SESSION['dol_login']=\".$_SESSION[\"dol_login\"].\" Session id=\".session_id());", "\t\t$db->begin();", "\t\t$user->update_last_login_date();", "\t\t$loginfo = 'TZ='.$_SESSION[\"dol_tz\"].';TZString='.$_SESSION[\"dol_tz_string\"].';Screen='.$_SESSION[\"dol_screenwidth\"].'x'.$_SESSION[\"dol_screenheight\"];", "\t\t// TODO @deprecated Remove this. Hook must be used, not this trigger.\n\t\t$user->trigger_mesg = $loginfo;\n\t\t// Call triggers\n\t\tinclude_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';\n\t\t$interface=new Interfaces($db);\n\t\t$result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);\n\t\tif ($result < 0) {\n\t\t\t$error++;\n\t\t}\n\t\t// End call triggers", "\t\t// Hooks on successfull login\n\t\t$action='';\n\t\t$hookmanager->initHooks(array('login'));\n\t\t$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);\n\t\t$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action); // Note that $action and $object may have been modified by some hooks\n\t\tif ($reshook < 0) $error++;", "\t\tif ($error)\n\t\t{\n\t\t\t$db->rollback();\n\t\t\tsession_destroy();\n\t\t\tdol_print_error($db,'Error in some hooks afterLogin (or old trigger USER_LOGIN)');\n\t\t\texit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$db->commit();\n\t\t}", "\t\t// Change landing page if defined.\n\t\t$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);\n\t\tif (! empty($landingpage)) // Example: /index.php\n\t\t{\n\t\t\t$newpath=dol_buildpath($landingpage, 1);\n\t\t\tif ($_SERVER[\"PHP_SELF\"] != $newpath) // not already on landing page (avoid infinite loop)\n\t\t\t{\n\t\t\t\theader('Location: '.$newpath);\n\t\t\t\texit;\n\t\t\t}\n\t\t}\n\t}", "\n\t// If user admin, we force the rights-based modules\n\tif ($user->admin)\n\t{\n\t\t$user->rights->user->user->lire=1;\n\t\t$user->rights->user->user->creer=1;\n\t\t$user->rights->user->user->password=1;\n\t\t$user->rights->user->user->supprimer=1;\n\t\t$user->rights->user->self->creer=1;\n\t\t$user->rights->user->self->password=1;\n\t}", "\t/*\n * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)\n */", "\t// Set liste_limit\n\tif (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))\t$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;\t// Can be 0\n\tif (isset($user->conf->PRODUIT_LIMIT_SIZE))\t$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;\t// Can be 0", "\t// Replace conf->css by personalized value if theme not forced\n\tif (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))\n\t{\n\t\t$conf->theme=$user->conf->MAIN_THEME;\n\t\t$conf->css = \"/theme/\".$conf->theme.\"/style.css.php\";\n\t}\n}", "// Case forcing style from url\nif (GETPOST('theme','alpha'))\n{\n\t$conf->theme=GETPOST('theme','alpha',1);\n\t$conf->css = \"/theme/\".$conf->theme.\"/style.css.php\";\n}", "\n// Set javascript option\nif (! GETPOST('nojs','int')) // If javascript was not disabled on URL\n{\n\tif (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))\n\t{\n\t\t$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;\n\t}\n}\nelse $conf->use_javascript_ajax=0;\n// Set MAIN_OPTIMIZEFORTEXTBROWSER\nif (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER)) // If we must enable text browser\n{\n\t$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;\n}\nelseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))\n{\n\t$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;\n}", "// Set terminal output option according to conf->browser.\nif (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu'])) $conf->dol_hide_leftmenu=1;\nif (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu'])) $conf->dol_hide_topmenu=1;\nif (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1;\nif (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover'])) $conf->dol_no_mouse_hover=1;\nif (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile'])) $conf->dol_use_jmobile=1;\nif (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;\nif ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')\n\t|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)\n\t|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)\n)\n{\n\t$conf->dol_optimize_smallscreen=1;\n}\n// If we force to use jmobile, then we reenable javascript\nif (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;\n// Replace themes bugged with jmobile with eldy\nif (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))\n{\n\t$conf->theme='eldy';\n\t$conf->css = \"/theme/\".$conf->theme.\"/style.css.php\";\n}\n//var_dump($conf->browser->phone);", "if (! defined('NOREQUIRETRAN'))\n{\n\tif (! GETPOST('lang','aZ09'))\t// If language was not forced on URL\n\t{\n\t\t// If user has chosen its own language\n\t\tif (! empty($user->conf->MAIN_LANG_DEFAULT))\n\t\t{\n\t\t\t// If different than current language\n\t\t\t//print \">>>\".$langs->getDefaultLang().\"-\".$user->conf->MAIN_LANG_DEFAULT;\n\t\t\tif ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)\n\t\t\t{\n\t\t\t\t$langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);\n\t\t\t}\n\t\t}\n\t}\n}", "if (! defined('NOLOGIN'))\n{\n\t// If the login is not recovered, it is identified with an account that does not exist.\n\t// Hacking attempt?\n\tif (! $user->login) accessforbidden();", "\t// Check if user is active\n\tif ($user->statut < 1)\n\t{\n\t\t// If not active, we refuse the user\n\t\t$langs->load(\"other\");\n\t\tdol_syslog(\"Authentification ko as login is disabled\");\n\t\taccessforbidden($langs->trans(\"ErrorLoginDisabled\"));\n\t\texit;\n\t}", "\t// Load permissions\n\t$user->getrights();\n}", "\ndol_syslog(\"--- Access to \".$_SERVER[\"PHP_SELF\"].' - action='.GETPOST('action','az09').', massaction='.GETPOST('massaction','az09'));\n//Another call for easy debugg\n//dol_syslog(\"Access to \".$_SERVER[\"PHP_SELF\"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));", "// Load main languages files\nif (! defined('NOREQUIRETRAN'))\n{\n\t$langs->load(\"main\");\n\t$langs->load(\"dict\");\n}", "// Define some constants used for style of arrays\n$bc=array(0=>'class=\"impair\"',1=>'class=\"pair\"');\n$bcdd=array(0=>'class=\"drag drop oddeven\"',1=>'class=\"drag drop oddeven\"');\n$bcnd=array(0=>'class=\"nodrag nodrop nohover\"',1=>'class=\"nodrag nodrop nohoverpair\"');\t\t// Used for tr to add new lines\n$bctag=array(0=>'class=\"impair tagtr\"',1=>'class=\"pair tagtr\"');", "// Define messages variables\n$mesg=''; $warning=''; $error=0;\n// deprecated, see setEventMessages() and dol_htmloutput_events()\n$mesgs=array(); $warnings=array(); $errors=array();", "// Constants used to defined number of lines in textarea\nif (empty($conf->browser->firefox))\n{\n\tdefine('ROWS_1',1);\n\tdefine('ROWS_2',2);\n\tdefine('ROWS_3',3);\n\tdefine('ROWS_4',4);\n\tdefine('ROWS_5',5);\n\tdefine('ROWS_6',6);\n\tdefine('ROWS_7',7);\n\tdefine('ROWS_8',8);\n\tdefine('ROWS_9',9);\n}\nelse\n{\n\tdefine('ROWS_1',0);\n\tdefine('ROWS_2',1);\n\tdefine('ROWS_3',2);\n\tdefine('ROWS_4',3);\n\tdefine('ROWS_5',4);\n\tdefine('ROWS_6',5);\n\tdefine('ROWS_7',6);\n\tdefine('ROWS_8',7);\n\tdefine('ROWS_9',8);\n}", "$heightforframes=48;", "// Init menu manager\nif (! defined('NOREQUIREMENU'))\n{\n\tif (empty($user->societe_id)) // If internal user or not defined\n\t{\n\t\t$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);\n\t}\n\telse // If external user\n\t{\n\t\t$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);\n\t}", "\t// Load the menu manager (only if not already done)\n\t$file_menu=$conf->standard_menu;\n\tif (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha'); // example: menu=eldy_menu.php\n\tif (! class_exists('MenuManager'))\n\t{\n\t\t$menufound=0;\n\t\t$dirmenus=array_merge(array(\"/core/menus/\"),(array) $conf->modules_parts['menus']);\n\t\tforeach($dirmenus as $dirmenu)\n\t\t{\n\t\t\t$menufound=dol_include_once($dirmenu.\"standard/\".$file_menu);\n\t\t\tif (class_exists('MenuManager')) break;\n\t\t}\n\t\tif (! class_exists('MenuManager'))\t// If failed to include, we try with standard eldy_menu.php\n\t\t{\n\t\t\tdol_syslog(\"You define a menu manager '\".$file_menu.\"' that can not be loaded.\", LOG_WARNING);\n\t\t\t$file_menu='eldy_menu.php';\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.\"/core/menus/standard/\".$file_menu;\n\t\t}\n\t}\n\t$menumanager = new MenuManager($db, empty($user->societe_id)?0:1);\n\t$menumanager->loadMenu();\n}", "", "// Functions", "if (! function_exists(\"llxHeader\"))\n{\n\t/**\n\t *\tShow HTML header HTML + BODY + Top menu + left menu + DIV\n\t *\n\t * @param \tstring \t$head\t\t\t\tOptionnal head lines\n\t * @param \tstring \t$title\t\t\t\tHTML title\n\t * @param\tstring\t$help_url\t\t\tUrl links to help page\n\t * \t\t \tSyntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage\n\t * \tFor other external page: http://server/url\n\t * @param\tstring\t$target\t\t\t\tTarget to use on links\n\t * @param \tint \t$disablejs\t\t\tMore content into html header\n\t * @param \tint \t$disablehead\t\tMore content into html header\n\t * @param \tarray \t$arrayofjs\t\t\tArray of complementary js files\n\t * @param \tarray \t$arrayofcss\t\t\tArray of complementary css files\n\t * @param\tstring\t$morequerystring\tQuery string to add to the link \"print\" to get same parameters (use only if autodetect fails)\n\t * @param string $morecssonbody More CSS on body tag.\n\t * @param\tstring\t$replacemainareaby\tReplace call to main_area() by a print of this string\n\t * @return\tvoid\n\t */\n\tfunction llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')\n\t{\n\t\tglobal $conf;", "\t\t// html header\n\t\ttop_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);", "\t\tprint '<body id=\"mainbody\"'.($morecssonbody?' class=\"'.$morecssonbody.'\"':'').'>' . \"\\n\";", "\t\t// top menu and left menu area\n\t\tif (empty($conf->dol_hide_topmenu))\n\t\t{\n\t\t\ttop_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);\n\t\t}", "\t\tif (empty($conf->dol_hide_leftmenu))\n\t\t{\n\t\t\tleft_menu('', $help_url, '', '', 1, $title, 1);\n\t\t}", "\t\t// main area\n\t\tif ($replacemainareaby)\n\t\t{\n\t\t\tprint $replacemainareaby;\n\t\t\treturn;\n\t\t}\n\t\tmain_area($title);\n\t}\n}", "\n/**\n * Show HTTP header\n *\n * @param string $contenttype Content type. For example, 'text/html'\n * @param\tint\t\t$forcenocache\tForce disabling of cache for the page\n * @return\tvoid\n */\nfunction top_httphead($contenttype='text/html', $forcenocache=0)\n{\n\tglobal $conf;", "\tif ($contenttype == 'text/html' ) header(\"Content-Type: text/html; charset=\".$conf->file->character_set_client);\n\telse header(\"Content-Type: \".$contenttype);\n\t// Security options\n\theader(\"X-Content-Type-Options: nosniff\"); // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)\n\theader(\"X-Frame-Options: SAMEORIGIN\"); // Frames allowed only if on same domain (stop some XSS attacks)\n\tif (! empty($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))\n\t{\n\t\t// For example, to restrict script, object, frames or img to some domains\n\t\t// script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; child-src https://youtube.com; img-src: https://static.example.com\n\t\t// For example, to restrict everything to one domain, except object, ...\n\t\t// default-src https://cdn.example.net; object-src 'none'\n\t\theader(\"Content-Security-Policy: \".$conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY);\n\t}\n\tif ($forcenocache)\n\t{\n\t\theader(\"Cache-Control: no-cache, no-store, must-revalidate, max-age=0\");\n\t}\n}", "/**\n * Ouput html header of a page.\n * This code is also duplicated into security2.lib.php::dol_loginfunction\n *\n * @param \tstring \t$head\t\t\t Optionnal head lines\n * @param \tstring \t$title\t\t\t HTML title\n * @param \tint \t$disablejs\t\t Disable js output\n * @param \tint \t$disablehead\t Disable head output\n * @param \tarray \t$arrayofjs\t\t Array of complementary js files\n * @param \tarray \t$arrayofcss\t\t Array of complementary css files\n * @param \tint \t$disablejmobile\t Disable jmobile (No more used)\n * @param int $disablenofollow Disable no follow tag\n * @return\tvoid\n */\nfunction top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)\n{\n\tglobal $user, $conf, $langs, $db;", "\ttop_httphead();", "\tif (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';\t// If not defined, eldy by default", "\tif (! empty($conf->global->MAIN_ACTIVATE_HTML4)) {\n\t\t$doctype = '<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">';\n\t}else {\n\t\t$doctype = '<!doctype html>';\n\t}\n\tprint $doctype.\"\\n\";\n\tif (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang=\"'.substr($langs->defaultlang,0,2).'\" manifest=\"'.DOL_URL_ROOT.'/cache.manifest\">'.\"\\n\";\n\telse print '<html lang=\"'.substr($langs->defaultlang,0,2).'\">'.\"\\n\";\n\t//print '<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\">'.\"\\n\";\n\tif (empty($disablehead))\n\t{\n\t\t$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);", "\t\tprint \"<head>\\n\";\n\t\tif (GETPOST('dol_basehref','alpha')) print '<base href=\"'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'\">'.\"\\n\";\n\t\t// Displays meta\n\t\tprint '<meta name=\"robots\" content=\"noindex'.($disablenofollow?'':',nofollow').'\">'.\"\\n\";\t// Do not index\n\t\tprint '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">'.\"\\n\";\t\t// Scale for mobile device\n\t\tprint '<meta name=\"author\" content=\"Dolibarr Development Team\">'.\"\\n\";\n\t\t// Favicon\n\t\t$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);\n\t\tif (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;\n\t\tif (empty($conf->dol_use_jmobile)) print '<link rel=\"shortcut icon\" type=\"image/x-icon\" href=\"'.$favicon.'\"/>'.\"\\n\";\t// Not required into an Android webview\n\t\t//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel=\"top\" title=\"'.$langs->trans(\"Home\").'\" href=\"'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'\">'.\"\\n\";\n\t\t//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel=\"copyright\" title=\"GNU General Public License\" href=\"http://www.gnu.org/copyleft/gpl.html#SEC1\">'.\"\\n\";\n\t\t//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel=\"author\" title=\"Dolibarr Development Team\" href=\"https://www.dolibarr.org\">'.\"\\n\";", "\t\t// Displays title\n\t\t$appli=constant('DOL_APPLICATION_TITLE');\n\t\tif (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;", "\t\tif ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) print '<title>'.dol_htmlentities($title).'</title>';\n\t\telse if ($title) print '<title>'.dol_htmlentities($appli.' - '.$title).'</title>';\n\t\telse print \"<title>\".dol_htmlentities($appli).\"</title>\";\n\t\tprint \"\\n\";", "\t\tif (GETPOST('version','int')) $ext='version='.GETPOST('version','int');\t// usefull to force no cache on css/js\n\t\tif (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);", "\t\t$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;\n\t\t$themeparam.=($ext?'&amp;'.$ext:'');\n\t\tif (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];\n\t\tif (GETPOST('dol_hide_topmenu','int')) { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }\n\t\tif (GETPOST('dol_hide_leftmenu','int')) { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }\n\t\tif (GETPOST('dol_optimize_smallscreen','int')) { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }\n\t\tif (GETPOST('dol_no_mouse_hover','int')) { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }\n\t\tif (GETPOST('dol_use_jmobile','int')) { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }", "\t\tif (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)\n\t\t{\n\t\t\tprint '<!-- Includes CSS for JQuery (Ajax library) -->'.\"\\n\";\n\t\t\t$jquerytheme = 'base';\n\t\t\tif (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;\n\t\t\tif (constant('JS_JQUERY_UI')) print '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'\">'.\"\\n\"; // JQuery\n\t\t\telse print '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'\">'.\"\\n\"; // JQuery\n\t\t\tif (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'\">'.\"\\n\"; // JNotify\n\t\t\tif (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) // jQuery plugin \"mutiselect\", \"multiple-select\", \"select2\"...\n\t\t\t{\n\t\t\t\t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;\n\t\t\t\tprint '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'\">'.\"\\n\";\n\t\t\t}\n\t\t}", "\t\tif (! defined('DISABLE_FONT_AWSOME'))\n\t\t{\n\t\t\tprint '<!-- Includes CSS for font awesome -->'.\"\\n\";\n\t\t\tprint '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'\">'.\"\\n\";\n\t\t}", "\t\tprint '<!-- Includes CSS for Dolibarr theme -->'.\"\\n\";\n\t\t// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'\n\t\t$themepath=dol_buildpath($conf->css,1);\n\t\t$themesubdir='';\n\t\tif (! empty($conf->modules_parts['theme']))\t// This slow down\n\t\t{\n\t\t\tforeach($conf->modules_parts['theme'] as $reldir)\n\t\t\t{\n\t\t\t\tif (file_exists(dol_buildpath($reldir.$conf->css, 0)))\n\t\t\t\t{\n\t\t\t\t\t$themepath=dol_buildpath($reldir.$conf->css, 1);\n\t\t\t\t\t$themesubdir=$reldir;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;\n\t\tprint '<link rel=\"stylesheet\" type=\"text/css\" href=\"'.$themepath.$themeparam.'\">'.\"\\n\";\n\t\tif (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'.\"\\n\".'<link rel=\"stylesheet\" type=\"text/css\" href=\"filethatdoesnotexiststosolvechromeflashbug\">'.\"\\n\";", "\t\t// CSS forced by modules (relative url starting with /)\n\t\tif (! empty($conf->modules_parts['css']))\n\t\t{\n\t\t\t$arraycss=(array) $conf->modules_parts['css'];\n\t\t\tforeach($arraycss as $modcss => $filescss)\n\t\t\t{\n\t\t\t\t$filescss=(array) $filescss;\t// To be sure filecss is an array\n\t\t\t\tforeach($filescss as $cssfile)\n\t\t\t\t{\n\t\t\t\t\tif (empty($cssfile)) dol_syslog(\"Warning: module \".$modcss.\" declared a css path file into its descriptor that is empty.\", LOG_WARNING);\n\t\t\t\t\t// cssfile is a relative path\n\t\t\t\t\tprint '<!-- Includes CSS added by module '.$modcss. ' -->'.\"\\n\".'<link rel=\"stylesheet\" type=\"text/css\" href=\"'.dol_buildpath($cssfile,1);\n\t\t\t\t\t// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.\n\t\t\t\t\tif (!preg_match('/\\.css$/i',$cssfile)) print $themeparam;\n\t\t\t\t\tprint '\">'.\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// CSS forced by page in top_htmlhead call (relative url starting with /)\n\t\tif (is_array($arrayofcss))\n\t\t{\n\t\t\tforeach($arrayofcss as $cssfile)\n\t\t\t{\n\t\t\t\tprint '<!-- Includes CSS added by page -->'.\"\\n\".'<link rel=\"stylesheet\" type=\"text/css\" title=\"default\" href=\"'.dol_buildpath($cssfile,1);\n\t\t\t\t// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.\n\t\t\t\tif (!preg_match('/\\.css$/i',$cssfile)) print $themeparam;\n\t\t\t\tprint '\">'.\"\\n\";\n\t\t\t}\n\t\t}", "\t\t// Output standard javascript links\n\t\tif (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\t// JQuery. Must be before other includes\n\t\t\tprint '<!-- Includes JS for JQuery -->'.\"\\n\";\n\t\t\tif (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type=\"text/javascript\" src=\"'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\telse print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\tif (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))\n\t\t\t{\n\t\t\t\tif (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type=\"text/javascript\" src=\"'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\telse print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t}\n\t\t\tif (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type=\"text/javascript\" src=\"'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\telse print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\tif (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t// jQuery jnotify\n\t\t\tif (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))\n\t\t\t{\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t}\n\t\t\t// Flot\n\t\t\tif (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))\n\t\t\t{\n\t\t\t\tif (constant('JS_JQUERY_FLOT'))\n\t\t\t\t{\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t// jQuery jeditable\n\t\t\tif (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))\n\t\t\t{\n\t\t\t\tprint '<!-- JS to manage editInPlace feature -->'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\">'.\"\\n\";\n\t\t\t\tprint 'var urlSaveInPlace = \\''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\\';'.\"\\n\";\n\t\t\t\tprint 'var urlLoadInPlace = \\''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\\';'.\"\\n\";\n\t\t\t\tprint 'var tooltipInPlace = \\''.$langs->transnoentities('ClickToEdit').'\\';'.\"\\n\";\t// Added in title attribute of span\n\t\t\t\tprint 'var placeholderInPlace = \\'&nbsp;\\';'.\"\\n\";\t// If we put another string than $langs->trans(\"ClickToEdit\") here, nothing is shown. If we put empty string, there is error, Why ?\n\t\t\t\tprint 'var cancelInPlace = \\''.$langs->trans('Cancel').'\\';'.\"\\n\";\n\t\t\t\tprint 'var submitInPlace = \\''.$langs->trans('Ok').'\\';'.\"\\n\";\n\t\t\t\tprint 'var indicatorInPlace = \\'<img src=\"'.DOL_URL_ROOT.\"/theme/\".$conf->theme.\"/img/working.gif\".'\">\\';'.\"\\n\";\n\t\t\t\tprint 'var withInPlace = 300;';\t\t// width in pixel for default string edit\n\t\t\t\tprint '</script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n\t\t\t}\n // jQuery Timepicker\n if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))\n {\n \tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n \tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'\"></script>'.\"\\n\";\n }\n if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) // jQuery plugin \"mutiselect\", \"multiple-select\", \"select2\", ...\n {\n \t$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;\n \tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\t// We include full because we need the support of containerCssClass\n }\n }", " if (! $disablejs && ! empty($conf->use_javascript_ajax))\n {\n // CKEditor\n if (! empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && ! defined('DISABLE_CKEDITOR'))\n {\n print '<!-- Includes JS for CKEditor -->'.\"\\n\";\n $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';\n $jsckeditor='ckeditor.js';\n if (constant('JS_CKEDITOR'))\t// To use external ckeditor 4 js lib\n {\n \t$pathckeditor=constant('JS_CKEDITOR');\n }\n print '<script type=\"text/javascript\">';\n print 'var CKEDITOR_BASEPATH = \\''.$pathckeditor.'\\';'.\"\\n\";\n print 'var ckeditorConfig = \\''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\\';'.\"\\n\";\t\t// $themesubdir='' in standard usage\n print 'var ckeditorFilebrowserBrowseUrl = \\''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\\';'.\"\\n\";\n print 'var ckeditorFilebrowserImageBrowseUrl = \\''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\\';'.\"\\n\";\n print '</script>'.\"\\n\";\n print '<script type=\"text/javascript\" src=\"'.$pathckeditor.$jsckeditor.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n }", " // Browser notifications\n if (! defined('DISABLE_BROWSER_NOTIF'))\n {\n $enablebrowsernotif=false;\n if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;\n if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;\n if ($enablebrowsernotif)\n {\n print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'.\"\\n\";\n print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext?'?'.$ext:'').'\"></script>'.\"\\n\";\n }\n }", " // Global js function\n print '<!-- Includes JS of Dolibarr -->'.\"\\n\";\n print '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'\"></script>'.\"\\n\";", " // JS forced by modules (relative url starting with /)\n if (! empty($conf->modules_parts['js']))\t\t// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))\n \t{\n \t\t$arrayjs=(array) $conf->modules_parts['js'];\n\t foreach($arrayjs as $modjs => $filesjs)\n\t {\n \t\t\t$filesjs=(array) $filesjs;\t// To be sure filejs is an array\n\t\t foreach($filesjs as $jsfile)\n\t\t {\n\t \t \t\t// jsfile is a relative path\n\t \t \tprint '<!-- Include JS added by module '.$modjs. '-->'.\"\\n\".'<script type=\"text/javascript\" src=\"'.dol_buildpath($jsfile,1).'\"></script>'.\"\\n\";\n\t\t }\n\t }\n \t}\n // JS forced by page in top_htmlhead (relative url starting with /)\n if (is_array($arrayofjs))\n {\n print '<!-- Includes JS added by page -->'.\"\\n\";\n foreach($arrayofjs as $jsfile)\n {\n if (preg_match('/^http/i',$jsfile))\n {\n print '<script type=\"text/javascript\" src=\"'.$jsfile.'\"></script>'.\"\\n\";\n }\n else\n {\n if (! preg_match('/^\\//',$jsfile)) $jsfile='/'.$jsfile;\t// For backward compatibility\n print '<script type=\"text/javascript\" src=\"'.dol_buildpath($jsfile,1).'\"></script>'.\"\\n\";\n }\n }\n }\n }", " if (! empty($head)) print $head.\"\\n\";\n if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER.\"\\n\";", " print \"</head>\\n\\n\";\n }", " $conf->headerdone=1;\t// To tell header was output\n}", "\n/**\n * Show an HTML header + a BODY + The top menu bar\n *\n * @param string\t$head \t\t\tLines in the HEAD\n * @param string\t$title \t\t\tTitle of web page\n * @param string\t$target \t\t\tTarget to use in menu links (Example: '' or '_top')\n *\t@param\t\tint\t\t$disablejs\t\t\tDo not output links to js (Ex: qd fonction utilisee par sous formulaire Ajax)\n *\t@param\t\tint\t\t$disablehead\t\tDo not output head section\n *\t@param\t\tarray\t$arrayofjs\t\t\tArray of js files to add in header\n *\t@param\t\tarray\t$arrayofcss\t\t\tArray of css files to add in header\n * @param\t\tstring\t$morequerystring\tQuery string to add to the link \"print\" to get same parameters (use only if autodetect fails)\n * @param string\t$helppagename \tName of wiki page for help ('' by default).\n * \t\t\t\t \t\t Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage\n * \t\t\t\t\t\t\t\t\t For other external page: http://server/url\n * @return\t\tvoid\n */\nfunction top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')\n{\n\tglobal $user, $conf, $langs, $db;\n\tglobal $dolibarr_main_authentication, $dolibarr_main_demo;\n\tglobal $hookmanager,$menumanager;", "\t$searchform='';\n\t$bookmarks='';", "\t// Instantiate hooks of thirdparty module\n\t$hookmanager->initHooks(array('toprightmenu'));", "\t$toprightmenu='';", "\t// For backward compatibility with old modules\n\tif (empty($conf->headerdone))\n\t{\n\t\ttop_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);\n\t\tprint '<body id=\"mainbody\">';\n\t}", "\t/*\n * Top menu\n */\n\tif (empty($conf->dol_hide_topmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))\n\t{\n\t\tprint \"\\n\".'<!-- Start top horizontal -->'.\"\\n\";", "\t\tprint '<div class=\"side-nav-vert\"><div id=\"id-top\">';", "\t\t// Show menu entries\n\t\tprint '<div id=\"tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'\" class=\"tmenu\">'.\"\\n\";\n\t\t$menumanager->atarget=$target;\n\t\t$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \\n\n\t\tprint \"</div>\\n\";", "\t\t// Define link to login card\n\t\t$appli=constant('DOL_APPLICATION_TITLE');\n\t\tif (! empty($conf->global->MAIN_APPLICATION_TITLE))\n\t\t{\n\t\t\t$appli=$conf->global->MAIN_APPLICATION_TITLE;\n\t\t\tif (preg_match('/\\d\\.\\d/', $appli))\n\t\t\t{\n\t\t\t\tif (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=\" (\".DOL_VERSION.\")\";\t// If new title contains a version that is different than core\n\t\t\t}\n\t\t\telse $appli.=\" \".DOL_VERSION;\n\t\t}\n\t\telse $appli.=\" \".DOL_VERSION;", "\t\tif (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.=\"<br>\".$langs->trans(\"LevelOfFeature\").': '.$conf->global->MAIN_FEATURES_LEVEL;", "\t\t$logouttext='';\n\t\tif (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))\n\t\t{\n\t\t\t//$logouthtmltext=$appli.'<br>';\n\t\t\tif ($_SESSION[\"dol_authmode\"] != 'forceuser' && $_SESSION[\"dol_authmode\"] != 'http')\n\t\t\t{\n\t\t\t\t$logouthtmltext.=$langs->trans(\"Logout\").'<br>';", "\t\t\t\t$logouttext .='<a href=\"'.DOL_URL_ROOT.'/user/logout.php\">';\n\t\t\t\t//$logouttext .= img_picto($langs->trans('Logout').\":\".$langs->trans('Logout'), 'logout_top.png', 'class=\"login\"', 0, 0, 1);\n\t\t\t\t$logouttext .='<span class=\"fa fa-sign-out atoplogin\"></span>';\n\t\t\t\t$logouttext .='</a>';\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t$logouthtmltext.=$langs->trans(\"NoLogoutProcessWithAuthMode\",$_SESSION[\"dol_authmode\"]);\n\t\t\t\t$logouttext .= img_picto($langs->trans('Logout').\":\".$langs->trans('Logout'), 'logout_top.png', 'class=\"login\"', 0, 0, 1);\n\t\t\t}\n\t\t}", "\t\tprint '<div class=\"login_block\">'.\"\\n\";", "\t\t// Add login user link\n\t\t$toprightmenu.='<div class=\"login_block_user\">';", "\t\t// Login name with photo and tooltip\n\t\t$mode=-1;\n\t\t$toprightmenu.='<div class=\"inline-block nowrap\"><div class=\"inline-block login_block_elem login_block_elem_name\" style=\"padding: 0px;\">';\n\t\t$toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');\n\t\t$toprightmenu.='</div></div>';", "\t\t$toprightmenu.='</div>'.\"\\n\";", "\t\t$toprightmenu.='<div class=\"login_block_other\">';", "\t\t// Execute hook printTopRightMenu (hooks should output string like '<div class=\"login\"><a href=\"\">mylink</a></div>')\n\t\t$parameters=array();\n\t\t$result=$hookmanager->executeHooks('printTopRightMenu',$parameters); // Note that $action and $object may have been modified by some hooks\n\t\tif (is_numeric($result))\n\t\t{\n\t\t\tif (empty($result)) $toprightmenu.=$hookmanager->resPrint;\t\t// add\n\t\t\telse $toprightmenu=$hookmanager->resPrint;\t\t\t\t\t\t// replace\n\t\t}\n\t\telse $toprightmenu.=$result;\t// For backward compatibility", "\t\t// Link to module builder\n\t\tif (! empty($conf->modulebuilder->enabled))\n\t\t{\n\t\t\t$text ='<a href=\"'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools\" target=\"_modulebuilder\">';\n\t\t\t//$text.= img_picto(\":\".$langs->trans(\"ModuleBuilder\"), 'printer_top.png', 'class=\"printer\"');\n\t\t\t$text.='<span class=\"fa fa-bug atoplogin\"></span>';\n\t\t\t$text.='</a>';\n\t\t\t$toprightmenu.=@Form::textwithtooltip('',$langs->trans(\"ModuleBuilder\"),2,1,$text,'login_block_elem',2);\n\t\t}", "\t\t// Link to print main content area\n\t\tif (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && empty($conf->browser->phone))\n\t\t{\n\t\t\t$qs=dol_escape_htmltag($_SERVER[\"QUERY_STRING\"]);", "\t\t\tif (is_array($_POST))\n\t\t\t{\n\t\t\t\tforeach($_POST as $key=>$value) {\n\t\t\t\t\tif ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);\n\t\t\t\t}\n\t\t\t}\n\t\t\t$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;\n\t\t\t$text ='<a href=\"'.dol_escape_htmltag($_SERVER[\"PHP_SELF\"]).'?'.$qs.($qs?'&':'').'optioncss=print\" target=\"_blank\">';\n\t\t\t//$text.= img_picto(\":\".$langs->trans(\"PrintContentArea\"), 'printer_top.png', 'class=\"printer\"');\n\t\t\t$text.='<span class=\"fa fa-print atoplogin\"></span>';\n\t\t\t$text.='</a>';\n\t\t\t$toprightmenu.=@Form::textwithtooltip('',$langs->trans(\"PrintContentArea\"),2,1,$text,'login_block_elem',2);\n\t\t}", "\t\t// Link to Dolibarr wiki pages\n\t\tif (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))\n\t\t{\n\t\t\t$langs->load(\"help\");", "\t\t\t$helpbaseurl='';\n\t\t\t$helppage='';\n\t\t\t$mode='';", "\t\t\tif (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:DocumentaciΓ³n_usuarios';", "\t\t\t// Get helpbaseurl, helppage and mode from helppagename and langs\n\t\t\t$arrayres=getHelpParamFor($helppagename,$langs);\n\t\t\t$helpbaseurl=$arrayres['helpbaseurl'];\n\t\t\t$helppage=$arrayres['helppage'];\n\t\t\t$mode=$arrayres['mode'];", "\t\t\t// Link to help pages\n\t\t\tif ($helpbaseurl && $helppage)\n\t\t\t{\n\t\t\t\t$text='';\n\t\t\t\t$title=$appli.'<br>';\n\t\t\t\t$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');\n\t\t\t\tif ($mode == 'wiki') $title.=' - '.$langs->trans(\"PageWiki\").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';\n\t\t\t\t$text.='<a class=\"help\" target=\"_blank\" rel=\"noopener\" href=\"';\n\t\t\t\tif ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));\n\t\t\t\telse $text.=sprintf($helpbaseurl,$helppage);\n\t\t\t\t$text.='\">';\n\t\t\t\t//$text.=img_picto('', 'helpdoc_top').' ';\n\t\t\t\t$text.='<span class=\"fa fa-question-circle atoplogin\"></span>';\n\t\t\t\t//$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');\n\t\t\t\t//if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';\n\t\t\t\t$text.='</a>';\n\t\t\t\t//$toprightmenu.='</div>'.\"\\n\";\n\t\t\t\t$toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);\n\t\t\t}\n\t\t}", "\t\t// Logout link\n\t\t$toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);", "\t\t$toprightmenu.='</div>';", "\t\tprint $toprightmenu;", "\t\tprint \"</div>\\n\";\n\t\tprint '</div></div>';\n", "", "\t\tprint '<div style=\"clear: both;\"></div>';\n\t\tprint \"<!-- End top horizontal menu -->\\n\\n\";\n\t}", "\tif (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id=\"id-container\" class=\"id-container'.($morecss?' '.$morecss:'').'\">';\n}", "\n/**\n * Show left menu bar\n *\n * @param array\t$menu_array_before \t \tTable of menu entries to show before entries of menu handler. This param is deprectaed and must be provided to ''.\n * @param string\t$helppagename \t \tName of wiki page for help ('' by default).\n * \t\t\t\t \t\t \tSyntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage\n * \t\t\t\t\t\t\t\t\t \t\t For other external page: http://server/url\n * @param string\t$notused \t\tDeprecated. Used in past to add content into left menu. Hooks can be used now.\n * @param array\t$menu_array_after Table of menu entries to show after entries of menu handler\n * @param int\t\t$leftmenuwithoutmainarea Must be set to 1. 0 by default for backward compatibility with old modules.\n * @param string\t$title Title of web page\n * @param string $acceptdelayedhtml 1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)\n * @return\tvoid\n */\nfunction left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)\n{\n\tglobal $user, $conf, $langs, $db, $form;\n\tglobal $hookmanager, $menumanager;", "\t$searchform='';\n\t$bookmarks='';", "\tif (! empty($menu_array_before)) dol_syslog(\"Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.\", LOG_WARNING);", "\tif (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))\n\t{\n\t\t// Instantiate hooks of thirdparty module\n\t\t$hookmanager->initHooks(array('searchform','leftblock'));", "\t\tprint \"\\n\".'<!-- Begin side-nav id-left -->'.\"\\n\".'<div class=\"side-nav\"><div id=\"id-left\">'.\"\\n\";", "\t\tif ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;\t// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?", "\t\tprint \"\\n\";\n\t\tif ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))\n\t\t{\n\t\t\tif (! is_object($form)) $form=new Form($db);\n\t\t\t$selected=-1;\n\t\t\t$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans(\"Search\"), 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (! is_object($form)) $form=new Form($db);\n\t\t\t$selected=-1;\n\t\t\t$usedbyinclude=1;\n\t\t\tinclude_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';", "\t\t\tforeach($arrayresult as $key => $val)\n\t\t\t{\n\t\t\t\t//$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));\n\t\t\t\t$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));\n\t\t\t}\n\t\t}", "\t\t// Execute hook printSearchForm\n\t\t$parameters=array('searchform'=>$searchform);\n\t\t$reshook=$hookmanager->executeHooks('printSearchForm',$parameters); // Note that $action and $object may have been modified by some hooks\n\t\tif (empty($reshook))\n\t\t{\n\t\t\t$searchform.=$hookmanager->resPrint;\n\t\t}\n\t\telse $searchform=$hookmanager->resPrint;", "\t\t// Force special value for $searchform\n\t\tif (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\t$urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';\n\t\t\t$searchform='<div class=\"blockvmenuimpair blockvmenusearchphone\"><div id=\"divsearchforms1\"><a href=\"'.$urltosearch.'\" alt=\"'.dol_escape_htmltag($langs->trans(\"ShowSearchFields\")).'\">'.$langs->trans(\"Search\").'...</a></div></div>';\n\t\t}\n\t\telseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))\n\t\t{\n\t\t\t$searchform='<div class=\"blockvmenuimpair blockvmenusearchphone\"><div id=\"divsearchforms1\"><a href=\"#\" alt=\"'.dol_escape_htmltag($langs->trans(\"ShowSearchFields\")).'\">'.$langs->trans(\"Search\").'...</a></div><div id=\"divsearchforms2\" style=\"display: none\">'.$searchform.'</div>';\n\t\t\t$searchform.='<script type=\"text/javascript\">\n \tjQuery(document).ready(function () {\n \t\tjQuery(\"#divsearchforms1\").click(function(){\n\t jQuery(\"#divsearchforms2\").toggle();\n\t });\n \t});\n </script>' . \"\\n\";\n\t\t\t$searchform.='</div>';\n\t\t}", "\t\t// Define $bookmarks\n\t\tif (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)\n\t\t{\n\t\t\tinclude_once (DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php');\n\t\t\t$langs->load(\"bookmarks\");", "\t\t\t$bookmarks=printBookmarksList($db, $langs);\n\t\t}", "\t\t// Left column\n\t\tprint '<!-- Begin left menu -->'.\"\\n\";", "\t\tprint '<div class=\"vmenu\"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title=\"Left menu\"').'>'.\"\\n\\n\";", "\t\t// Show left menu with other forms\n\t\t$menumanager->menu_array = $menu_array_before;\n\t\t$menumanager->menu_array_after = $menu_array_after;\n\t\t$menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database", "\t\t// Dolibarr version + help + bug report link\n\t\tprint \"\\n\";\n\t\tprint \"<!-- Begin Help Block-->\\n\";\n\t\tprint '<div id=\"blockvmenuhelp\" class=\"blockvmenuhelp\">'.\"\\n\";", "\t\t// Version\n\t\tif (empty($conf->global->MAIN_HIDE_VERSION)) // Version is already on help picto and on login page.\n\t\t{\n\t\t\t$doliurl='https://www.dolibarr.org';\n\t\t\t//local communities\n\t\t\tif (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';\n\t\t\tif (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';\n\t\t\tif (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';\n\t\t\tif (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';\n\t\t\tif (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';", "\t\t\t$appli=constant('DOL_APPLICATION_TITLE');\n\t\t\tif (! empty($conf->global->MAIN_APPLICATION_TITLE))\n\t\t\t{\n\t\t\t\t$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';\n\t\t\t\tif (preg_match('/\\d\\.\\d/', $appli))\n\t\t\t\t{\n\t\t\t\t\tif (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=\" (\".DOL_VERSION.\")\";\t// If new title contains a version that is different than core\n\t\t\t\t}\n\t\t\t\telse $appli.=\" \".DOL_VERSION;\n\t\t\t}\n\t\t\telse $appli.=\" \".DOL_VERSION;\n\t\t\tprint '<div id=\"blockvmenuhelpapp\" class=\"blockvmenuhelp\">';\n\t\t\tif ($doliurl) print '<a class=\"help\" target=\"_blank\" rel=\"noopener\" href=\"'.$doliurl.'\">';\n\t\t\telse print '<span class=\"help\">';\n\t\t\tprint $appli;\n\t\t\tif ($doliurl) print '</a>';\n\t\t\telse print '</span>';\n\t\t\tprint '</div>'.\"\\n\";\n\t\t}", "\t\t// Link to bugtrack\n\t\tif (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))\n\t\t{\n\t\t\trequire_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';", "\t\t\t$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';\n\t\t\t$bugbaseurl.= '?title=';\n\t\t\t$bugbaseurl.= urlencode(\"Bug: \");\n\t\t\t$bugbaseurl.= '&body=';\n\t\t\t// TODO use .github/ISSUE_TEMPLATE.md to generate?\n\t\t\t$bugbaseurl .= urlencode(\"# Bug\\n\");\n\t\t\t$bugbaseurl .= urlencode(\"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"## Environment\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **Version**: \" . DOL_VERSION . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **OS**: \" . php_uname('s') . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **Web server**: \" . $_SERVER[\"SERVER_SOFTWARE\"] . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **PHP**: \" . php_sapi_name() . ' ' . phpversion() . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **Database**: \" . $db::LABEL . ' ' . $db->getVersion() . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"- **URL**: \" . $_SERVER[\"REQUEST_URI\"] . \"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"\\n\");\n\t\t\t$bugbaseurl.= urlencode(\"## Report\\n\");\n\t\t\tprint '<div id=\"blockvmenuhelpbugreport\" class=\"blockvmenuhelp\">';\n\t\t\tprint '<a class=\"help\" target=\"_blank\" rel=\"noopener\" href=\"'.$bugbaseurl.'\">'.$langs->trans(\"FindBug\").'</a>';\n\t\t\tprint '</div>';\n\t\t}", "\t\tprint \"</div>\\n\";\n\t\tprint \"<!-- End Help Block-->\\n\";\n\t\tprint \"\\n\";", "\t\tprint \"</div>\\n\";\n\t\tprint \"<!-- End left menu -->\\n\";\n\t\tprint \"\\n\";", "\t\t// Execute hook printLeftBlock\n\t\t$parameters=array();\n\t\t$reshook=$hookmanager->executeHooks('printLeftBlock',$parameters); // Note that $action and $object may have been modified by some hooks\n\t\tprint $hookmanager->resPrint;", "\t\tprint '</div></div> <!-- End side-nav id-left -->';\t// End div id=\"side-nav\" div id=\"id-left\"\n\t}", "\tprint \"\\n\";\n\tprint '<!-- Begin right area -->'.\"\\n\";", "\tif (empty($leftmenuwithoutmainarea)) main_area($title);\n}", "\n/**\n * Begin main area\n *\n * @param\tstring\t$title\t\tTitle\n * @return\tvoid\n */\nfunction main_area($title='')\n{\n\tglobal $conf, $langs;", "\tif (empty($conf->dol_hide_leftmenu)) print '<div id=\"id-right\">';", "\tprint \"\\n\";", "\tprint '<!-- Begin div class=\"fiche\" -->'.\"\\n\".'<div class=\"fiche\">'.\"\\n\";", "\tif (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans(\"WarningYouAreInMaintenanceMode\",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));\n}", "\n/**\n * Return helpbaseurl, helppage and mode\n *\n * @param\tstring\t\t$helppagename\t\tPage name ('EN:xxx,ES:eee,FR:fff...' or 'http://localpage')\n * @param Translate\t$langs\t\t\t\tLanguage\n * @return\tarray\t\tArray of help urls\n */\nfunction getHelpParamFor($helppagename,$langs)\n{\n\t$helpbaseurl='';\n\t$helppage='';\n\t$mode='';", "\tif (preg_match('/^http/i',$helppagename))\n\t{\n\t\t// If complete URL\n\t\t$helpbaseurl='%s';\n\t\t$helppage=$helppagename;\n\t\t$mode='local';\n\t}\n\telse\n\t{\n\t\t// If WIKI URL\n\t\tif (preg_match('/^es/i',$langs->defaultlang))\n\t\t{\n\t\t\t$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';\n\t\t\tif (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];\n\t\t}\n\t\tif (preg_match('/^fr/i',$langs->defaultlang))\n\t\t{\n\t\t\t$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';\n\t\t\tif (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];\n\t\t}\n\t\tif (empty($helppage))\t// If help page not already found\n\t\t{\n\t\t\t$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';\n\t\t\tif (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];\n\t\t}\n\t\t$mode='wiki';\n\t}\n\treturn array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);\n}", "\n/**\n * Show a search area.\n * Used when the javascript quick search is not used.\n *\n * @param string\t$urlaction Url post\n * @param string\t$urlobject Url of the link under the search box\n * @param string\t$title Title search area\n * @param string\t$htmlmorecss Add more css\n * @param string\t$htmlinputname Field Name input form\n * @param\tstring\t$accesskey\t\t\tAccesskey\n * @param string $prefhtmlinputname Complement for id to avoid multiple same id in the page\n * @param\tstring\t$img\t\t\t\tImage to use\n * @param\tstring\t$showtitlebefore\tShow title before input text instead of into placeholder. This can be set when output is dedicated for text browsers.\n * @return\tstring\n */\nfunction printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='', $showtitlebefore=0)\n{\n\tglobal $conf,$langs,$user;", "\t$ret='';\n\t$ret.='<form action=\"'.$urlaction.'\" method=\"post\" class=\"searchform\">';\n\t$ret.='<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t$ret.='<input type=\"hidden\" name=\"mode\" value=\"search\">';\n\t$ret.='<input type=\"hidden\" name=\"savelogin\" value=\"'.dol_escape_htmltag($user->login).'\">';\n\tif ($showtitlebefore) $ret.=$title.' ';\n\t$ret.='<input type=\"text\" class=\"flat '.$htmlmorecss.'\"';\n\t$ret.=' style=\"text-indent: 22px; background-image: url(\\''.$img.'\\'); background-repeat: no-repeat; background-position: 3px;\"';\n\t$ret.=($accesskey?' accesskey=\"'.$accesskey.'\"':'');\n\t$ret.=' placeholder=\"'.strip_tags($title).'\"';\n\t$ret.=' name=\"'.$htmlinputname.'\" id=\"'.$prefhtmlinputname.$htmlinputname.'\" />';\n\t$ret.='<input type=\"submit\" class=\"button\" style=\"padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px\" value=\"'.$langs->trans(\"Go\").'\">';\n\t$ret.=\"</form>\\n\";\n\treturn $ret;\n}", "\nif (! function_exists(\"llxFooter\"))\n{\n\t/**\n\t * Show HTML footer\n\t * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.\n\t * If global var $delayedhtmlcontent was filled, we output it just before closing the body.\n\t *\n\t * @param\tstring\t$comment \t\t\t\tA text to add as HTML comment into HTML generated page\n\t * @param\tstring\t$zone\t\t\t\t\t\t'private' (for private pages) or 'public' (for public pages)\n\t * @param\tint\t\t$disabledoutputofmessages\tClear all messages stored into session without diplaying them\n\t * @return\tvoid\n\t */\n\tfunction llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)\n\t{\n\t\tglobal $conf, $langs, $user, $object;\n\t\tglobal $delayedhtmlcontent;", "\t\t$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);", "\t\t// Global html output events ($mesgs, $errors, $warnings)\n\t\tdol_htmloutput_events($disabledoutputofmessages);", "\t\t// Code for search criteria persistence.\n\t\t// Save $user->lastsearch_values if defined (define on list pages when a form field search_xxx exists)\n\t\tif (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))\n\t\t{\n\t\t\t// Clean data\n\t\t\tforeach($user->lastsearch_values_tmp as $key => $val)\n\t\t\t{\n\t\t\t\tunset($_SESSION['lastsearch_values_tmp_'.$key]);\t\t\t// Clean arry to rebuild it just after\n\t\t\t\tif (count($val) && empty($_POST['button_removefilter']))\t// If there is search criteria to save and we did not click on 'Clear filter' button\n\t\t\t\t{\n\t\t\t\t\tif (empty($val['sortfield'])) unset($val['sortfield']);\n\t\t\t\t\tif (empty($val['sortorder'])) unset($val['sortorder']);\n\t\t\t\t\tdol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0).\" (systematic recording of last search criteria)\");\n\t\t\t\t\t$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);\n\t\t\t\t\tunset($_SESSION['lastsearch_values_'.$key]);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "\t\t// Core error message\n\t\tif (! empty($conf->global->MAIN_CORE_ERROR))\n\t\t{\n\t\t\t// Ajax version\n\t\t\tif ($conf->use_javascript_ajax)\n\t\t\t{\n\t\t\t\t$title = img_warning().' '.$langs->trans('CoreErrorTitle');\n\t\t\t\tprint ajax_dialog($title, $langs->trans('CoreErrorMessage'));\n\t\t\t}\n\t\t\t// html version\n\t\t\telse\n\t\t\t{\n\t\t\t\t$msg = img_warning().' '.$langs->trans('CoreErrorMessage');\n\t\t\t\tprint '<div class=\"error\">'.$msg.'</div>';\n\t\t\t}", "\t\t\t//define(\"MAIN_CORE_ERROR\",0); // Constant was defined and we can't change value of a constant\n\t\t}", "\t\tprint \"\\n\\n\";", "\t\tprint '</div> <!-- End div class=\"fiche\" -->'.\"\\n\"; // End div fiche", "\t\tif (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'.\"\\n\"; // End div id-right", "\t\tif (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'.\"\\n\";\t// End div container", "\t\tprint \"\\n\";\n\t\tif ($comment) print '<!-- '.$comment.' -->'.\"\\n\";", "\t\tprintCommonFooter($zone);", "\t\tif (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;", "\t\tif (! empty($conf->use_javascript_ajax))\n\t\t{\n\t\t\tprint \"\\n\".'<!-- Includes JS Footer of Dolibarr -->'.\"\\n\";\n\t\t\tprint '<script type=\"text/javascript\" src=\"'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'\"></script>'.\"\\n\";\n\t\t}", "\t\t// Wrapper to add log when clicking on download or preview\n\t\tif (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)\n\t\t{\n\t\t\tif (in_array($object->element, array('facture'))) // Restrict for the moment to element 'facture'\n\t\t\t{\n\t\t\t\tprint \"\\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\\n\";\n\t\t\t\t?>\n \t\t\t<script type=\"text/javascript\">\n \t\t\tjQuery(document).ready(function () {\n \t\t\t\t$('a.documentpreview').click(function() {\n \t\t\t\t\t$.post('<?php echo DOL_URL_ROOT.\"/blockedlog/ajax/block-add.php\" ?>'\n \t\t\t\t\t\t\t, {\n \t\t\t\t\t\t\t\tid:<?php echo $object->id; ?>\n \t\t\t\t\t\t\t\t, element:'<?php echo $object->element ?>'\n \t\t\t\t\t\t\t\t, action:'DOC_PREVIEW'\n \t\t\t\t\t\t\t}\n \t\t\t\t\t);\n \t\t\t\t});\n \t\t\t\t$('a.documentdownload').click(function() {\n \t\t\t\t\t$.post('<?php echo DOL_URL_ROOT.\"/blockedlog/ajax/block-add.php\" ?>'\n \t\t\t\t\t\t\t, {\n \t\t\t\t\t\t\t\tid:<?php echo $object->id; ?>\n \t\t\t\t\t\t\t\t, element:'<?php echo $object->element ?>'\n \t\t\t\t\t\t\t\t, action:'DOC_DOWNLOAD'\n \t\t\t\t\t\t\t}\n \t\t\t\t\t);\n \t\t\t\t});\n \t\t\t});\n \t\t\t</script>\n\t\t\t\t<?php\n\t\t\t}\n\t \t}", "\t\t// A div for the address popup\n\t\tprint \"\\n<!-- A div to allow dialog popup -->\\n\";\n\t\tprint '<div id=\"dialogforpopup\" style=\"display: none;\"></div>'.\"\\n\";", "\t\tprint \"</body>\\n\";\n\t\tprint \"</html>\\n\";\n\t}\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (C) 2001-2007\tRodolphe Quiedeville\t<rodolphe@quiedeville.org>\n * Copyright (C) 2004-2016\tLaurent Destailleur\t\t<eldy@users.sourceforge.net>\n * Copyright (C) 2005\t\tEric Seigne\t\t\t\t<eric.seigne@ryxeo.com>\n * Copyright (C) 2005-2015\tRegis Houssin\t\t\t<regis.houssin@capnetworks.com>\n * Copyright (C) 2006\t\tAndre Cianfarani\t\t<acianfa@free.fr>\n * Copyright (C) 2006\t\tAuguria SARL\t\t\t<info@auguria.org>\n * Copyright (C) 2010-2015\tJuanjo Menent\t\t\t<jmenent@2byte.es>\n * Copyright (C) 2013-2016\tMarcos GarcΓ­a\t\t\t<marcosgdf@gmail.com>\n * Copyright (C) 2012-2013\tCΓ©dric Salvador\t\t\t<csalvador@gpcsolutions.fr>\n * Copyright (C) 2011-2017\tAlexandre Spangaro\t\t<aspangaro@zendsi.com>\n * Copyright (C) 2014\t\tCΓ©dric Gross\t\t\t<c.gross@kreiz-it.fr>\n * Copyright (C) 2014-2015\tFerran Marcet\t\t\t<fmarcet@2byte.es>\n * Copyright (C) 2015\t\tJean-FranΓ§ois Ferry\t\t<jfefe@aternatik.fr>\n * Copyright (C) 2015\t\tRaphaΓ«l Doursenaud\t\t<rdoursenaud@gpcsolutions.fr>\n * Copyright (C) 2016\t\tCharlie Benke\t\t\t<charlie@patas-monkey.com>\n * Copyright (C) 2016\t\tMeziane Sof\t\t\t\t<virtualsof@yahoo.fr>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n * \\file htdocs/product/card.php\n * \\ingroup product\n * \\brief Page to show product\n */", "require '../main.inc.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';\nrequire_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.php';", "if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';\nif (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';\nif (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';\nif (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';\nif (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';\nif (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';", "$langs->load(\"products\");\n$langs->load(\"other\");\nif (! empty($conf->stock->enabled)) $langs->load(\"stocks\");\nif (! empty($conf->facture->enabled)) $langs->load(\"bills\");\nif (! empty($conf->productbatch->enabled)) $langs->load(\"productbatch\");", "$mesg=''; $error=0; $errors=array();", "$refalreadyexists=0;", "$id=GETPOST('id', 'int');\n$ref=GETPOST('ref', 'alpha');\n$type=GETPOST('type','int');\n$action=(GETPOST('action','alpha') ? GETPOST('action','alpha') : 'view');\n$cancel=GETPOST('cancel','alpha');\n$confirm=GETPOST('confirm','alpha');\n$socid=GETPOST('socid','int');\n$duration_value = GETPOST('duration_value');\n$duration_unit = GETPOST('duration_unit');\nif (! empty($user->societe_id)) $socid=$user->societe_id;", "$object = new Product($db);\n$object->type = $type;\t// so test later to fill $usercancxxx is correct\n$extrafields = new ExtraFields($db);", "// fetch optionals attributes and labels\n$extralabels=$extrafields->fetch_name_optionals_label($object->table_element);", "if ($id > 0 || ! empty($ref))\n{\n $result = $object->fetch($id, $ref);", " if (! empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref);\n elseif (! empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref);", " if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs\n {\n if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr(\"000\".$object->id, -2),1,1).'/'.substr(substr(\"000\".$object->id, -2),0,1).'/'.$object->id.\"/photos\";\n else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr(\"000\".$object->id, -2),1,1).'/'.substr(substr(\"000\".$object->id, -2),0,1).'/'.$object->id.\"/photos\";\n }\n}", "$modulepart='product';", "// Get object canvas (By default, this is not defined, so standard usage of dolibarr)\n$canvas = !empty($object->canvas)?$object->canvas:GETPOST(\"canvas\");\n$objcanvas=null;\nif (! empty($canvas))\n{\n require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';\n $objcanvas = new Canvas($db,$action);\n $objcanvas->getCanvas('product','card',$canvas);\n}", "// Security check\n$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : ''));\n$fieldtype = (! empty($id) ? 'rowid' : 'ref');\n$result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype,$objcanvas);", "// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context\n$hookmanager->initHooks(array('productcard','globalcard'));", "", "/*\n * Actions\n */", "if ($cancel) $action = '';", "$usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire));\n$usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer));\n$usercandelete = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer));\n$createbarcode=empty($conf->barcode->enabled)?0:1;\nif (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->creer_advance)) $createbarcode=0;", "$parameters=array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas);\n$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks\nif ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');", "if (empty($reshook))\n{\n // Type\n\tif ($action == 'setfk_product_type' && $usercancreate)\n {\n \t$result = $object->setValueFrom('fk_product_type', GETPOST('fk_product_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY');\n \theader(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$object->id);\n \texit;\n }", " // Actions to build doc\n $upload_dir = $conf->produit->dir_output;\n $permissioncreate = $usercancreate;\n include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';", " include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';", " // Barcode type\n if ($action ==\t'setfk_barcode_type' && $createbarcode)\n {\n $result = $object->setValueFrom('fk_barcode_type', GETPOST('fk_barcode_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY');\n \theader(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$object->id);\n \texit;\n }", " // Barcode value\n if ($action ==\t'setbarcode' && $createbarcode)\n {\n \t$result=$object->check_barcode(GETPOST('barcode'),GETPOST('barcode_type_code'));", "\t\tif ($result >= 0)\n\t\t{\n\t \t$result = $object->setValueFrom('barcode', GETPOST('barcode'));\n\t \theader(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$object->id);\n\t \texit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$langs->load(\"errors\");\n \tif ($result == -1) $errors[] = 'ErrorBadBarCodeSyntax';\n \telse if ($result == -2) $errors[] = 'ErrorBarCodeRequired';\n \telse if ($result == -3) $errors[] = 'ErrorBarCodeAlreadyUsed';\n \telse $errors[] = 'FailedToValidateBarCode';", "\t\t\t$error++;\n\t\t\tsetEventMessages($errors, null, 'errors');\n\t\t}\n }", " // Add a product or service\n if ($action == 'add' && $usercancreate)\n {\n $error=0;", " if (! GETPOST('label'))\n {\n setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Label')), null, 'errors');\n $action = \"create\";\n $error++;\n }\n if (empty($ref))\n {\n setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Ref')), null, 'errors');\n $action = \"create\";\n $error++;\n }\n if (! empty($duration_value) && empty($duration_unit))\n {\n setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Unit')), null, 'errors');\n $action = \"create\";\n $error++;\n }", " if (! $error)\n {\n\t $units = GETPOST('units', 'int');", " $object->ref = $ref;\n $object->label = GETPOST('label');\n $object->price_base_type = GETPOST('price_base_type');", " if ($object->price_base_type == 'TTC')\n \t$object->price_ttc = GETPOST('price');\n else\n \t$object->price = GETPOST('price');\n if ($object->price_base_type == 'TTC')\n \t$object->price_min_ttc = GETPOST('price_min');\n else\n \t$object->price_min = GETPOST('price_min');", "\t $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)'", "\t // We must define tva_tx, npr and local taxes\n\t $vatratecode = '';\n\t $tva_tx = preg_replace('/[^0-9\\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot\n\t $npr = preg_match('/\\*/', $tva_tx_txt) ? 1 : 0;\n\t $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';\n\t // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes\n\t if (preg_match('/\\((.*)\\)/', $tva_tx_txt, $reg))\n\t {\n\t // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price.\n\t $vatratecode=$reg[1];\n\t // Get record from code\n\t $sql = \"SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type\";\n\t $sql.= \" FROM \".MAIN_DB_PREFIX.\"c_tva as t, \".MAIN_DB_PREFIX.\"c_country as c\";\n\t $sql.= \" WHERE t.fk_pays = c.rowid AND c.code = '\".$mysoc->country_code.\"'\";\n\t $sql.= \" AND t.taux = \".((float) $tva_tx).\" AND t.active = 1\";\n\t $sql.= \" AND t.code ='\".$vatratecode.\"'\";\n\t $resql=$db->query($sql);\n\t if ($resql)\n\t {\n\t $obj = $db->fetch_object($resql);\n\t $npr = $obj->recuperableonly;\n\t $localtax1 = $obj->localtax1;\n\t $localtax2 = $obj->localtax2;\n\t $localtax1_type = $obj->localtax1_type;\n\t $localtax2_type = $obj->localtax2_type;\n\t }\n\t }", "\t $object->default_vat_code = $vatratecode;\n\t $object->tva_tx = $tva_tx;\n\t $object->tva_npr = $npr;\n\t $object->localtax1_tx = $localtax1;\n\t $object->localtax2_tx = $localtax2;\n\t $object->localtax1_type = $localtax1_type;\n\t $object->localtax2_type = $localtax2_type;", " $object->type \t = $type;\n $object->status \t = GETPOST('statut');\n $object->status_buy = GETPOST('statut_buy');\n\t\t\t$object->status_batch \t= GETPOST('status_batch');", " $object->barcode_type = GETPOST('fk_barcode_type');\n $object->barcode\t\t = GETPOST('barcode');\n // Set barcode_type_xxx from barcode_type id\n $stdobject=new GenericObject($db);\n \t $stdobject->element='product';\n $stdobject->barcode_type=GETPOST('fk_barcode_type');\n $result=$stdobject->fetch_barcode();\n if ($result < 0)\n {\n \t$error++;\n \t$mesg='Failed to get bar code type information ';\n \tsetEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors');\n }\n $object->barcode_type_code = $stdobject->barcode_type_code;\n $object->barcode_type_coder = $stdobject->barcode_type_coder;\n $object->barcode_type_label = $stdobject->barcode_type_label;", " $object->description \t = dol_htmlcleanlastbr(GETPOST('desc','none'));\n $object->url\t\t\t\t\t = GETPOST('url');\n $object->note_private \t = dol_htmlcleanlastbr(GETPOST('note_private','none'));\n $object->note \t = $object->note_private; // deprecated", " $object->customcode = GETPOST('customcode');\n $object->country_id = GETPOST('country_id');", " $object->duration_value \t = $duration_value;\n $object->duration_unit \t = $duration_unit;\n $object->seuil_stock_alerte \t = GETPOST('seuil_stock_alerte')?GETPOST('seuil_stock_alerte'):0;\n $object->desiredstock = GETPOST('desiredstock')?GETPOST('desiredstock'):0;\n $object->canvas \t = GETPOST('canvas');\n $object->weight \t = GETPOST('weight');\n $object->weight_units \t = GETPOST('weight_units');\n $object->length \t = GETPOST('size');\n $object->length_units \t = GETPOST('size_units');\n $object->width \t = GETPOST('sizewidth');\n $object->height \t = GETPOST('sizeheight');\n\t $object->surface \t = GETPOST('surface');\n $object->surface_units \t = GETPOST('surface_units');\n $object->volume \t = GETPOST('volume');\n $object->volume_units \t = GETPOST('volume_units');", " $object->finished \t = GETPOST('finished');\n\t $object->fk_unit = GETPOST('units');", "\t\t\t$accountancy_code_sell \t\t\t = GETPOST('accountancy_code_sell');\n\t\t\t$accountancy_code_sell_intra\t = GETPOST('accountancy_code_sell_intra');\n\t\t\t$accountancy_code_sell_export\t = GETPOST('accountancy_code_sell_export');\n\t\t\t$accountancy_code_buy \t\t\t = GETPOST('accountancy_code_buy');", "\n\t\t\tif ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; }\n\t\t\tif ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; }\n\t\t\tif ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; }\n\t\t\tif ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; }", " // MultiPrix\n if (! empty($conf->global->PRODUIT_MULTIPRICES))\n {\n for($i=2;$i<=$conf->global->PRODUIT_MULTIPRICES_LIMIT;$i++)\n {\n if (isset($_POST[\"price_\".$i]))\n {\n $object->multiprices[\"$i\"] = price2num($_POST[\"price_\".$i],'MU');\n $object->multiprices_base_type[\"$i\"] = $_POST[\"multiprices_base_type_\".$i];\n }\n else\n {\n $object->multiprices[\"$i\"] = \"\";\n }\n }\n }", " // Fill array 'array_options' with data from add form\n \t$ret = $extrafields->setOptionalsFromPost($extralabels,$object);\n\t\t\tif ($ret < 0) $error++;", "\t\t\tif (! $error)\n\t\t\t{\n \t$id = $object->create($user);\n\t\t\t}", " if ($id > 0)\n {\n\t\t\t\t// Category association\n\t\t\t\t$categories = GETPOST('categories', 'array');\n\t\t\t\t$object->setCategories($categories);", " header(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$id);\n exit;\n }\n else\n\t\t\t{\n \tif (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors');\n\t\t\t\telse setEventMessages($langs->trans($object->error), null, 'errors');\n $action = \"create\";\n }\n }\n }", " // Update a product or service\n if ($action == 'update' && $usercancreate)\n {\n \tif (GETPOST('cancel','alpha'))\n {\n $action = '';\n }\n else\n {\n if ($object->id > 0)\n {\n\t\t\t\t$object->oldcopy= clone $object;", " $object->ref = $ref;\n $object->label = GETPOST('label');\n $object->description = dol_htmlcleanlastbr(GETPOST('desc','none'));\n \t$object->url\t\t\t\t\t= GETPOST('url');\n \t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n \t\t\t{\n \t$object->note_private = dol_htmlcleanlastbr(GETPOST('note_private','none'));\n $object->note = $object->note_private;\n \t\t\t}", " $object->customcode = GETPOST('customcode');\n $object->country_id = GETPOST('country_id');\n $object->status = GETPOST('statut');\n $object->status_buy = GETPOST('statut_buy');\n $object->status_batch\t = GETPOST('status_batch');", " // removed from update view so GETPOST always empty\n /*\n $object->seuil_stock_alerte = GETPOST('seuil_stock_alerte');\n $object->desiredstock = GETPOST('desiredstock');\n */\n $object->duration_value = GETPOST('duration_value');\n $object->duration_unit = GETPOST('duration_unit');", " $object->canvas = GETPOST('canvas');\n $object->weight = GETPOST('weight');\n $object->weight_units = GETPOST('weight_units');\n $object->length = GETPOST('size');\n $object->length_units = GETPOST('size_units');\n $object->width \t = GETPOST('sizewidth');\n $object->height \t = GETPOST('sizeheight');", " $object->surface = GETPOST('surface');\n $object->surface_units = GETPOST('surface_units');\n $object->volume = GETPOST('volume');\n $object->volume_units = GETPOST('volume_units');", " $object->finished = GETPOST('finished');", "\n\t $units = GETPOST('units', 'int');", "\t if ($units > 0) {\n\t\t $object->fk_unit = $units;\n\t } else {\n\t\t $object->fk_unit = null;\n\t }", "\t $object->barcode_type = GETPOST('fk_barcode_type');\n \t $object->barcode\t\t = GETPOST('barcode');\n \t // Set barcode_type_xxx from barcode_type id\n \t $stdobject=new GenericObject($db);\n \t $stdobject->element='product';\n \t $stdobject->barcode_type=GETPOST('fk_barcode_type');\n \t $result=$stdobject->fetch_barcode();\n \t if ($result < 0)\n \t {\n \t \t$error++;\n \t \t$mesg='Failed to get bar code type information ';\n \t\tsetEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors');\n \t }\n \t $object->barcode_type_code = $stdobject->barcode_type_code;\n \t $object->barcode_type_coder = $stdobject->barcode_type_coder;\n \t $object->barcode_type_label = $stdobject->barcode_type_label;\n", "\t\t\t\t$accountancy_code_sell \t\t\t = GETPOST('accountancy_code_sell');\n\t\t\t\t$accountancy_code_sell_intra\t = GETPOST('accountancy_code_sell_intra');\n\t\t\t\t$accountancy_code_sell_export\t = GETPOST('accountancy_code_sell_export');\n\t\t\t\t$accountancy_code_buy \t\t\t = GETPOST('accountancy_code_buy');", "\n\t\t\t\tif ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; }\n\t\t\t\tif ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; }\n\t\t\t\tif ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; }\n\t\t\t\tif ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; }", " // Fill array 'array_options' with data from add form\n \t\t$ret = $extrafields->setOptionalsFromPost($extralabels,$object);\n\t\t\t\tif ($ret < 0) $error++;", " if (! $error && $object->check())\n {\n if ($object->update($object->id, $user) > 0)\n {\n\t\t\t\t\t\t// Category association\n\t\t\t\t\t\t$categories = GETPOST('categories', 'array');\n\t\t\t\t\t\t$object->setCategories($categories);", " $action = 'view';\n }\n else\n\t\t\t\t\t{\n\t\t\t\t\t\tif (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors');\n \telse setEventMessages($langs->trans($object->error), null, 'errors');\n $action = 'edit';\n }\n }\n else\n\t\t\t\t{\n\t\t\t\t\tif (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors');\n \telse setEventMessages($langs->trans(\"ErrorProductBadRefOrLabel\"), null, 'errors');\n $action = 'edit';\n }\n }", " }\n }", " // Action clone object\n if ($action == 'confirm_clone' && $confirm != 'yes') { $action=''; }\n if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate)\n {\n if (! GETPOST('clone_content') && ! GETPOST('clone_prices') )\n {\n \tsetEventMessages($langs->trans(\"NoCloneOptionsSpecified\"), null, 'errors');\n }\n else\n {\n $db->begin();", " $originalId = $id;\n if ($object->id > 0)\n {\n $object->ref = GETPOST('clone_ref');\n $object->status = 0;\n $object->status_buy = 0;\n $object->id = null;\n $object->barcode = -1;", " if ($object->check())\n {\n $id = $object->create($user);\n if ($id > 0)\n {\n if (GETPOST('clone_composition'))\n {\n $result = $object->clone_associations($originalId, $id);", " if ($result < 1)\n {\n $db->rollback();\n setEventMessages($langs->trans('ErrorProductClone'), null, 'errors');\n header(\"Location: \".$_SERVER[\"PHP_SELF\"].\"?id=\".$originalId);\n exit;\n }\n }", " // $object->clone_fournisseurs($originalId, $id);", " $db->commit();\n $db->close();", " header(\"Location: \".$_SERVER[\"PHP_SELF\"].\"?id=\".$id);\n exit;\n }\n else\n {\n $id=$originalId;", " if ($object->error == 'ErrorProductAlreadyExists')\n {\n $db->rollback();", " $refalreadyexists++;\n $action = \"\";", " $mesg=$langs->trans(\"ErrorProductAlreadyExists\",$object->ref);\n $mesg.=' <a href=\"'.$_SERVER[\"PHP_SELF\"].'?ref='.$object->ref.'\">'.$langs->trans(\"ShowCardHere\").'</a>.';\n setEventMessages($mesg, null, 'errors');\n $object->fetch($id);\n }\n else\n {\n $db->rollback();\n if (count($object->errors))\n {\n \tsetEventMessages($object->error, $object->errors, 'errors');\n \tdol_print_error($db,$object->errors);\n }\n else\n {\n \tsetEventMessages($langs->trans($object->error), null, 'errors');\n \tdol_print_error($db,$object->error);\n }\n }\n }\n }\n }\n else\n {\n $db->rollback();\n dol_print_error($db,$object->error);\n }\n }\n }", " // Delete a product\n if ($action == 'confirm_delete' && $confirm != 'yes') { $action=''; }\n if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete)\n\t{\n\t\t$result = $object->delete($user);", " if ($result > 0)\n {\n header('Location: '.DOL_URL_ROOT.'/product/list.php?type='.$object->type.'&delprod='.urlencode($object->ref));\n exit;\n }\n else\n {\n \tsetEventMessages($langs->trans($object->error), null, 'errors');\n $reload = 0;\n $action='';\n }\n }", "\n // Add product into object\n if ($object->id > 0 && $action == 'addin')\n {\n $thirpdartyid =0 ;\n if (GETPOST('propalid') > 0)\n {\n \t$propal = new Propal($db);\n\t $result=$propal->fetch(GETPOST('propalid'));\n\t if ($result <= 0)\n\t {\n\t dol_print_error($db,$propal->error);\n\t exit;\n\t }\n\t $thirpdartyid = $propal->socid;\n }\n elseif (GETPOST('commandeid') > 0)\n {\n $commande = new Commande($db);\n\t $result=$commande->fetch(GETPOST('commandeid'));\n\t if ($result <= 0)\n\t {\n\t dol_print_error($db,$commande->error);\n\t exit;\n\t }\n\t $thirpdartyid = $commande->socid;\n }\n elseif (GETPOST('factureid') > 0)\n {\n \t $facture = new Facture($db);\n\t $result=$facture->fetch(GETPOST('factureid'));\n\t if ($result <= 0)\n\t {\n\t dol_print_error($db,$facture->error);\n\t exit;\n\t }\n\t $thirpdartyid = $facture->socid;\n }", " if ( $thirpdartyid > 0) {\n $soc = new Societe($db);\n $result = $soc->fetch($thirpdartyid);\n if ($result <= 0) {\n dol_print_error($db, $soc->error);\n exit;\n }", " $desc = $object->description;", " $tva_tx = get_default_tva($mysoc, $soc, $object->id);\n $tva_npr = get_default_npr($mysoc, $soc, $object->id);\n if (empty($tva_tx)) $tva_npr=0;\n $localtax1_tx = get_localtax($tva_tx, 1, $soc, $mysoc, $tva_npr);\n $localtax2_tx = get_localtax($tva_tx, 2, $soc, $mysoc, $tva_npr);", " $pu_ht = $object->price;\n $pu_ttc = $object->price_ttc;\n $price_base_type = $object->price_base_type;", " // If multiprice\n if ($conf->global->PRODUIT_MULTIPRICES && $soc->price_level) {\n $pu_ht = $object->multiprices[$soc->price_level];\n $pu_ttc = $object->multiprices_ttc[$soc->price_level];\n $price_base_type = $object->multiprices_base_type[$soc->price_level];\n } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {\n require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';", " $prodcustprice = new Productcustomerprice($db);", " $filter = array('t.fk_product' => $object->id, 't.fk_soc' => $soc->id);", " $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);\n if ($result) {\n if (count($prodcustprice->lines) > 0) {\n $pu_ht = price($prodcustprice->lines [0]->price);\n $pu_ttc = price($prodcustprice->lines [0]->price_ttc);\n $price_base_type = $prodcustprice->lines [0]->price_base_type;\n $tva_tx = $prodcustprice->lines [0]->tva_tx;\n }\n }\n }", "\t\t\t$tmpvat = price2num(preg_replace('/\\s*\\(.*\\)/', '', $tva_tx));\n\t\t\t$tmpprodvat = price2num(preg_replace('/\\s*\\(.*\\)/', '', $prod->tva_tx));", " // On reevalue prix selon taux tva car taux tva transaction peut etre different\n // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).\n if ($tmpvat != $tmpprodvat) {\n if ($price_base_type != 'HT') {\n $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');\n } else {\n $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');\n }\n }", " if (GETPOST('propalid') > 0) {\n // Define cost price for margin calculation\n $buyprice=0;\n if (($result = $propal->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0)\n {\n dol_syslog($langs->trans('FailedToGetCostPrice'));\n setEventMessage($langs->trans('FailedToGetCostPrice'), 'errors');\n }\n else\n {\n $buyprice = $result;\n }", " $result = $propal->addline(\n $desc,\n $pu_ht,\n GETPOST('qty'),\n $tva_tx,\n $localtax1_tx, // localtax1\n $localtax2_tx, // localtax2\n $object->id,\n GETPOST('remise_percent'),\n $price_base_type,\n $pu_ttc,\n 0,\n 0,\n -1,\n 0,\n 0,\n 0,\n $buyprice,\n '',\n '',\n '',\n 0,\n $object->fk_unit\n );\n if ($result > 0) {\n header(\"Location: \" . DOL_URL_ROOT . \"/comm/propal/card.php?id=\" . $propal->id);\n return;\n }", " setEventMessages($langs->trans(\"ErrorUnknown\") . \": $result\", null, 'errors');\n } elseif (GETPOST('commandeid') > 0) {\n // Define cost price for margin calculation\n $buyprice=0;\n if (($result = $commande->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0)\n {\n dol_syslog($langs->trans('FailedToGetCostPrice'));\n setEventMessage($langs->trans('FailedToGetCostPrice'), 'errors');\n }\n else\n {\n $buyprice = $result;\n }", " $result = $commande->addline(\n $desc,\n $pu_ht,\n GETPOST('qty'),\n $tva_tx,\n $localtax1_tx, // localtax1\n $localtax2_tx, // localtax2\n $object->id,\n GETPOST('remise_percent'),\n '',\n '',\n $price_base_type,\n $pu_ttc,\n '',\n '',\n 0,\n -1,\n 0,\n 0,\n null,\n $buyprice,\n '',\n 0,\n $object->fk_unit\n );", " if ($result > 0) {\n header(\"Location: \" . DOL_URL_ROOT . \"/commande/card.php?id=\" . $commande->id);\n exit;\n }\n } elseif (GETPOST('factureid') > 0) {\n // Define cost price for margin calculation\n $buyprice=0;\n if (($result = $facture->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0)\n {\n dol_syslog($langs->trans('FailedToGetCostPrice'));\n setEventMessage($langs->trans('FailedToGetCostPrice'), 'errors');\n }\n else\n {\n $buyprice = $result;\n }", " $result = $facture->addline(\n $desc,\n $pu_ht,\n GETPOST('qty'),\n $tva_tx,\n $localtax1_tx,\n $localtax2_tx,\n $object->id,\n GETPOST('remise_percent'),\n '',\n '',\n '',\n '',\n '',\n $price_base_type,\n $pu_ttc,\n Facture::TYPE_STANDARD,\n -1,\n 0,\n '',\n 0,\n 0,\n null,\n $buyprice,\n '',\n 0,\n 100,\n '',\n $object->fk_unit\n );", " if ($result > 0) {\n header(\"Location: \" . DOL_URL_ROOT . \"/compta/facture/card.php?facid=\" . $facture->id);\n exit;\n }\n }\n }\n else {\n $action=\"\";\n setEventMessages($langs->trans(\"WarningSelectOneDocument\"), null, 'warnings');\n }\n }\n}", "", "/*\n * View\n */", "$title = $langs->trans('ProductServiceCard');\n$helpurl = '';\n$shortlabel = dol_trunc($object->label,16);\nif (GETPOST(\"type\") == '0' || ($object->type == Product::TYPE_PRODUCT))\n{\n\t$title = $langs->trans('Product').\" \". $shortlabel .\" - \".$langs->trans('Card');\n\t$helpurl='EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';\n}\nif (GETPOST(\"type\") == '1' || ($object->type == Product::TYPE_SERVICE))\n{\n\t$title = $langs->trans('Service').\" \". $shortlabel .\" - \".$langs->trans('Card');\n\t$helpurl='EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';\n}", "llxHeader('', $title, $helpurl);", "$form = new Form($db);\n$formfile = new FormFile($db);\n$formproduct = new FormProduct($db);\nif (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);", "// Load object modBarCodeProduct\n$res=0;\nif (! empty($conf->barcode->enabled) && ! empty($conf->global->BARCODE_PRODUCT_ADDON_NUM))\n{\n\t$module=strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);\n\t$dirbarcode=array_merge(array('/core/modules/barcode/'),$conf->modules_parts['barcode']);\n\tforeach ($dirbarcode as $dirroot)\n\t{\n\t\t$res=dol_include_once($dirroot.$module.'.php');\n\t\tif ($res) break;\n\t}\n\tif ($res > 0)\n\t{\n\t\t\t$modBarCodeProduct =new $module();\n\t}\n}", "\nif (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))\n{\n\t// -----------------------------------------\n\t// When used with CANVAS\n\t// -----------------------------------------\n\tif (empty($object->error) && $id)\n\t{\n\t\t$object = new Product($db);\n\t\t$result=$object->fetch($id);\n\t\tif ($result <= 0) dol_print_error('',$object->error);\n\t}\n\t$objcanvas->assign_values($action, $object->id, $object->ref);\t// Set value for templates\n\t$objcanvas->display_canvas($action);\t\t\t\t\t\t\t// Show template\n}\nelse\n{\n // -----------------------------------------\n // When used in standard mode\n // -----------------------------------------\n\tif ($action == 'create' && $usercancreate)\n {\n //WYSIWYG Editor\n require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';", "\t\t// Load object modCodeProduct\n $module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard');\n if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php')\n {\n $module = substr($module, 0, dol_strlen($module)-4);\n }\n $result=dol_include_once('/core/modules/product/'.$module.'.php');\n if ($result > 0)\n {\n \t$modCodeProduct = new $module();\n }", " dol_set_focus('input[name=\"ref\"]');", " print '<form action=\"'.$_SERVER[\"PHP_SELF\"].'\" method=\"POST\">';\n print '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n print '<input type=\"hidden\" name=\"action\" value=\"add\">';\n print '<input type=\"hidden\" name=\"type\" value=\"'.$type.'\">'.\"\\n\";\n\t\tif (! empty($modCodeProduct->code_auto))\n\t\t\tprint '<input type=\"hidden\" name=\"code_auto\" value=\"1\">';\n\t\tif (! empty($modBarCodeProduct->code_auto))\n\t\t\tprint '<input type=\"hidden\" name=\"barcode_auto\" value=\"1\">';", " if ($type==1) $title=$langs->trans(\"NewService\");\n else $title=$langs->trans(\"NewProduct\");\n $linkback=\"\";\n print load_fiche_titre($title,$linkback,'title_products.png');", " dol_fiche_head('');", " print '<table class=\"border centpercent\">';", " print '<tr>';\n $tmpcode='';\n\t\tif (! empty($modCodeProduct->code_auto)) $tmpcode=$modCodeProduct->getNextValue($object,$type);\n print '<td class=\"titlefieldcreate fieldrequired\">'.$langs->trans(\"Ref\").'</td><td colspan=\"3\"><input id=\"ref\" name=\"ref\" class=\"maxwidth200\" maxlength=\"128\" value=\"'.dol_escape_htmltag(GETPOST('ref')?GETPOST('ref'):$tmpcode).'\">';\n if ($refalreadyexists)\n {\n print $langs->trans(\"RefAlreadyExists\");\n }\n print '</td></tr>';", " // Label\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Label\").'</td><td colspan=\"3\"><input name=\"label\" class=\"minwidth300 maxwidth400onsmartphone\" maxlength=\"255\" value=\"'.dol_escape_htmltag(GETPOST('label')).'\"></td></tr>';", " // On sell\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Sell\").')</td><td colspan=\"3\">';\n $statutarray=array('1' => $langs->trans(\"OnSell\"), '0' => $langs->trans(\"NotOnSell\"));\n print $form->selectarray('statut',$statutarray,GETPOST('statut'));\n print '</td></tr>';", " // To buy\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Buy\").')</td><td colspan=\"3\">';\n $statutarray=array('1' => $langs->trans(\"ProductStatusOnBuy\"), '0' => $langs->trans(\"ProductStatusNotOnBuy\"));\n print $form->selectarray('statut_buy',$statutarray,GETPOST('statut_buy'));\n print '</td></tr>';", "\t // Batch number management\n\t\tif (! empty($conf->productbatch->enabled))\n\t\t{\n\t\t\tprint '<tr><td>'.$langs->trans(\"ManageLotSerial\").'</td><td colspan=\"3\">';\n\t\t\t$statutarray=array('0' => $langs->trans(\"ProductStatusNotOnBatch\"), '1' => $langs->trans(\"ProductStatusOnBatch\"));\n\t\t\tprint $form->selectarray('status_batch',$statutarray,GETPOST('status_batch'));\n\t\t\tprint '</td></tr>';\n\t\t}", " $showbarcode=empty($conf->barcode->enabled)?0:1;\n if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;", " if ($showbarcode)\n {\n \t print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>';\n \t if (isset($_POST['fk_barcode_type']))\n\t {\n\t \t$fk_barcode_type=GETPOST('fk_barcode_type');\n\t }\n\t else\n\t {\n\t \tif (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;\n\t }\n\t require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';\n $formbarcode = new FormBarCode($db);\n\t print $formbarcode->select_barcode_type($fk_barcode_type, 'fk_barcode_type', 1);\n\t print '</td><td>'.$langs->trans(\"BarcodeValue\").'</td><td>';\n\t $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode;\n\t if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object,$type);\n\t print '<input class=\"maxwidth100\" type=\"text\" name=\"barcode\" value=\"'.dol_escape_htmltag($tmpcode).'\">';\n\t print '</td></tr>';\n }", " // Description (used in invoice, propal...)\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"Description\").'</td><td colspan=\"3\">';", " $doleditor = new DolEditor('desc', GETPOST('desc','none'), '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%');\n $doleditor->Create();", " print \"</td></tr>\";", " // Public URL\n print '<tr><td>'.$langs->trans(\"PublicUrl\").'</td><td colspan=\"3\">';\n\t\tprint '<input type=\"text\" name=\"url\" class=\"quatrevingtpercent\" value=\"'.GETPOST('url').'\">';\n print '</td></tr>';", " // Stock min level\n if ($type != 1 && ! empty($conf->stock->enabled))\n {\n print '<tr><td>'.$form->textwithpicto($langs->trans(\"StockLimit\"), $langs->trans(\"StockLimitDesc\"), 1).'</td><td>';\n print '<input name=\"seuil_stock_alerte\" class=\"maxwidth50\" value=\"'.GETPOST('seuil_stock_alerte').'\">';\n print '</td>';\n // Stock desired level\n print '<td>'.$form->textwithpicto($langs->trans(\"DesiredStock\"), $langs->trans(\"DesiredStockDesc\"), 1).'</td><td>';\n print '<input name=\"desiredstock\" class=\"maxwidth50\" value=\"'.GETPOST('desiredstock').'\">';\n print '</td></tr>';\n }\n else\n {\n print '<input name=\"seuil_stock_alerte\" type=\"hidden\" value=\"0\">';\n print '<input name=\"desiredstock\" type=\"hidden\" value=\"0\">';\n }", " // Nature\n if ($type != 1)\n {\n print '<tr><td>'.$langs->trans(\"Nature\").'</td><td colspan=\"3\">';\n $statutarray=array('1' => $langs->trans(\"Finished\"), '0' => $langs->trans(\"RowMaterial\"));\n print $form->selectarray('finished',$statutarray,GETPOST('finished'),1);\n print '</td></tr>';\n }", " // Duration\n if ($type == 1)\n {\n print '<tr><td>' . $langs->trans(\"Duration\") . '</td><td colspan=\"3\"><input name=\"duration_value\" size=\"6\" maxlength=\"5\" value=\"' . $duration_value . '\"> &nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"h\">'.$langs->trans(\"Hour\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"d\">'.$langs->trans(\"Day\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"w\">'.$langs->trans(\"Week\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"m\">'.$langs->trans(\"Month\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"y\">'.$langs->trans(\"Year\").'&nbsp;';\n print '</td></tr>';\n }", " if ($type != 1)\t// Le poids et le volume ne concerne que les produits et pas les services\n {\n // Weight\n print '<tr><td>'.$langs->trans(\"Weight\").'</td><td colspan=\"3\">';\n print '<input name=\"weight\" size=\"4\" value=\"'.GETPOST('weight').'\">';\n print $formproduct->select_measuring_units(\"weight_units\",\"weight\");\n print '</td></tr>';\n // Length\n if (empty($conf->global->PRODUCT_DISABLE_SIZE))\n {\n print '<tr><td>'.$langs->trans(\"Length\").' x '.$langs->trans(\"Width\").' x '.$langs->trans(\"Height\").'</td><td colspan=\"3\">';\n print '<input name=\"size\" size=\"4\" value=\"'.GETPOST('size').'\"> x ';\n print '<input name=\"sizewidth\" size=\"4\" value=\"'.GETPOST('sizewidth').'\"> x ';\n print '<input name=\"sizeheight\" size=\"4\" value=\"'.GETPOST('sizeheight').'\">';\n print $formproduct->select_measuring_units(\"size_units\",\"size\");\n print '</td></tr>';\n }\n if (empty($conf->global->PRODUCT_DISABLE_SURFACE))\n {\n // Surface\n print '<tr><td>'.$langs->trans(\"Surface\").'</td><td colspan=\"3\">';\n print '<input name=\"surface\" size=\"4\" value=\"'.GETPOST('surface').'\">';\n print $formproduct->select_measuring_units(\"surface_units\",\"surface\");\n print '</td></tr>';\n }\n // Volume\n print '<tr><td>'.$langs->trans(\"Volume\").'</td><td colspan=\"3\">';\n print '<input name=\"volume\" size=\"4\" value=\"'.GETPOST('volume').'\">';\n print $formproduct->select_measuring_units(\"volume_units\",\"volume\");\n print '</td></tr>';\n }", " // Units\n\t if($conf->global->PRODUCT_USE_UNITS)\n\t {\n\t\t print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td>';\n\t\t print '<td colspan=\"3\">';\n\t\t print $form->selectUnits('','units');\n\t\t print '</td></tr>';\n\t }", " // Custom code\n if (empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO) && empty($type))\n {\n\t print '<tr><td>'.$langs->trans(\"CustomCode\").'</td><td><input name=\"customcode\" class=\"maxwidth100onsmartphone\" value=\"'.GETPOST('customcode').'\"></td>';\n\t // Origin country\n\t print '<td>'.$langs->trans(\"CountryOrigin\").'</td><td>';\n\t print $form->select_country(GETPOST('country_id','int'),'country_id');\n\t if ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t print '</td></tr>';\n }", " // Other attributes\n $parameters=array('cols' => 3);\n $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n print $hookmanager->resPrint;\n if (empty($reshook) && ! empty($extrafields->attribute_label))\n {\n \tprint $object->showOptionals($extrafields,'edit',$parameters);\n }", " // Note (private, no output on invoices, propales...)\n //if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) available in create mode\n //{\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"NoteNotVisibleOnBill\").'</td><td colspan=\"3\">';", " // We use dolibarr_details as type of DolEditor here, because we must not accept images as description is included into PDF and not accepted by TCPDF.\n $doleditor = new DolEditor('note_private', GETPOST('note_private','none'), '', 140, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_8, '90%');\n \t $doleditor->Create();", " print \"</td></tr>\";\n //}", "\t\tif ($conf->categorie->enabled) {\n\t\t\t// Categories\n\t\t\tprint '<tr><td>'.$langs->trans(\"Categories\").'</td><td colspan=\"3\">';\n\t\t\t$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 64, 0, 1);\n\t\t\tprint $form->multiselectarray('categories', $cate_arbo, GETPOST('categories', 'array'), '', 0, '', 0, '100%');\n\t\t\tprint \"</td></tr>\";\n\t\t}", " print '</table>';", " print '<br>';", " if (! empty($conf->global->PRODUIT_MULTIPRICES))\n {\n // We do no show price array on create when multiprices enabled.\n // We must set them on prices tab.\n print '<table class=\"border\" width=\"100%\">';\n // VAT\n print '<tr><td class=\"titlefieldcreate\">' . $langs->trans(\"VATRate\") . '</td><td>';\n $defaultva = get_default_tva($mysoc, $mysoc);\n print $form->load_tva(\"tva_tx\", $defaultva, $mysoc, $mysoc, 0, 0, '', false, 1);\n print '</td></tr>';\n print '</table>';\n print '<br>';\n }\n else\n\t\t{\n print '<table class=\"border\" width=\"100%\">';", " // Price\n print '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"SellingPrice\").'</td>';\n print '<td><input name=\"price\" class=\"maxwidth50\" value=\"'.$object->price.'\">';\n print $form->selectPriceBaseType($object->price_base_type, \"price_base_type\");\n print '</td></tr>';", " // Min price\n print '<tr><td>'.$langs->trans(\"MinPrice\").'</td>';\n print '<td><input name=\"price_min\" class=\"maxwidth50\" value=\"'.$object->price_min.'\">';\n print '</td></tr>';", " // VAT\n print '<tr><td>'.$langs->trans(\"VATRate\").'</td><td>';\n $defaultva=get_default_tva($mysoc, $mysoc);\n print $form->load_tva(\"tva_tx\", $defaultva, $mysoc, $mysoc, 0, 0, '', false, 1);\n print '</td></tr>';", " print '</table>';", " print '<br>';\n }", " // Accountancy codes\n print '<table class=\"border\" width=\"100%\">';", "\t\tif (! empty($conf->accounting->enabled))\n\t\t{\n\t\t\t// Accountancy_code_sell\n\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\tprint '<td>';\n\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_sell'), 'accountancy_code_sell', 1, null, 1, 1, '');\n\t\t\tprint '</td></tr>';", "\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\tprint '<td>';\n\t\t\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_sell_intra'), 'accountancy_code_sell_intra', 1, null, 1, 1, '');\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\tprint '<td>';\n\t\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_sell_export'), 'accountancy_code_sell_export', 1, null, 1, 1, '');\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", "\t\t\t// Accountancy_code_buy\n\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\tprint '<td>';\n\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_buy'), 'accountancy_code_buy', 1, null, 1, 1, '');\n\t\t\tprint '</td></tr>';\n\t\t}\n\t\telse // For external software\n\t\t{\n\t\t\t// Accountancy_code_sell\n\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_sell\" value=\"'.$object->accountancy_code_sell.'\">';\n\t\t\tprint '</td></tr>';", "\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_sell_intra\" value=\"'.$object->accountancy_code_sell_intra.'\">';\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_sell_export\" value=\"'.$object->accountancy_code_sell_export.'\">';\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", "\t\t\t// Accountancy_code_buy\n\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_buy\" value=\"'.$object->accountancy_code_buy.'\">';\n\t\t\tprint '</td></tr>';\n\t\t}\n\t\tprint '</table>';", "\t\tdol_fiche_end();", "\t\tprint '<div class=\"center\">';\n\t\tprint '<input type=\"submit\" class=\"button\" value=\"' . $langs->trans(\"Create\") . '\">';\n\t\tprint ' &nbsp; &nbsp; ';\n\t\tprint '<input type=\"button\" class=\"button\" value=\"' . $langs->trans(\"Cancel\") . '\" onClick=\"javascript:history.go(-1)\">';\n\t\tprint '</div>';", "\t\tprint '</form>';\n\t}", " /*\n * Product card\n */", " else if ($object->id > 0)\n {\n // Fiche en mode edition\n\t\tif ($action == 'edit' && $usercancreate)\n\t\t{\n //WYSIWYG Editor\n require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';", " $type = $langs->trans('Product');\n if ($object->isService()) $type = $langs->trans('Service');\n //print load_fiche_titre($langs->trans('Modify').' '.$type.' : '.(is_object($object->oldcopy)?$object->oldcopy->ref:$object->ref), \"\");", " // Main official, simple, and not duplicated code\n print '<form action=\"'.$_SERVER['PHP_SELF'].'?id='.$object->id.'\" method=\"POST\">'.\"\\n\";\n print '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n print '<input type=\"hidden\" name=\"action\" value=\"update\">';\n print '<input type=\"hidden\" name=\"id\" value=\"'.$object->id.'\">';\n print '<input type=\"hidden\" name=\"canvas\" value=\"'.$object->canvas.'\">';", " $head=product_prepare_head($object);\n $titre=$langs->trans(\"CardProduct\".$object->type);\n $picto=($object->type== Product::TYPE_SERVICE?'service':'product');\n dol_fiche_head($head, 'card', $titre, 0, $picto);", " print '<table class=\"border allwidth\">';", " // Ref\n print '<tr><td class=\"titlefield fieldrequired\">'.$langs->trans(\"Ref\").'</td><td colspan=\"3\"><input name=\"ref\" class=\"maxwidth200\" maxlength=\"128\" value=\"'.dol_escape_htmltag($object->ref).'\"></td></tr>';", " // Label\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Label\").'</td><td colspan=\"3\"><input name=\"label\" class=\"minwidth300 maxwidth400onsmartphone\" maxlength=\"255\" value=\"'.dol_escape_htmltag($object->label).'\"></td></tr>';", " // Status To sell\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Sell\").')</td><td colspan=\"3\">';\n print '<select class=\"flat\" name=\"statut\">';\n if ($object->status)\n {\n print '<option value=\"1\" selected>'.$langs->trans(\"OnSell\").'</option>';\n print '<option value=\"0\">'.$langs->trans(\"NotOnSell\").'</option>';\n }\n else\n {\n print '<option value=\"1\">'.$langs->trans(\"OnSell\").'</option>';\n print '<option value=\"0\" selected>'.$langs->trans(\"NotOnSell\").'</option>';\n }\n print '</select>';\n print '</td></tr>';", " // Status To Buy\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Buy\").')</td><td colspan=\"3\">';\n print '<select class=\"flat\" name=\"statut_buy\">';\n if ($object->status_buy)\n {\n print '<option value=\"1\" selected>'.$langs->trans(\"ProductStatusOnBuy\").'</option>';\n print '<option value=\"0\">'.$langs->trans(\"ProductStatusNotOnBuy\").'</option>';\n }\n else\n {\n print '<option value=\"1\">'.$langs->trans(\"ProductStatusOnBuy\").'</option>';\n print '<option value=\"0\" selected>'.$langs->trans(\"ProductStatusNotOnBuy\").'</option>';\n }\n print '</select>';\n print '</td></tr>';", "\t\t\t// Batch number managment", "\t\t\tif ($conf->productbatch->enabled) ", "\t\t\t{\n\t\t\t\tif ($object->isProduct() || ! empty($conf->global->STOCK_SUPPORTS_SERVICES))\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td>'.$langs->trans(\"ManageLotSerial\").'</td><td colspan=\"3\">';\n\t\t\t\t\t$statutarray=array('0' => $langs->trans(\"ProductStatusNotOnBatch\"), '1' => $langs->trans(\"ProductStatusOnBatch\"));\n\t\t\t\t\tprint $form->selectarray('status_batch',$statutarray,$object->status_batch);\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}\n\t\t\t}", " // Barcode\n $showbarcode=empty($conf->barcode->enabled)?0:1;\n if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;", "\t if ($showbarcode)\n\t {\n\t\t print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>';\n\t\t if (isset($_POST['fk_barcode_type']))\n\t\t {\n\t\t \t$fk_barcode_type=GETPOST('fk_barcode_type');\n\t\t }\n\t\t else\n\t\t {\n\t \t\t$fk_barcode_type=$object->barcode_type;\n\t\t \tif (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;\n\t\t }\n\t\t require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';\n\t $formbarcode = new FormBarCode($db);\n\t\t print $formbarcode->select_barcode_type($fk_barcode_type, 'fk_barcode_type', 1);\n\t\t print '</td><td>'.$langs->trans(\"BarcodeValue\").'</td><td>';\n\t\t $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode;\n\t\t if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object,$type);\n\t\t print '<input size=\"40\" class=\"maxwidthonsmartphone\" type=\"text\" name=\"barcode\" value=\"'.dol_escape_htmltag($tmpcode).'\">';\n\t\t print '</td></tr>';\n\t }", " // Description (used in invoice, propal...)\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"Description\").'</td><td colspan=\"3\">';", " // We use dolibarr_details as type of DolEditor here, because we must not accept images as description is included into PDF and not accepted by TCPDF.\n $doleditor = new DolEditor('desc', $object->description, '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%');\n $doleditor->Create();", " print \"</td></tr>\";\n print \"\\n\";", " // Public Url\n print '<tr><td>'.$langs->trans(\"PublicUrl\").'</td><td colspan=\"3\">';\n\t\t\tprint '<input type=\"text\" name=\"url\" class=\"quatrevingtpercent\" value=\"'.$object->url.'\">';\n print '</td></tr>';", " // Stock\n /*\n if ($object->isProduct() && ! empty($conf->stock->enabled))\n {\n print \"<tr>\".'<td>'.$langs->trans(\"StockLimit\").'</td><td>';\n print '<input name=\"seuil_stock_alerte\" size=\"4\" value=\"'.$object->seuil_stock_alerte.'\">';\n print '</td>';", " print '<td>'.$langs->trans(\"DesiredStock\").'</td><td>';\n print '<input name=\"desiredstock\" size=\"4\" value=\"'.$object->desiredstock.'\">';\n print '</td></tr>';\n }\n else\n {\n print '<input name=\"seuil_stock_alerte\" type=\"hidden\" value=\"'.$object->seuil_stock_alerte.'\">';\n print '<input name=\"desiredstock\" type=\"hidden\" value=\"'.$object->desiredstock.'\">';\n }*/", " // Nature\n if($object->type!= Product::TYPE_SERVICE)\n {\n print '<tr><td>'.$langs->trans(\"Nature\").'</td><td colspan=\"3\">';\n $statutarray=array('-1'=>'&nbsp;', '1' => $langs->trans(\"Finished\"), '0' => $langs->trans(\"RowMaterial\"));\n print $form->selectarray('finished',$statutarray,$object->finished);\n print '</td></tr>';\n }", " if ($object->isService())\n {\n // Duration\n print '<tr><td>'.$langs->trans(\"Duration\").'</td><td colspan=\"3\"><input name=\"duration_value\" size=\"3\" maxlength=\"5\" value=\"'.$object->duration_value.'\">';\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"h\"'.($object->duration_unit=='h'?' checked':'').'>'.$langs->trans(\"Hour\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"d\"'.($object->duration_unit=='d'?' checked':'').'>'.$langs->trans(\"Day\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"w\"'.($object->duration_unit=='w'?' checked':'').'>'.$langs->trans(\"Week\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"m\"'.($object->duration_unit=='m'?' checked':'').'>'.$langs->trans(\"Month\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"y\"'.($object->duration_unit=='y'?' checked':'').'>'.$langs->trans(\"Year\");\n print '</td></tr>';\n }\n else\n\t\t\t{\n // Weight\n print '<tr><td>'.$langs->trans(\"Weight\").'</td><td colspan=\"3\">';\n print '<input name=\"weight\" size=\"5\" value=\"'.$object->weight.'\"> ';\n print $formproduct->select_measuring_units(\"weight_units\", \"weight\", $object->weight_units);\n print '</td></tr>';\n if (empty($conf->global->PRODUCT_DISABLE_SIZE))\n {\n \t\t\t// Length\n \t\t\tprint '<tr><td>'.$langs->trans(\"Length\").' x '.$langs->trans(\"Width\").' x '.$langs->trans(\"Height\").'</td><td colspan=\"3\">';\n \t\t\tprint '<input name=\"size\" size=\"5\" value=\"'.$object->length.'\">x';\n \t\t\tprint '<input name=\"sizewidth\" size=\"5\" value=\"'.$object->width.'\">x';\n \t\t\tprint '<input name=\"sizeheight\" size=\"5\" value=\"'.$object->height.'\"> ';\n \t\t\tprint $formproduct->select_measuring_units(\"size_units\", \"size\", $object->length_units);\n \t\t\tprint '</td></tr>';\n }\n if (empty($conf->global->PRODUCT_DISABLE_SURFACE))\n {\n // Surface\n print '<tr><td>'.$langs->trans(\"Surface\").'</td><td colspan=\"3\">';\n print '<input name=\"surface\" size=\"5\" value=\"'.$object->surface.'\"> ';\n print $formproduct->select_measuring_units(\"surface_units\", \"surface\", $object->surface_units);\n print '</td></tr>';\n }\n if (empty($conf->global->PRODUCT_DISABLE_VOLUME))\n {\n // Volume\n print '<tr><td>'.$langs->trans(\"Volume\").'</td><td colspan=\"3\">';\n print '<input name=\"volume\" size=\"5\" value=\"'.$object->volume.'\"> ';\n print $formproduct->select_measuring_units(\"volume_units\", \"volume\", $object->volume_units);\n print '</td></tr>';\n }\n }\n \t// Units\n\t if($conf->global->PRODUCT_USE_UNITS)\n\t {\n\t\t print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td>';\n\t\t print '<td colspan=\"3\">';\n\t\t print $form->selectUnits($object->fk_unit, 'units');\n\t\t print '</td></tr>';\n\t }", "\t // Custom code\n \t if (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO))\n \t{\n\t print '<tr><td>'.$langs->trans(\"CustomCode\").'</td><td><input name=\"customcode\" class=\"maxwidth100onsmartphone\" value=\"'.$object->customcode.'\"></td>';\n\t // Origin country\n\t print '<td>'.$langs->trans(\"CountryOrigin\").'</td><td>';\n\t print $form->select_country($object->country_id, 'country_id', '', 0, 'minwidth100 maxwidthonsmartphone');\n\t if ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t print '</td></tr>';\n \t}", " // Other attributes\n $parameters=array('colspan' => ' colspan=\"3\"', 'cols'=>3);\n $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n print $hookmanager->resPrint;\n if (empty($reshook) && ! empty($extrafields->attribute_label))\n {\n \tprint $object->showOptionals($extrafields,'edit');\n }", "\t\t\t// Tags-Categories\n if ($conf->categorie->enabled)\n\t\t\t{\n\t\t\t\tprint '<tr><td class=\"tdtop\">'.$langs->trans(\"Categories\").'</td><td colspan=\"3\">';\n\t\t\t\t$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 64, 0, 1);\n\t\t\t\t$c = new Categorie($db);\n\t\t\t\t$cats = $c->containing($object->id,Categorie::TYPE_PRODUCT);\n\t\t\t\t$arrayselected=array();\n\t\t\t\tforeach($cats as $cat) {\n\t\t\t\t\t$arrayselected[] = $cat->id;\n\t\t\t\t}\n\t\t\t\tprint $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%');\n\t\t\t\tprint \"</td></tr>\";\n\t\t\t}", " // Note private\n\t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n\t\t\t{\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"NoteNotVisibleOnBill\").'</td><td colspan=\"3\">';", " $doleditor = new DolEditor('note_private', $object->note_private, '', 140, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%');\n $doleditor->Create();", " print \"</td></tr>\";\n\t\t\t}", " print '</table>';", " print '<br>';", " print '<table class=\"border\" width=\"100%\">';", "\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell\n\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\t\tprint '<td>';\n\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_sell, 'accountancy_code_sell', 1, '', 1, 1);\n\t\t\t\tprint '</td></tr>';", "\t\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t\t{\n\t\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\t\tprint '<td>';\n\t\t\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, '', 1, 1);\n\t\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t\t}", "\t\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\t\tprint '<td>';\n\t\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_sell_export, 'accountancy_code_sell_export', 1, '', 1, 1);\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_buy\n\t\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\t\tprint '<td>';\n\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_buy, 'accountancy_code_buy', 1, '', 1, 1);\n\t\t\t\tprint '</td></tr>';\n\t\t\t}\n\t\t\telse // For external software\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell\n\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\t\tprint '<td><input name=\"accountancy_code_sell\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_sell.'\">';\n\t\t\t\tprint '</td></tr>';", "\t\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t\t{\n\t\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\t\tprint '<td><input name=\"accountancy_code_sell_intra\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_sell_intra.'\">';\n\t\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t\t}", "\t\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\t\tprint '<td><input name=\"accountancy_code_sell_export\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_sell_export.'\">';\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_buy\n\t\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\t\tprint '<td><input name=\"accountancy_code_buy\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_buy.'\">';\n\t\t\t\tprint '</td></tr>';\n\t\t\t}\n\t\t\tprint '</table>';", "\t\t\tdol_fiche_end();", "\t\t\tprint '<div class=\"center\">';\n\t\t\tprint '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Save\").'\">';\n\t\t\tprint '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';\n\t\t\tprint '<input type=\"submit\" class=\"button\" name=\"cancel\" value=\"'.$langs->trans(\"Cancel\").'\">';\n\t\t\tprint '</div>';", "\t\t\tprint '</form>';\n\t\t}\n // Fiche en mode visu\n else\n\t\t{\n $showbarcode=empty($conf->barcode->enabled)?0:1;\n if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;", "\t\t $head=product_prepare_head($object);\n $titre=$langs->trans(\"CardProduct\".$object->type);\n $picto=($object->type== Product::TYPE_SERVICE?'service':'product');", " dol_fiche_head($head, 'card', $titre, -1, $picto);", " $linkback = '<a href=\"'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1&type='.$object->type.'\">'.$langs->trans(\"BackToList\").'</a>';\n $object->next_prev_filter=\" fk_product_type = \".$object->type;", " $shownav = 1;\n if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0;", " dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');", "\n print '<div class=\"fichecenter\">';\n print '<div class=\"fichehalfleft\">';", " print '<div class=\"underbanner clearboth\"></div>';\n print '<table class=\"border tableforfield\" width=\"100%\">';", "\t\t\t// Type\n\t\t\tif (! empty($conf->produit->enabled) && ! empty($conf->service->enabled))\n\t\t\t{\n\t\t\t\t// TODO change for compatibility with edit in place\n\t\t\t\t$typeformat='select;0:'.$langs->trans(\"Product\").',1:'.$langs->trans(\"Service\");\n\t\t\t\tprint '<tr><td class=\"titlefield\">'.$form->editfieldkey(\"Type\", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat).'</td><td colspan=\"2\">';\n\t\t\t\tprint $form->editfieldval(\"Type\", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat);\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", " if ($showbarcode)\n {\n // Barcode type\n print '<tr><td class=\"nowrap\">';\n print '<table width=\"100%\" class=\"nobordernopadding\"><tr><td class=\"nowrap\">';\n print $langs->trans(\"BarcodeType\");\n print '</td>';\n if (($action != 'editbarcodetype') && $usercancreate && $createbarcode) print '<td align=\"right\"><a href=\"'.$_SERVER[\"PHP_SELF\"].'?action=editbarcodetype&amp;id='.$object->id.'\">'.img_edit($langs->trans('Edit'),1).'</a></td>';\n print '</tr></table>';\n print '</td><td colspan=\"2\">';\n if ($action == 'editbarcodetype' || $action == 'editbarcode')\n {\n require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';\n $formbarcode = new FormBarCode($db);\n\t\t\t\t}\n if ($action == 'editbarcodetype')\n {\n $formbarcode->form_barcode_type($_SERVER['PHP_SELF'].'?id='.$object->id,$object->barcode_type,'fk_barcode_type');\n }\n else\n {\n $object->fetch_barcode();\n print $object->barcode_type_label?$object->barcode_type_label:($object->barcode?'<div class=\"warning\">'.$langs->trans(\"SetDefaultBarcodeType\").'<div>':'');\n }\n print '</td></tr>'.\"\\n\";", " // Barcode value\n print '<tr><td class=\"nowrap\">';\n print '<table width=\"100%\" class=\"nobordernopadding\"><tr><td class=\"nowrap\">';\n print $langs->trans(\"BarcodeValue\");\n print '</td>';\n if (($action != 'editbarcode') && $usercancreate && $createbarcode) print '<td align=\"right\"><a href=\"'.$_SERVER[\"PHP_SELF\"].'?action=editbarcode&amp;id='.$object->id.'\">'.img_edit($langs->trans('Edit'),1).'</a></td>';\n print '</tr></table>';\n print '</td><td colspan=\"2\">';\n if ($action == 'editbarcode')\n {\n\t\t\t\t\t$tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode;\n\t\t\t\t\tif (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object,$type);", "\t\t\t\t\tprint '<form method=\"post\" action=\"'.$_SERVER[\"PHP_SELF\"].'?id='.$object->id.'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setbarcode\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"barcode_type_code\" value=\"'.$object->barcode_type_code.'\">';\n\t\t\t\t\tprint '<input size=\"40\" class=\"maxwidthonsmartphone\" type=\"text\" name=\"barcode\" value=\"'.$tmpcode.'\">';\n\t\t\t\t\tprint '&nbsp;<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\t\t\tprint '</form>';\n }\n else\n {\n\t\t\t\t\tprint $object->barcode;\n }\n print '</td></tr>'.\"\\n\";\n }", "\t\t\t// Accountancy sell code\n\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\tprint $langs->trans(\"ProductAccountancySellCode\");\n\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t{\n\t\t\t\t$accountingaccount = new AccountingAccount($db);\n\t\t\t\t$accountingaccount->fetch('',$object->accountancy_code_sell,1);", "\t\t\t\tprint $accountingaccount->getNomUrl(0,1,1,'',1);\n\t\t\t} else {\n\t\t\t\tprint $object->accountancy_code_sell;\n\t\t\t}\n\t\t\tprint '</td></tr>';", "\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t{\n\t\t\t\t// Accountancy sell code intra-community\n\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\t\t\tprint $langs->trans(\"ProductAccountancySellIntraCode\");\n\t\t\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t\t\t{\n\t\t\t\t\t\t$accountingaccount2 = new AccountingAccount($db);\n\t\t\t\t\t\t$accountingaccount2->fetch('',$object->accountancy_code_sell_intra,1);", "\t\t\t\t\t\tprint $accountingaccount2->getNomUrl(0,1,1,'',1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint $object->accountancy_code_sell_intra;\n\t\t\t\t\t}\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy sell code export\n\t\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\t\tprint $langs->trans(\"ProductAccountancySellExportCode\");\n\t\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t\t{\n\t\t\t\t\t$accountingaccount3 = new AccountingAccount($db);\n\t\t\t\t\t$accountingaccount3->fetch('',$object->accountancy_code_sell_export,1);", "\t\t\t\t\tprint $accountingaccount3->getNomUrl(0,1,1,'',1);\n\t\t\t\t} else {\n\t\t\t\t\tprint $object->accountancy_code_sell_export;\n\t\t\t\t}\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", "\t\t\t// Accountancy buy code\n\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\tprint $langs->trans(\"ProductAccountancyBuyCode\");\n\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t{\n\t\t\t\t$accountingaccount4 = new AccountingAccount($db);\n\t\t\t\t$accountingaccount4->fetch('',$object->accountancy_code_buy,1);", "\t\t\t\tprint $accountingaccount4->getNomUrl(0,1,1,'',1);\n\t\t\t} else {\n\t\t\t\tprint $object->accountancy_code_buy;\n\t\t\t}\n\t\t\tprint '</td></tr>';", " // Batch number management (to batch)", " if (! empty($conf->productbatch->enabled)) ", " {\n\t\t\t\tif ($object->isProduct() || ! empty($conf->global->STOCK_SUPPORTS_SERVICES))\n\t\t\t\t{\n \t\tprint '<tr><td>'.$langs->trans(\"ManageLotSerial\").'</td><td colspan=\"2\">';\n \t if (! empty($conf->use_javascript_ajax) && $usercancreate && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {\n \t print ajax_object_onoff($object, 'status_batch', 'tobatch', 'ProductStatusOnBatch', 'ProductStatusNotOnBatch');\n \t } else {\n \t print $object->getLibStatut(0,2);\n \t }\n \t print '</td></tr>';\n\t\t\t\t}\n }", " // Description\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"Description\").'</td><td colspan=\"2\">'.(dol_textishtml($object->description)?$object->description:dol_nl2br($object->description,1,true)).'</td></tr>';", " // Public URL\n print '<tr><td>'.$langs->trans(\"PublicUrl\").'</td><td colspan=\"2\">';\n\t\t\tprint dol_print_url($object->url);\n print '</td></tr>';", " //Parent product.\n if (!empty($conf->variants->enabled) && $object->isProduct()) {", " $combination = new ProductCombination($db);", " if ($combination->fetchByFkProductChild($object->id) > 0) {\n $prodstatic = new Product($db);\n $prodstatic->fetch($combination->fk_product_parent);", " // Parent product\n print '<tr><td>'.$langs->trans(\"ParentProduct\").'</td><td colspan=\"2\">';\n print $prodstatic->getNomUrl(1);\n print '</td></tr>';\n }\n }", " print '</table>';\n print '</div>';\n print '<div class=\"fichehalfright\"><div class=\"ficheaddleft\">';", " print '<div class=\"underbanner clearboth\"></div>';\n print '<table class=\"border tableforfield\" width=\"100%\">';", " // Nature\n if($object->type!= Product::TYPE_SERVICE)\n {\n print '<tr><td class=\"titlefield\">'.$langs->trans(\"Nature\").'</td><td colspan=\"2\">';\n print $object->getLibFinished();\n print '</td></tr>';\n }", " if ($object->isService())\n {\n // Duration\n print '<tr><td class=\"titlefield\">'.$langs->trans(\"Duration\").'</td><td colspan=\"2\">'.$object->duration_value.'&nbsp;';\n if ($object->duration_value > 1)\n {\n $dur=array(\"h\"=>$langs->trans(\"Hours\"),\"d\"=>$langs->trans(\"Days\"),\"w\"=>$langs->trans(\"Weeks\"),\"m\"=>$langs->trans(\"Months\"),\"y\"=>$langs->trans(\"Years\"));\n }\n else if ($object->duration_value > 0)\n {\n $dur=array(\"h\"=>$langs->trans(\"Hour\"),\"d\"=>$langs->trans(\"Day\"),\"w\"=>$langs->trans(\"Week\"),\"m\"=>$langs->trans(\"Month\"),\"y\"=>$langs->trans(\"Year\"));\n }\n print (! empty($object->duration_unit) && isset($dur[$object->duration_unit]) ? $langs->trans($dur[$object->duration_unit]) : '').\"&nbsp;\";", " print '</td></tr>';\n }\n else\n {\n // Weight\n print '<tr><td class=\"titlefield\">'.$langs->trans(\"Weight\").'</td><td colspan=\"2\">';\n if ($object->weight != '')\n {\n print $object->weight.\" \".measuring_units_string($object->weight_units,\"weight\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n if (empty($conf->global->PRODUCT_DISABLE_SIZE))\n {\n // Length\n print '<tr><td>'.$langs->trans(\"Length\").' x '.$langs->trans(\"Width\").' x '.$langs->trans(\"Height\").'</td><td colspan=\"2\">';\n if ($object->length != '' || $object->width != '' || $object->height != '')\n {\n print $object->length;\n if ($object->width) print \" x \".$object->width;\n if ($object->height) print \" x \".$object->height;\n print ' '.measuring_units_string($object->length_units,\"size\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n }\n if (empty($conf->global->PRODUCT_DISABLE_SURFACE))\n {\n // Surface\n print '<tr><td>'.$langs->trans(\"Surface\").'</td><td colspan=\"2\">';\n if ($object->surface != '')\n {\n print $object->surface.\" \".measuring_units_string($object->surface_units,\"surface\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n }\n if (empty($conf->global->PRODUCT_DISABLE_VOLUME))\n {\n // Volume\n print '<tr><td>'.$langs->trans(\"Volume\").'</td><td colspan=\"2\">';\n if ($object->volume != '')\n {\n print $object->volume.\" \".measuring_units_string($object->volume_units,\"volume\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n }\n }", "\t\t\t// Unit\n\t\t\tif (! empty($conf->global->PRODUCT_USE_UNITS))\n\t\t\t{\n\t\t\t\t$unit = $object->getLabelOfUnit();", "\t\t\t\tprint '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td><td>';\n\t\t\t\tif ($unit !== '') {\n\t\t\t\t\tprint $langs->trans($unit);\n\t\t\t\t}\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", " \t// Custom code\n \tif (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO))\n \t{\n\t print '<tr><td>'.$langs->trans(\"CustomCode\").'</td><td colspan=\"2\">'.$object->customcode.'</td>';", " \t// Origin country code\n \tprint '<tr><td>'.$langs->trans(\"CountryOrigin\").'</td><td colspan=\"2\">'.getCountry($object->country_id,0,$db).'</td>';\n \t}", " // Other attributes\n $parameters=array('colspan' => ' colspan=\"'.(2+(($showphoto||$showbarcode)?1:0)).'\"');\n include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';", "\t\t\t// Categories\n\t\t\tif($conf->categorie->enabled) {\n\t\t\t\tprint '<tr><td valign=\"middle\">'.$langs->trans(\"Categories\").'</td><td colspan=\"3\">';\n\t\t\t\tprint $form->showCategories($object->id,'product',1);\n\t\t\t\tprint \"</td></tr>\";\n\t\t\t}", " // Note private\n\t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n\t\t\t{\n \t\t\tprint '<!-- show Note --> '.\"\\n\";\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"NotePrivate\").'</td><td colspan=\"'.(2+(($showphoto||$showbarcode)?1:0)).'\">'.(dol_textishtml($object->note_private)?$object->note_private:dol_nl2br($object->note_private,1,true)).'</td></tr>'.\"\\n\";\n print '<!-- End show Note --> '.\"\\n\";\n\t\t\t}", " print \"</table>\\n\";\n \t\tprint '</div>';", " print '</div></div>';\n print '<div style=\"clear:both\"></div>';", " dol_fiche_end();\n }", " }\n else if ($action != 'create')\n {\n exit;\n }\n}", "// Load object modCodeProduct\n$module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard');\nif (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php')\n{\n $module = substr($module, 0, dol_strlen($module)-4);\n}\n$result=dol_include_once('/core/modules/product/'.$module.'.php');\nif ($result > 0)\n{\n\t$modCodeProduct = new $module();\n}", "$tmpcode='';\nif (! empty($modCodeProduct->code_auto)) $tmpcode=$modCodeProduct->getNextValue($object,$object->type);", "// Define confirmation messages\n$formquestionclone=array(\n\t'text' => $langs->trans(\"ConfirmClone\"),\n array('type' => 'text', 'name' => 'clone_ref','label' => $langs->trans(\"NewRefForClone\"), 'value' => empty($tmpcode) ? $langs->trans(\"CopyOf\").' '.$object->ref : $tmpcode, 'size'=>24),\n array('type' => 'checkbox', 'name' => 'clone_content','label' => $langs->trans(\"CloneContentProduct\"), 'value' => 1),\n array('type' => 'checkbox', 'name' => 'clone_prices', 'label' => $langs->trans(\"ClonePricesProduct\").' ('.$langs->trans(\"FeatureNotYetAvailable\").')', 'value' => 0, 'disabled' => true),\n);\nif (! empty($conf->global->PRODUIT_SOUSPRODUITS))\n{\n $formquestionclone[]=array('type' => 'checkbox', 'name' => 'clone_composition', 'label' => $langs->trans('CloneCompositionProduct'), 'value' => 1);\n}", "// Confirm delete product\nif (($action == 'delete' && (empty($conf->use_javascript_ajax) || ! empty($conf->dol_use_jmobile)))\t// Output when action = clone if jmobile or no js\n\t|| (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)))\t\t\t\t\t\t\t// Always output when not jmobile nor js\n{\n print $form->formconfirm(\"card.php?id=\".$object->id,$langs->trans(\"DeleteProduct\"),$langs->trans(\"ConfirmDeleteProduct\"),\"confirm_delete\",'',0,\"action-delete\");\n}", "// Clone confirmation\nif (($action == 'clone' && (empty($conf->use_javascript_ajax) || ! empty($conf->dol_use_jmobile)))\t\t// Output when action = clone if jmobile or no js\n\t|| (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)))\t\t\t\t\t\t\t// Always output when not jmobile nor js\n{\n print $form->formconfirm($_SERVER[\"PHP_SELF\"].'?id='.$object->id,$langs->trans('CloneProduct'),$langs->trans('ConfirmCloneProduct',$object->ref),'confirm_clone',$formquestionclone,'yes','action-clone',260,600);\n}", "\n/* ************************************************************************** */\n/* */\n/* Barre d'action */\n/* */\n/* ************************************************************************** */\nif ($action != 'create' && $action != 'edit')\n{\n print \"\\n\".'<div class=\"tabsAction\">'.\"\\n\";", " $parameters=array();\n $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n if (empty($reshook))\n\t{\n\t\tif ($usercancreate)\n {\n if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print '<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"'.$_SERVER[\"PHP_SELF\"].'?action=edit&amp;id='.$object->id.'\">'.$langs->trans(\"Modify\").'</a></div>';", " if (! isset($object->no_button_copy) || $object->no_button_copy <> 1)\n {\n if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))\n {\n print '<div class=\"inline-block divButAction\"><span id=\"action-clone\" class=\"butAction\">'.$langs->trans('ToClone').'</span></div>'.\"\\n\";\n }\n else\n \t\t\t{\n print '<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"'.$_SERVER[\"PHP_SELF\"].'?action=clone&amp;id='.$object->id.'\">'.$langs->trans(\"ToClone\").'</a></div>';\n }\n }\n }\n $object_is_used = $object->isObjectUsed($object->id);", " if ($usercandelete)\n {\n if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1))\n {\n if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))\n {\n print '<div class=\"inline-block divButAction\"><span id=\"action-delete\" class=\"butActionDelete\">'.$langs->trans('Delete').'</span></div>'.\"\\n\";\n }\n else\n \t\t\t{\n print '<div class=\"inline-block divButAction\"><a class=\"butActionDelete\" href=\"'.$_SERVER[\"PHP_SELF\"].'?action=delete&amp;id='.$object->id.'\">'.$langs->trans(\"Delete\").'</a></div>';\n }\n }\n else\n \t\t{\n print '<div class=\"inline-block divButAction\"><a class=\"butActionRefused\" href=\"#\" title=\"'.$langs->trans(\"ProductIsUsed\").'\">'.$langs->trans(\"Delete\").'</a></div>';\n }\n }\n else\n \t{\n print '<div class=\"inline-block divButAction\"><a class=\"butActionRefused\" href=\"#\" title=\"'.$langs->trans(\"NotEnoughPermissions\").'\">'.$langs->trans(\"Delete\").'</a></div>';\n }\n }", " print \"\\n</div>\\n\";\n}", "/*\n * All the \"Add to\" areas\n */", "if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == '' || $action == 'view') && $object->status)\n{\n //Variable used to check if any text is going to be printed\n $html = '';\n\t//print '<div class=\"fichecenter\"><div class=\"fichehalfleft\">';", " // Propals\n if (! empty($conf->propal->enabled) && $user->rights->propale->creer)\n {\n $propal = new Propal($db);", " $langs->load(\"propal\");", " $otherprop = $propal->liste_array(2,1,0);", " if (is_array($otherprop) && count($otherprop))\n {\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftProposals\").'</td><td>';\n \t$html .= $form->selectarray(\"propalid\", $otherprop, 0, 1);\n \t$html .= '</td></tr>';\n }\n else\n {\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftProposals\").'</td><td>';\n \t$html .= $langs->trans(\"NoDraftProposals\");\n \t$html .= '</td></tr>';\n }\n }", " // Commande\n if (! empty($conf->commande->enabled) && $user->rights->commande->creer)\n {\n $commande = new Commande($db);", " $langs->load(\"orders\");", " $othercom = $commande->liste_array(2, 1, null);\n if (is_array($othercom) && count($othercom))\n {\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftOrders\").'</td><td>';\n \t$html .= $form->selectarray(\"commandeid\", $othercom, 0, 1);\n \t$html .= '</td></tr>';\n }\n else\n\t\t{\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftOrders\").'</td><td>';\n \t$html .= $langs->trans(\"NoDraftOrders\");\n \t$html .= '</td></tr>';\n }\n }", " // Factures\n if (! empty($conf->facture->enabled) && $user->rights->facture->creer)\n {\n \t$invoice = new Facture($db);", " \t$langs->load(\"bills\");", " \t$otherinvoice = $invoice->liste_array(2, 1, null);\n \tif (is_array($otherinvoice) && count($otherinvoice))\n \t{\n \t\t$html .= '<tr><td style=\"width: 200px;\">';\n \t\t$html .= $langs->trans(\"AddToDraftInvoices\").'</td><td>';\n \t\t$html .= $form->selectarray(\"factureid\", $otherinvoice, 0, 1);\n \t\t$html .= '</td></tr>';\n \t}\n \telse\n \t{\n \t\t$html .= '<tr><td style=\"width: 200px;\">';\n \t\t$html .= $langs->trans(\"AddToDraftInvoices\").'</td><td>';\n \t\t$html .= $langs->trans(\"NoDraftInvoices\");\n \t\t$html .= '</td></tr>';\n \t}\n }", " //If any text is going to be printed, then we show the table\n if (!empty($html))\n {\n\t print '<form method=\"POST\" action=\"'.$_SERVER[\"PHP_SELF\"].'?id='.$object->id.'\">';\n \tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n \tprint '<input type=\"hidden\" name=\"action\" value=\"addin\">';", "\t print load_fiche_titre($langs->trans(\"AddToDraft\"),'','');", "\t\tdol_fiche_head('');", " \t$html .= '<tr><td class=\"nowrap\">'.$langs->trans(\"Quantity\").' ';\n \t$html .= '<input type=\"text\" class=\"flat\" name=\"qty\" size=\"1\" value=\"1\"></td>';\n $html .= '<td class=\"nowrap\">'.$langs->trans(\"ReductionShort\").'(%) ';\n \t$html .= '<input type=\"text\" class=\"flat\" name=\"remise_percent\" size=\"1\" value=\"0\">';\n \t$html .= '</td></tr>';", " \tprint '<table width=\"100%\" class=\"border\">';\n print $html;\n print '</table>';", " print '<div class=\"center\">';\n print '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Add\").'\">';\n print '</div>';", " dol_fiche_end();", " print '</form>';\n }\n}", "\n/*\n * Documents generes\n */", "if ($action != 'create' && $action != 'edit' && $action != 'delete')\n{\n print '<div class=\"fichecenter\"><div class=\"fichehalfleft\">';\n print '<a name=\"builddoc\"></a>'; // ancre", " // Documents\n $objectref = dol_sanitizeFileName($object->ref);\n $relativepath = $comref . '/' . $objectref . '.pdf';\n $filedir = $conf->produit->dir_output . '/' . $objectref;\n $urlsource=$_SERVER[\"PHP_SELF\"].\"?id=\".$object->id;\n $genallowed=$usercanread;\n $delallowed=$usercancreate;", " $var=true;", " print $formfile->showdocuments($modulepart,$object->ref,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$object->default_lang, '', $object);\n $somethingshown=$formfile->numoffiles;", " print '</div><div class=\"fichehalfright\"><div class=\"ficheaddleft\">';", " $MAXEVENT = 10;", " $morehtmlright = '<a href=\"'.DOL_URL_ROOT.'/product/agenda.php?id='.$object->id.'\">';\n $morehtmlright.= $langs->trans(\"SeeAll\");\n $morehtmlright.= '</a>';", " // List of actions on element\n include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';\n $formactions = new FormActions($db);\n $somethingshown = $formactions->showactions($object, 'product', 0, 1, '', $MAXEVENT, '', $morehtmlright);\t\t// Show all action for product", " print '</div></div></div>';\n}", "\nllxFooter();\n$db->close();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (C) 2001-2007\tRodolphe Quiedeville\t<rodolphe@quiedeville.org>\n * Copyright (C) 2004-2016\tLaurent Destailleur\t\t<eldy@users.sourceforge.net>\n * Copyright (C) 2005\t\tEric Seigne\t\t\t\t<eric.seigne@ryxeo.com>\n * Copyright (C) 2005-2015\tRegis Houssin\t\t\t<regis.houssin@capnetworks.com>\n * Copyright (C) 2006\t\tAndre Cianfarani\t\t<acianfa@free.fr>\n * Copyright (C) 2006\t\tAuguria SARL\t\t\t<info@auguria.org>\n * Copyright (C) 2010-2015\tJuanjo Menent\t\t\t<jmenent@2byte.es>\n * Copyright (C) 2013-2016\tMarcos GarcΓ­a\t\t\t<marcosgdf@gmail.com>\n * Copyright (C) 2012-2013\tCΓ©dric Salvador\t\t\t<csalvador@gpcsolutions.fr>\n * Copyright (C) 2011-2017\tAlexandre Spangaro\t\t<aspangaro@zendsi.com>\n * Copyright (C) 2014\t\tCΓ©dric Gross\t\t\t<c.gross@kreiz-it.fr>\n * Copyright (C) 2014-2015\tFerran Marcet\t\t\t<fmarcet@2byte.es>\n * Copyright (C) 2015\t\tJean-FranΓ§ois Ferry\t\t<jfefe@aternatik.fr>\n * Copyright (C) 2015\t\tRaphaΓ«l Doursenaud\t\t<rdoursenaud@gpcsolutions.fr>\n * Copyright (C) 2016\t\tCharlie Benke\t\t\t<charlie@patas-monkey.com>\n * Copyright (C) 2016\t\tMeziane Sof\t\t\t\t<virtualsof@yahoo.fr>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n * \\file htdocs/product/card.php\n * \\ingroup product\n * \\brief Page to show product\n */", "require '../main.inc.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';\nrequire_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';\nrequire_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.php';", "if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';\nif (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';\nif (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';\nif (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';\nif (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';\nif (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';", "$langs->load(\"products\");\n$langs->load(\"other\");\nif (! empty($conf->stock->enabled)) $langs->load(\"stocks\");\nif (! empty($conf->facture->enabled)) $langs->load(\"bills\");\nif (! empty($conf->productbatch->enabled)) $langs->load(\"productbatch\");", "$mesg=''; $error=0; $errors=array();", "$refalreadyexists=0;", "$id=GETPOST('id', 'int');\n$ref=GETPOST('ref', 'alpha');\n$type=GETPOST('type','int');\n$action=(GETPOST('action','alpha') ? GETPOST('action','alpha') : 'view');\n$cancel=GETPOST('cancel','alpha');\n$confirm=GETPOST('confirm','alpha');\n$socid=GETPOST('socid','int');\n$duration_value = GETPOST('duration_value');\n$duration_unit = GETPOST('duration_unit');\nif (! empty($user->societe_id)) $socid=$user->societe_id;", "$object = new Product($db);\n$object->type = $type;\t// so test later to fill $usercancxxx is correct\n$extrafields = new ExtraFields($db);", "// fetch optionals attributes and labels\n$extralabels=$extrafields->fetch_name_optionals_label($object->table_element);", "if ($id > 0 || ! empty($ref))\n{\n $result = $object->fetch($id, $ref);", " if (! empty($conf->product->enabled)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref);\n elseif (! empty($conf->service->enabled)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product').dol_sanitizeFileName($object->ref);", " if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) // For backward compatiblity, we scan also old dirs\n {\n if (! empty($conf->product->enabled)) $upload_dirold = $conf->product->multidir_output[$object->entity].'/'.substr(substr(\"000\".$object->id, -2),1,1).'/'.substr(substr(\"000\".$object->id, -2),0,1).'/'.$object->id.\"/photos\";\n else $upload_dirold = $conf->service->multidir_output[$object->entity].'/'.substr(substr(\"000\".$object->id, -2),1,1).'/'.substr(substr(\"000\".$object->id, -2),0,1).'/'.$object->id.\"/photos\";\n }\n}", "$modulepart='product';", "// Get object canvas (By default, this is not defined, so standard usage of dolibarr)\n$canvas = !empty($object->canvas)?$object->canvas:GETPOST(\"canvas\");\n$objcanvas=null;\nif (! empty($canvas))\n{\n require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php';\n $objcanvas = new Canvas($db,$action);\n $objcanvas->getCanvas('product','card',$canvas);\n}", "// Security check\n$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : ''));\n$fieldtype = (! empty($id) ? 'rowid' : 'ref');\n$result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype,$objcanvas);", "// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context\n$hookmanager->initHooks(array('productcard','globalcard'));", "", "/*\n * Actions\n */", "if ($cancel) $action = '';", "$usercanread = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->lire) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->lire));\n$usercancreate = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->creer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->creer));\n$usercandelete = (($object->type == Product::TYPE_PRODUCT && $user->rights->produit->supprimer) || ($object->type == Product::TYPE_SERVICE && $user->rights->service->supprimer));\n$createbarcode=empty($conf->barcode->enabled)?0:1;\nif (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->creer_advance)) $createbarcode=0;", "$parameters=array('id'=>$id, 'ref'=>$ref, 'objcanvas'=>$objcanvas);\n$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks\nif ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');", "if (empty($reshook))\n{\n // Type\n\tif ($action == 'setfk_product_type' && $usercancreate)\n {\n \t$result = $object->setValueFrom('fk_product_type', GETPOST('fk_product_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY');\n \theader(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$object->id);\n \texit;\n }", " // Actions to build doc\n $upload_dir = $conf->produit->dir_output;\n $permissioncreate = $usercancreate;\n include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';", " include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';", " // Barcode type\n if ($action ==\t'setfk_barcode_type' && $createbarcode)\n {\n $result = $object->setValueFrom('fk_barcode_type', GETPOST('fk_barcode_type'), '', null, 'text', '', $user, 'PRODUCT_MODIFY');\n \theader(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$object->id);\n \texit;\n }", " // Barcode value\n if ($action ==\t'setbarcode' && $createbarcode)\n {\n \t$result=$object->check_barcode(GETPOST('barcode'),GETPOST('barcode_type_code'));", "\t\tif ($result >= 0)\n\t\t{\n\t \t$result = $object->setValueFrom('barcode', GETPOST('barcode'));\n\t \theader(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$object->id);\n\t \texit;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t$langs->load(\"errors\");\n \tif ($result == -1) $errors[] = 'ErrorBadBarCodeSyntax';\n \telse if ($result == -2) $errors[] = 'ErrorBarCodeRequired';\n \telse if ($result == -3) $errors[] = 'ErrorBarCodeAlreadyUsed';\n \telse $errors[] = 'FailedToValidateBarCode';", "\t\t\t$error++;\n\t\t\tsetEventMessages($errors, null, 'errors');\n\t\t}\n }", " // Add a product or service\n if ($action == 'add' && $usercancreate)\n {\n $error=0;", " if (! GETPOST('label'))\n {\n setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Label')), null, 'errors');\n $action = \"create\";\n $error++;\n }\n if (empty($ref))\n {\n setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Ref')), null, 'errors');\n $action = \"create\";\n $error++;\n }\n if (! empty($duration_value) && empty($duration_unit))\n {\n setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Unit')), null, 'errors');\n $action = \"create\";\n $error++;\n }", " if (! $error)\n {\n\t $units = GETPOST('units', 'int');", " $object->ref = $ref;\n $object->label = GETPOST('label');\n $object->price_base_type = GETPOST('price_base_type');", " if ($object->price_base_type == 'TTC')\n \t$object->price_ttc = GETPOST('price');\n else\n \t$object->price = GETPOST('price');\n if ($object->price_base_type == 'TTC')\n \t$object->price_min_ttc = GETPOST('price_min');\n else\n \t$object->price_min = GETPOST('price_min');", "\t $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)'", "\t // We must define tva_tx, npr and local taxes\n\t $vatratecode = '';\n\t $tva_tx = preg_replace('/[^0-9\\.].*$/', '', $tva_tx_txt); // keep remove all after the numbers and dot\n\t $npr = preg_match('/\\*/', $tva_tx_txt) ? 1 : 0;\n\t $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0';\n\t // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes\n\t if (preg_match('/\\((.*)\\)/', $tva_tx_txt, $reg))\n\t {\n\t // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in update price.\n\t $vatratecode=$reg[1];\n\t // Get record from code\n\t $sql = \"SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type\";\n\t $sql.= \" FROM \".MAIN_DB_PREFIX.\"c_tva as t, \".MAIN_DB_PREFIX.\"c_country as c\";\n\t $sql.= \" WHERE t.fk_pays = c.rowid AND c.code = '\".$mysoc->country_code.\"'\";\n\t $sql.= \" AND t.taux = \".((float) $tva_tx).\" AND t.active = 1\";\n\t $sql.= \" AND t.code ='\".$vatratecode.\"'\";\n\t $resql=$db->query($sql);\n\t if ($resql)\n\t {\n\t $obj = $db->fetch_object($resql);\n\t $npr = $obj->recuperableonly;\n\t $localtax1 = $obj->localtax1;\n\t $localtax2 = $obj->localtax2;\n\t $localtax1_type = $obj->localtax1_type;\n\t $localtax2_type = $obj->localtax2_type;\n\t }\n\t }", "\t $object->default_vat_code = $vatratecode;\n\t $object->tva_tx = $tva_tx;\n\t $object->tva_npr = $npr;\n\t $object->localtax1_tx = $localtax1;\n\t $object->localtax2_tx = $localtax2;\n\t $object->localtax1_type = $localtax1_type;\n\t $object->localtax2_type = $localtax2_type;", " $object->type \t = $type;\n $object->status \t = GETPOST('statut');\n $object->status_buy = GETPOST('statut_buy');\n\t\t\t$object->status_batch \t= GETPOST('status_batch');", " $object->barcode_type = GETPOST('fk_barcode_type');\n $object->barcode\t\t = GETPOST('barcode');\n // Set barcode_type_xxx from barcode_type id\n $stdobject=new GenericObject($db);\n \t $stdobject->element='product';\n $stdobject->barcode_type=GETPOST('fk_barcode_type');\n $result=$stdobject->fetch_barcode();\n if ($result < 0)\n {\n \t$error++;\n \t$mesg='Failed to get bar code type information ';\n \tsetEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors');\n }\n $object->barcode_type_code = $stdobject->barcode_type_code;\n $object->barcode_type_coder = $stdobject->barcode_type_coder;\n $object->barcode_type_label = $stdobject->barcode_type_label;", " $object->description \t = dol_htmlcleanlastbr(GETPOST('desc','none'));\n $object->url\t\t\t\t\t = GETPOST('url');\n $object->note_private \t = dol_htmlcleanlastbr(GETPOST('note_private','none'));\n $object->note \t = $object->note_private; // deprecated", " $object->customcode = GETPOST('customcode','alpha');\n $object->country_id = GETPOST('country_id','int');", " $object->duration_value \t = $duration_value;\n $object->duration_unit \t = $duration_unit;\n $object->seuil_stock_alerte \t = GETPOST('seuil_stock_alerte')?GETPOST('seuil_stock_alerte'):0;\n $object->desiredstock = GETPOST('desiredstock')?GETPOST('desiredstock'):0;\n $object->canvas \t = GETPOST('canvas');\n $object->weight \t = GETPOST('weight');\n $object->weight_units \t = GETPOST('weight_units');\n $object->length \t = GETPOST('size');\n $object->length_units \t = GETPOST('size_units');\n $object->width \t = GETPOST('sizewidth');\n $object->height \t = GETPOST('sizeheight');\n\t $object->surface \t = GETPOST('surface');\n $object->surface_units \t = GETPOST('surface_units');\n $object->volume \t = GETPOST('volume');\n $object->volume_units \t = GETPOST('volume_units');", " $object->finished \t = GETPOST('finished','alpha');\n $object->fk_unit = GETPOST('units','alpha');", "\t $accountancy_code_sell \t\t\t = GETPOST('accountancy_code_sell','alpha');\n\t $accountancy_code_sell_intra\t = GETPOST('accountancy_code_sell_intra','alpha');\n\t $accountancy_code_sell_export\t = GETPOST('accountancy_code_sell_export','alpha');\n\t $accountancy_code_buy \t\t\t = GETPOST('accountancy_code_buy','alpha');", "\n\t\t\tif ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; }\n\t\t\tif ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; }\n\t\t\tif ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; }\n\t\t\tif ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; }", " // MultiPrix\n if (! empty($conf->global->PRODUIT_MULTIPRICES))\n {\n for($i=2;$i<=$conf->global->PRODUIT_MULTIPRICES_LIMIT;$i++)\n {\n if (isset($_POST[\"price_\".$i]))\n {\n $object->multiprices[\"$i\"] = price2num($_POST[\"price_\".$i],'MU');\n $object->multiprices_base_type[\"$i\"] = $_POST[\"multiprices_base_type_\".$i];\n }\n else\n {\n $object->multiprices[\"$i\"] = \"\";\n }\n }\n }", " // Fill array 'array_options' with data from add form\n \t$ret = $extrafields->setOptionalsFromPost($extralabels,$object);\n\t\t\tif ($ret < 0) $error++;", "\t\t\tif (! $error)\n\t\t\t{\n \t$id = $object->create($user);\n\t\t\t}", " if ($id > 0)\n {\n\t\t\t\t// Category association\n\t\t\t\t$categories = GETPOST('categories', 'array');\n\t\t\t\t$object->setCategories($categories);", " header(\"Location: \".$_SERVER['PHP_SELF'].\"?id=\".$id);\n exit;\n }\n else\n\t\t\t{\n \tif (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors');\n\t\t\t\telse setEventMessages($langs->trans($object->error), null, 'errors');\n $action = \"create\";\n }\n }\n }", " // Update a product or service\n if ($action == 'update' && $usercancreate)\n {\n \tif (GETPOST('cancel','alpha'))\n {\n $action = '';\n }\n else\n {\n if ($object->id > 0)\n {\n\t\t\t\t$object->oldcopy= clone $object;", " $object->ref = $ref;\n $object->label = GETPOST('label');\n $object->description = dol_htmlcleanlastbr(GETPOST('desc','none'));\n \t$object->url\t\t\t\t\t= GETPOST('url');\n \t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n \t\t\t{\n \t$object->note_private = dol_htmlcleanlastbr(GETPOST('note_private','none'));\n $object->note = $object->note_private;\n \t\t\t}", " $object->customcode = GETPOST('customcode','alpha');\n $object->country_id = GETPOST('country_id','int');\n $object->status = GETPOST('statut','int');\n $object->status_buy = GETPOST('statut_buy','int');\n $object->status_batch\t = GETPOST('status_batch','aZ09');", " // removed from update view so GETPOST always empty\n /*\n $object->seuil_stock_alerte = GETPOST('seuil_stock_alerte');\n $object->desiredstock = GETPOST('desiredstock');\n */\n $object->duration_value = GETPOST('duration_value');\n $object->duration_unit = GETPOST('duration_unit');", " $object->canvas = GETPOST('canvas');\n $object->weight = GETPOST('weight');\n $object->weight_units = GETPOST('weight_units');\n $object->length = GETPOST('size');\n $object->length_units = GETPOST('size_units');\n $object->width \t = GETPOST('sizewidth');\n $object->height \t = GETPOST('sizeheight');", " $object->surface = GETPOST('surface');\n $object->surface_units = GETPOST('surface_units');\n $object->volume = GETPOST('volume');\n $object->volume_units = GETPOST('volume_units');", " $object->finished = GETPOST('finished','alpha');", "\n\t $units = GETPOST('units', 'int');", "\t if ($units > 0) {\n\t\t $object->fk_unit = $units;\n\t } else {\n\t\t $object->fk_unit = null;\n\t }", "\t $object->barcode_type = GETPOST('fk_barcode_type');\n \t $object->barcode\t\t = GETPOST('barcode');\n \t // Set barcode_type_xxx from barcode_type id\n \t $stdobject=new GenericObject($db);\n \t $stdobject->element='product';\n \t $stdobject->barcode_type=GETPOST('fk_barcode_type');\n \t $result=$stdobject->fetch_barcode();\n \t if ($result < 0)\n \t {\n \t \t$error++;\n \t \t$mesg='Failed to get bar code type information ';\n \t\tsetEventMessages($mesg.$stdobject->error, $mesg.$stdobject->errors, 'errors');\n \t }\n \t $object->barcode_type_code = $stdobject->barcode_type_code;\n \t $object->barcode_type_coder = $stdobject->barcode_type_coder;\n \t $object->barcode_type_label = $stdobject->barcode_type_label;\n", " \t $accountancy_code_sell \t\t\t = GETPOST('accountancy_code_sell','alpha');\n \t $accountancy_code_sell_intra\t = GETPOST('accountancy_code_sell_intra','alpha');\n \t $accountancy_code_sell_export\t = GETPOST('accountancy_code_sell_export','alpha');\n \t $accountancy_code_buy \t\t\t = GETPOST('accountancy_code_buy','alpha');", "\n\t\t\t\tif ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; }\n\t\t\t\tif ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; }\n\t\t\t\tif ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; }\n\t\t\t\tif ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; }", " // Fill array 'array_options' with data from add form\n \t\t$ret = $extrafields->setOptionalsFromPost($extralabels,$object);\n\t\t\t\tif ($ret < 0) $error++;", " if (! $error && $object->check())\n {\n if ($object->update($object->id, $user) > 0)\n {\n\t\t\t\t\t\t// Category association\n\t\t\t\t\t\t$categories = GETPOST('categories', 'array');\n\t\t\t\t\t\t$object->setCategories($categories);", " $action = 'view';\n }\n else\n\t\t\t\t\t{\n\t\t\t\t\t\tif (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors');\n \telse setEventMessages($langs->trans($object->error), null, 'errors');\n $action = 'edit';\n }\n }\n else\n\t\t\t\t{\n\t\t\t\t\tif (count($object->errors)) setEventMessages($object->error, $object->errors, 'errors');\n \telse setEventMessages($langs->trans(\"ErrorProductBadRefOrLabel\"), null, 'errors');\n $action = 'edit';\n }\n }", " }\n }", " // Action clone object\n if ($action == 'confirm_clone' && $confirm != 'yes') { $action=''; }\n if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate)\n {\n if (! GETPOST('clone_content') && ! GETPOST('clone_prices') )\n {\n \tsetEventMessages($langs->trans(\"NoCloneOptionsSpecified\"), null, 'errors');\n }\n else\n {\n $db->begin();", " $originalId = $id;\n if ($object->id > 0)\n {\n $object->ref = GETPOST('clone_ref');\n $object->status = 0;\n $object->status_buy = 0;\n $object->id = null;\n $object->barcode = -1;", " if ($object->check())\n {\n $id = $object->create($user);\n if ($id > 0)\n {\n if (GETPOST('clone_composition'))\n {\n $result = $object->clone_associations($originalId, $id);", " if ($result < 1)\n {\n $db->rollback();\n setEventMessages($langs->trans('ErrorProductClone'), null, 'errors');\n header(\"Location: \".$_SERVER[\"PHP_SELF\"].\"?id=\".$originalId);\n exit;\n }\n }", " // $object->clone_fournisseurs($originalId, $id);", " $db->commit();\n $db->close();", " header(\"Location: \".$_SERVER[\"PHP_SELF\"].\"?id=\".$id);\n exit;\n }\n else\n {\n $id=$originalId;", " if ($object->error == 'ErrorProductAlreadyExists')\n {\n $db->rollback();", " $refalreadyexists++;\n $action = \"\";", " $mesg=$langs->trans(\"ErrorProductAlreadyExists\",$object->ref);\n $mesg.=' <a href=\"'.$_SERVER[\"PHP_SELF\"].'?ref='.$object->ref.'\">'.$langs->trans(\"ShowCardHere\").'</a>.';\n setEventMessages($mesg, null, 'errors');\n $object->fetch($id);\n }\n else\n {\n $db->rollback();\n if (count($object->errors))\n {\n \tsetEventMessages($object->error, $object->errors, 'errors');\n \tdol_print_error($db,$object->errors);\n }\n else\n {\n \tsetEventMessages($langs->trans($object->error), null, 'errors');\n \tdol_print_error($db,$object->error);\n }\n }\n }\n }\n }\n else\n {\n $db->rollback();\n dol_print_error($db,$object->error);\n }\n }\n }", " // Delete a product\n if ($action == 'confirm_delete' && $confirm != 'yes') { $action=''; }\n if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete)\n\t{\n\t\t$result = $object->delete($user);", " if ($result > 0)\n {\n header('Location: '.DOL_URL_ROOT.'/product/list.php?type='.$object->type.'&delprod='.urlencode($object->ref));\n exit;\n }\n else\n {\n \tsetEventMessages($langs->trans($object->error), null, 'errors');\n $reload = 0;\n $action='';\n }\n }", "\n // Add product into object\n if ($object->id > 0 && $action == 'addin')\n {\n $thirpdartyid =0 ;\n if (GETPOST('propalid') > 0)\n {\n \t$propal = new Propal($db);\n\t $result=$propal->fetch(GETPOST('propalid'));\n\t if ($result <= 0)\n\t {\n\t dol_print_error($db,$propal->error);\n\t exit;\n\t }\n\t $thirpdartyid = $propal->socid;\n }\n elseif (GETPOST('commandeid') > 0)\n {\n $commande = new Commande($db);\n\t $result=$commande->fetch(GETPOST('commandeid'));\n\t if ($result <= 0)\n\t {\n\t dol_print_error($db,$commande->error);\n\t exit;\n\t }\n\t $thirpdartyid = $commande->socid;\n }\n elseif (GETPOST('factureid') > 0)\n {\n \t $facture = new Facture($db);\n\t $result=$facture->fetch(GETPOST('factureid'));\n\t if ($result <= 0)\n\t {\n\t dol_print_error($db,$facture->error);\n\t exit;\n\t }\n\t $thirpdartyid = $facture->socid;\n }", " if ( $thirpdartyid > 0) {\n $soc = new Societe($db);\n $result = $soc->fetch($thirpdartyid);\n if ($result <= 0) {\n dol_print_error($db, $soc->error);\n exit;\n }", " $desc = $object->description;", " $tva_tx = get_default_tva($mysoc, $soc, $object->id);\n $tva_npr = get_default_npr($mysoc, $soc, $object->id);\n if (empty($tva_tx)) $tva_npr=0;\n $localtax1_tx = get_localtax($tva_tx, 1, $soc, $mysoc, $tva_npr);\n $localtax2_tx = get_localtax($tva_tx, 2, $soc, $mysoc, $tva_npr);", " $pu_ht = $object->price;\n $pu_ttc = $object->price_ttc;\n $price_base_type = $object->price_base_type;", " // If multiprice\n if ($conf->global->PRODUIT_MULTIPRICES && $soc->price_level) {\n $pu_ht = $object->multiprices[$soc->price_level];\n $pu_ttc = $object->multiprices_ttc[$soc->price_level];\n $price_base_type = $object->multiprices_base_type[$soc->price_level];\n } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {\n require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';", " $prodcustprice = new Productcustomerprice($db);", " $filter = array('t.fk_product' => $object->id, 't.fk_soc' => $soc->id);", " $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);\n if ($result) {\n if (count($prodcustprice->lines) > 0) {\n $pu_ht = price($prodcustprice->lines [0]->price);\n $pu_ttc = price($prodcustprice->lines [0]->price_ttc);\n $price_base_type = $prodcustprice->lines [0]->price_base_type;\n $tva_tx = $prodcustprice->lines [0]->tva_tx;\n }\n }\n }", "\t\t\t$tmpvat = price2num(preg_replace('/\\s*\\(.*\\)/', '', $tva_tx));\n\t\t\t$tmpprodvat = price2num(preg_replace('/\\s*\\(.*\\)/', '', $prod->tva_tx));", " // On reevalue prix selon taux tva car taux tva transaction peut etre different\n // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).\n if ($tmpvat != $tmpprodvat) {\n if ($price_base_type != 'HT') {\n $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');\n } else {\n $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');\n }\n }", " if (GETPOST('propalid') > 0) {\n // Define cost price for margin calculation\n $buyprice=0;\n if (($result = $propal->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0)\n {\n dol_syslog($langs->trans('FailedToGetCostPrice'));\n setEventMessage($langs->trans('FailedToGetCostPrice'), 'errors');\n }\n else\n {\n $buyprice = $result;\n }", " $result = $propal->addline(\n $desc,\n $pu_ht,\n GETPOST('qty'),\n $tva_tx,\n $localtax1_tx, // localtax1\n $localtax2_tx, // localtax2\n $object->id,\n GETPOST('remise_percent'),\n $price_base_type,\n $pu_ttc,\n 0,\n 0,\n -1,\n 0,\n 0,\n 0,\n $buyprice,\n '',\n '',\n '',\n 0,\n $object->fk_unit\n );\n if ($result > 0) {\n header(\"Location: \" . DOL_URL_ROOT . \"/comm/propal/card.php?id=\" . $propal->id);\n return;\n }", " setEventMessages($langs->trans(\"ErrorUnknown\") . \": $result\", null, 'errors');\n } elseif (GETPOST('commandeid') > 0) {\n // Define cost price for margin calculation\n $buyprice=0;\n if (($result = $commande->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0)\n {\n dol_syslog($langs->trans('FailedToGetCostPrice'));\n setEventMessage($langs->trans('FailedToGetCostPrice'), 'errors');\n }\n else\n {\n $buyprice = $result;\n }", " $result = $commande->addline(\n $desc,\n $pu_ht,\n GETPOST('qty'),\n $tva_tx,\n $localtax1_tx, // localtax1\n $localtax2_tx, // localtax2\n $object->id,\n GETPOST('remise_percent'),\n '',\n '',\n $price_base_type,\n $pu_ttc,\n '',\n '',\n 0,\n -1,\n 0,\n 0,\n null,\n $buyprice,\n '',\n 0,\n $object->fk_unit\n );", " if ($result > 0) {\n header(\"Location: \" . DOL_URL_ROOT . \"/commande/card.php?id=\" . $commande->id);\n exit;\n }\n } elseif (GETPOST('factureid') > 0) {\n // Define cost price for margin calculation\n $buyprice=0;\n if (($result = $facture->defineBuyPrice($pu_ht, GETPOST('remise_percent'), $object->id)) < 0)\n {\n dol_syslog($langs->trans('FailedToGetCostPrice'));\n setEventMessage($langs->trans('FailedToGetCostPrice'), 'errors');\n }\n else\n {\n $buyprice = $result;\n }", " $result = $facture->addline(\n $desc,\n $pu_ht,\n GETPOST('qty'),\n $tva_tx,\n $localtax1_tx,\n $localtax2_tx,\n $object->id,\n GETPOST('remise_percent'),\n '',\n '',\n '',\n '',\n '',\n $price_base_type,\n $pu_ttc,\n Facture::TYPE_STANDARD,\n -1,\n 0,\n '',\n 0,\n 0,\n null,\n $buyprice,\n '',\n 0,\n 100,\n '',\n $object->fk_unit\n );", " if ($result > 0) {\n header(\"Location: \" . DOL_URL_ROOT . \"/compta/facture/card.php?facid=\" . $facture->id);\n exit;\n }\n }\n }\n else {\n $action=\"\";\n setEventMessages($langs->trans(\"WarningSelectOneDocument\"), null, 'warnings');\n }\n }\n}", "", "/*\n * View\n */", "$title = $langs->trans('ProductServiceCard');\n$helpurl = '';\n$shortlabel = dol_trunc($object->label,16);\nif (GETPOST(\"type\") == '0' || ($object->type == Product::TYPE_PRODUCT))\n{\n\t$title = $langs->trans('Product').\" \". $shortlabel .\" - \".$langs->trans('Card');\n\t$helpurl='EN:Module_Products|FR:Module_Produits|ES:M&oacute;dulo_Productos';\n}\nif (GETPOST(\"type\") == '1' || ($object->type == Product::TYPE_SERVICE))\n{\n\t$title = $langs->trans('Service').\" \". $shortlabel .\" - \".$langs->trans('Card');\n\t$helpurl='EN:Module_Services_En|FR:Module_Services|ES:M&oacute;dulo_Servicios';\n}", "llxHeader('', $title, $helpurl);", "$form = new Form($db);\n$formfile = new FormFile($db);\n$formproduct = new FormProduct($db);\nif (! empty($conf->accounting->enabled)) $formaccounting = new FormAccounting($db);", "// Load object modBarCodeProduct\n$res=0;\nif (! empty($conf->barcode->enabled) && ! empty($conf->global->BARCODE_PRODUCT_ADDON_NUM))\n{\n\t$module=strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);\n\t$dirbarcode=array_merge(array('/core/modules/barcode/'),$conf->modules_parts['barcode']);\n\tforeach ($dirbarcode as $dirroot)\n\t{\n\t\t$res=dol_include_once($dirroot.$module.'.php');\n\t\tif ($res) break;\n\t}\n\tif ($res > 0)\n\t{\n\t\t\t$modBarCodeProduct =new $module();\n\t}\n}", "\nif (is_object($objcanvas) && $objcanvas->displayCanvasExists($action))\n{\n\t// -----------------------------------------\n\t// When used with CANVAS\n\t// -----------------------------------------\n\tif (empty($object->error) && $id)\n\t{\n\t\t$object = new Product($db);\n\t\t$result=$object->fetch($id);\n\t\tif ($result <= 0) dol_print_error('',$object->error);\n\t}\n\t$objcanvas->assign_values($action, $object->id, $object->ref);\t// Set value for templates\n\t$objcanvas->display_canvas($action);\t\t\t\t\t\t\t// Show template\n}\nelse\n{\n // -----------------------------------------\n // When used in standard mode\n // -----------------------------------------\n\tif ($action == 'create' && $usercancreate)\n {\n //WYSIWYG Editor\n require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';", "\t\t// Load object modCodeProduct\n $module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard');\n if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php')\n {\n $module = substr($module, 0, dol_strlen($module)-4);\n }\n $result=dol_include_once('/core/modules/product/'.$module.'.php');\n if ($result > 0)\n {\n \t$modCodeProduct = new $module();\n }", " dol_set_focus('input[name=\"ref\"]');", " print '<form action=\"'.$_SERVER[\"PHP_SELF\"].'\" method=\"POST\">';\n print '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n print '<input type=\"hidden\" name=\"action\" value=\"add\">';\n print '<input type=\"hidden\" name=\"type\" value=\"'.$type.'\">'.\"\\n\";\n\t\tif (! empty($modCodeProduct->code_auto))\n\t\t\tprint '<input type=\"hidden\" name=\"code_auto\" value=\"1\">';\n\t\tif (! empty($modBarCodeProduct->code_auto))\n\t\t\tprint '<input type=\"hidden\" name=\"barcode_auto\" value=\"1\">';", " if ($type==1) $title=$langs->trans(\"NewService\");\n else $title=$langs->trans(\"NewProduct\");\n $linkback=\"\";\n print load_fiche_titre($title,$linkback,'title_products.png');", " dol_fiche_head('');", " print '<table class=\"border centpercent\">';", " print '<tr>';\n $tmpcode='';\n\t\tif (! empty($modCodeProduct->code_auto)) $tmpcode=$modCodeProduct->getNextValue($object,$type);\n print '<td class=\"titlefieldcreate fieldrequired\">'.$langs->trans(\"Ref\").'</td><td colspan=\"3\"><input id=\"ref\" name=\"ref\" class=\"maxwidth200\" maxlength=\"128\" value=\"'.dol_escape_htmltag(GETPOST('ref')?GETPOST('ref'):$tmpcode).'\">';\n if ($refalreadyexists)\n {\n print $langs->trans(\"RefAlreadyExists\");\n }\n print '</td></tr>';", " // Label\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Label\").'</td><td colspan=\"3\"><input name=\"label\" class=\"minwidth300 maxwidth400onsmartphone\" maxlength=\"255\" value=\"'.dol_escape_htmltag(GETPOST('label')).'\"></td></tr>';", " // On sell\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Sell\").')</td><td colspan=\"3\">';\n $statutarray=array('1' => $langs->trans(\"OnSell\"), '0' => $langs->trans(\"NotOnSell\"));\n print $form->selectarray('statut',$statutarray,GETPOST('statut'));\n print '</td></tr>';", " // To buy\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Buy\").')</td><td colspan=\"3\">';\n $statutarray=array('1' => $langs->trans(\"ProductStatusOnBuy\"), '0' => $langs->trans(\"ProductStatusNotOnBuy\"));\n print $form->selectarray('statut_buy',$statutarray,GETPOST('statut_buy'));\n print '</td></tr>';", "\t // Batch number management\n\t\tif (! empty($conf->productbatch->enabled))\n\t\t{\n\t\t\tprint '<tr><td>'.$langs->trans(\"ManageLotSerial\").'</td><td colspan=\"3\">';\n\t\t\t$statutarray=array('0' => $langs->trans(\"ProductStatusNotOnBatch\"), '1' => $langs->trans(\"ProductStatusOnBatch\"));\n\t\t\tprint $form->selectarray('status_batch',$statutarray,GETPOST('status_batch'));\n\t\t\tprint '</td></tr>';\n\t\t}", " $showbarcode=empty($conf->barcode->enabled)?0:1;\n if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;", " if ($showbarcode)\n {\n \t print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>';\n \t if (isset($_POST['fk_barcode_type']))\n\t {\n\t \t$fk_barcode_type=GETPOST('fk_barcode_type');\n\t }\n\t else\n\t {\n\t \tif (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;\n\t }\n\t require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';\n $formbarcode = new FormBarCode($db);\n\t print $formbarcode->select_barcode_type($fk_barcode_type, 'fk_barcode_type', 1);\n\t print '</td><td>'.$langs->trans(\"BarcodeValue\").'</td><td>';\n\t $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode;\n\t if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object,$type);\n\t print '<input class=\"maxwidth100\" type=\"text\" name=\"barcode\" value=\"'.dol_escape_htmltag($tmpcode).'\">';\n\t print '</td></tr>';\n }", " // Description (used in invoice, propal...)\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"Description\").'</td><td colspan=\"3\">';", " $doleditor = new DolEditor('desc', GETPOST('desc','none'), '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%');\n $doleditor->Create();", " print \"</td></tr>\";", " // Public URL\n print '<tr><td>'.$langs->trans(\"PublicUrl\").'</td><td colspan=\"3\">';\n\t\tprint '<input type=\"text\" name=\"url\" class=\"quatrevingtpercent\" value=\"'.GETPOST('url').'\">';\n print '</td></tr>';", " // Stock min level\n if ($type != 1 && ! empty($conf->stock->enabled))\n {\n print '<tr><td>'.$form->textwithpicto($langs->trans(\"StockLimit\"), $langs->trans(\"StockLimitDesc\"), 1).'</td><td>';\n print '<input name=\"seuil_stock_alerte\" class=\"maxwidth50\" value=\"'.GETPOST('seuil_stock_alerte').'\">';\n print '</td>';\n // Stock desired level\n print '<td>'.$form->textwithpicto($langs->trans(\"DesiredStock\"), $langs->trans(\"DesiredStockDesc\"), 1).'</td><td>';\n print '<input name=\"desiredstock\" class=\"maxwidth50\" value=\"'.GETPOST('desiredstock').'\">';\n print '</td></tr>';\n }\n else\n {\n print '<input name=\"seuil_stock_alerte\" type=\"hidden\" value=\"0\">';\n print '<input name=\"desiredstock\" type=\"hidden\" value=\"0\">';\n }", " // Nature\n if ($type != 1)\n {\n print '<tr><td>'.$langs->trans(\"Nature\").'</td><td colspan=\"3\">';\n $statutarray=array('1' => $langs->trans(\"Finished\"), '0' => $langs->trans(\"RowMaterial\"));\n print $form->selectarray('finished',$statutarray,GETPOST('finished'),1);\n print '</td></tr>';\n }", " // Duration\n if ($type == 1)\n {\n print '<tr><td>' . $langs->trans(\"Duration\") . '</td><td colspan=\"3\"><input name=\"duration_value\" size=\"6\" maxlength=\"5\" value=\"' . $duration_value . '\"> &nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"h\">'.$langs->trans(\"Hour\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"d\">'.$langs->trans(\"Day\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"w\">'.$langs->trans(\"Week\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"m\">'.$langs->trans(\"Month\").'&nbsp;';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"y\">'.$langs->trans(\"Year\").'&nbsp;';\n print '</td></tr>';\n }", " if ($type != 1)\t// Le poids et le volume ne concerne que les produits et pas les services\n {\n // Weight\n print '<tr><td>'.$langs->trans(\"Weight\").'</td><td colspan=\"3\">';\n print '<input name=\"weight\" size=\"4\" value=\"'.GETPOST('weight').'\">';\n print $formproduct->select_measuring_units(\"weight_units\",\"weight\");\n print '</td></tr>';\n // Length\n if (empty($conf->global->PRODUCT_DISABLE_SIZE))\n {\n print '<tr><td>'.$langs->trans(\"Length\").' x '.$langs->trans(\"Width\").' x '.$langs->trans(\"Height\").'</td><td colspan=\"3\">';\n print '<input name=\"size\" size=\"4\" value=\"'.GETPOST('size').'\"> x ';\n print '<input name=\"sizewidth\" size=\"4\" value=\"'.GETPOST('sizewidth').'\"> x ';\n print '<input name=\"sizeheight\" size=\"4\" value=\"'.GETPOST('sizeheight').'\">';\n print $formproduct->select_measuring_units(\"size_units\",\"size\");\n print '</td></tr>';\n }\n if (empty($conf->global->PRODUCT_DISABLE_SURFACE))\n {\n // Surface\n print '<tr><td>'.$langs->trans(\"Surface\").'</td><td colspan=\"3\">';\n print '<input name=\"surface\" size=\"4\" value=\"'.GETPOST('surface').'\">';\n print $formproduct->select_measuring_units(\"surface_units\",\"surface\");\n print '</td></tr>';\n }\n // Volume\n print '<tr><td>'.$langs->trans(\"Volume\").'</td><td colspan=\"3\">';\n print '<input name=\"volume\" size=\"4\" value=\"'.GETPOST('volume').'\">';\n print $formproduct->select_measuring_units(\"volume_units\",\"volume\");\n print '</td></tr>';\n }", " // Units\n\t if($conf->global->PRODUCT_USE_UNITS)\n\t {\n\t\t print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td>';\n\t\t print '<td colspan=\"3\">';\n\t\t print $form->selectUnits('','units');\n\t\t print '</td></tr>';\n\t }", " // Custom code\n if (empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO) && empty($type))\n {\n\t print '<tr><td>'.$langs->trans(\"CustomCode\").'</td><td><input name=\"customcode\" class=\"maxwidth100onsmartphone\" value=\"'.GETPOST('customcode').'\"></td>';\n\t // Origin country\n\t print '<td>'.$langs->trans(\"CountryOrigin\").'</td><td>';\n\t print $form->select_country(GETPOST('country_id','int'),'country_id');\n\t if ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t print '</td></tr>';\n }", " // Other attributes\n $parameters=array('cols' => 3);\n $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n print $hookmanager->resPrint;\n if (empty($reshook) && ! empty($extrafields->attribute_label))\n {\n \tprint $object->showOptionals($extrafields,'edit',$parameters);\n }", " // Note (private, no output on invoices, propales...)\n //if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB)) available in create mode\n //{\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"NoteNotVisibleOnBill\").'</td><td colspan=\"3\">';", " // We use dolibarr_details as type of DolEditor here, because we must not accept images as description is included into PDF and not accepted by TCPDF.\n $doleditor = new DolEditor('note_private', GETPOST('note_private','none'), '', 140, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_8, '90%');\n \t $doleditor->Create();", " print \"</td></tr>\";\n //}", "\t\tif ($conf->categorie->enabled) {\n\t\t\t// Categories\n\t\t\tprint '<tr><td>'.$langs->trans(\"Categories\").'</td><td colspan=\"3\">';\n\t\t\t$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 64, 0, 1);\n\t\t\tprint $form->multiselectarray('categories', $cate_arbo, GETPOST('categories', 'array'), '', 0, '', 0, '100%');\n\t\t\tprint \"</td></tr>\";\n\t\t}", " print '</table>';", " print '<br>';", " if (! empty($conf->global->PRODUIT_MULTIPRICES))\n {\n // We do no show price array on create when multiprices enabled.\n // We must set them on prices tab.\n print '<table class=\"border\" width=\"100%\">';\n // VAT\n print '<tr><td class=\"titlefieldcreate\">' . $langs->trans(\"VATRate\") . '</td><td>';\n $defaultva = get_default_tva($mysoc, $mysoc);\n print $form->load_tva(\"tva_tx\", $defaultva, $mysoc, $mysoc, 0, 0, '', false, 1);\n print '</td></tr>';\n print '</table>';\n print '<br>';\n }\n else\n\t\t{\n print '<table class=\"border\" width=\"100%\">';", " // Price\n print '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"SellingPrice\").'</td>';\n print '<td><input name=\"price\" class=\"maxwidth50\" value=\"'.$object->price.'\">';\n print $form->selectPriceBaseType($object->price_base_type, \"price_base_type\");\n print '</td></tr>';", " // Min price\n print '<tr><td>'.$langs->trans(\"MinPrice\").'</td>';\n print '<td><input name=\"price_min\" class=\"maxwidth50\" value=\"'.$object->price_min.'\">';\n print '</td></tr>';", " // VAT\n print '<tr><td>'.$langs->trans(\"VATRate\").'</td><td>';\n $defaultva=get_default_tva($mysoc, $mysoc);\n print $form->load_tva(\"tva_tx\", $defaultva, $mysoc, $mysoc, 0, 0, '', false, 1);\n print '</td></tr>';", " print '</table>';", " print '<br>';\n }", " // Accountancy codes\n print '<table class=\"border\" width=\"100%\">';", "\t\tif (! empty($conf->accounting->enabled))\n\t\t{\n\t\t\t// Accountancy_code_sell\n\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\tprint '<td>';\n\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_sell'), 'accountancy_code_sell', 1, null, 1, 1, '');\n\t\t\tprint '</td></tr>';", "\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\tprint '<td>';\n\t\t\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_sell_intra'), 'accountancy_code_sell_intra', 1, null, 1, 1, '');\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\tprint '<td>';\n\t\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_sell_export'), 'accountancy_code_sell_export', 1, null, 1, 1, '');\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", "\t\t\t// Accountancy_code_buy\n\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\tprint '<td>';\n\t\t\tprint $formaccounting->select_account(GETPOST('accountancy_code_buy'), 'accountancy_code_buy', 1, null, 1, 1, '');\n\t\t\tprint '</td></tr>';\n\t\t}\n\t\telse // For external software\n\t\t{\n\t\t\t// Accountancy_code_sell\n\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_sell\" value=\"'.$object->accountancy_code_sell.'\">';\n\t\t\tprint '</td></tr>';", "\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_sell_intra\" value=\"'.$object->accountancy_code_sell_intra.'\">';\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\tprint '<tr><td class=\"titlefieldcreate\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_sell_export\" value=\"'.$object->accountancy_code_sell_export.'\">';\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", "\t\t\t// Accountancy_code_buy\n\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\tprint '<td class=\"maxwidthonsmartphone\"><input class=\"minwidth100\" name=\"accountancy_code_buy\" value=\"'.$object->accountancy_code_buy.'\">';\n\t\t\tprint '</td></tr>';\n\t\t}\n\t\tprint '</table>';", "\t\tdol_fiche_end();", "\t\tprint '<div class=\"center\">';\n\t\tprint '<input type=\"submit\" class=\"button\" value=\"' . $langs->trans(\"Create\") . '\">';\n\t\tprint ' &nbsp; &nbsp; ';\n\t\tprint '<input type=\"button\" class=\"button\" value=\"' . $langs->trans(\"Cancel\") . '\" onClick=\"javascript:history.go(-1)\">';\n\t\tprint '</div>';", "\t\tprint '</form>';\n\t}", " /*\n * Product card\n */", " else if ($object->id > 0)\n {\n // Fiche en mode edition\n\t\tif ($action == 'edit' && $usercancreate)\n\t\t{\n //WYSIWYG Editor\n require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';", " $type = $langs->trans('Product');\n if ($object->isService()) $type = $langs->trans('Service');\n //print load_fiche_titre($langs->trans('Modify').' '.$type.' : '.(is_object($object->oldcopy)?$object->oldcopy->ref:$object->ref), \"\");", " // Main official, simple, and not duplicated code\n print '<form action=\"'.$_SERVER['PHP_SELF'].'?id='.$object->id.'\" method=\"POST\">'.\"\\n\";\n print '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n print '<input type=\"hidden\" name=\"action\" value=\"update\">';\n print '<input type=\"hidden\" name=\"id\" value=\"'.$object->id.'\">';\n print '<input type=\"hidden\" name=\"canvas\" value=\"'.$object->canvas.'\">';", " $head=product_prepare_head($object);\n $titre=$langs->trans(\"CardProduct\".$object->type);\n $picto=($object->type== Product::TYPE_SERVICE?'service':'product');\n dol_fiche_head($head, 'card', $titre, 0, $picto);", " print '<table class=\"border allwidth\">';", " // Ref\n print '<tr><td class=\"titlefield fieldrequired\">'.$langs->trans(\"Ref\").'</td><td colspan=\"3\"><input name=\"ref\" class=\"maxwidth200\" maxlength=\"128\" value=\"'.dol_escape_htmltag($object->ref).'\"></td></tr>';", " // Label\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Label\").'</td><td colspan=\"3\"><input name=\"label\" class=\"minwidth300 maxwidth400onsmartphone\" maxlength=\"255\" value=\"'.dol_escape_htmltag($object->label).'\"></td></tr>';", " // Status To sell\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Sell\").')</td><td colspan=\"3\">';\n print '<select class=\"flat\" name=\"statut\">';\n if ($object->status)\n {\n print '<option value=\"1\" selected>'.$langs->trans(\"OnSell\").'</option>';\n print '<option value=\"0\">'.$langs->trans(\"NotOnSell\").'</option>';\n }\n else\n {\n print '<option value=\"1\">'.$langs->trans(\"OnSell\").'</option>';\n print '<option value=\"0\" selected>'.$langs->trans(\"NotOnSell\").'</option>';\n }\n print '</select>';\n print '</td></tr>';", " // Status To Buy\n print '<tr><td class=\"fieldrequired\">'.$langs->trans(\"Status\").' ('.$langs->trans(\"Buy\").')</td><td colspan=\"3\">';\n print '<select class=\"flat\" name=\"statut_buy\">';\n if ($object->status_buy)\n {\n print '<option value=\"1\" selected>'.$langs->trans(\"ProductStatusOnBuy\").'</option>';\n print '<option value=\"0\">'.$langs->trans(\"ProductStatusNotOnBuy\").'</option>';\n }\n else\n {\n print '<option value=\"1\">'.$langs->trans(\"ProductStatusOnBuy\").'</option>';\n print '<option value=\"0\" selected>'.$langs->trans(\"ProductStatusNotOnBuy\").'</option>';\n }\n print '</select>';\n print '</td></tr>';", "\t\t\t// Batch number managment", "\t\t\tif ($conf->productbatch->enabled)", "\t\t\t{\n\t\t\t\tif ($object->isProduct() || ! empty($conf->global->STOCK_SUPPORTS_SERVICES))\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td>'.$langs->trans(\"ManageLotSerial\").'</td><td colspan=\"3\">';\n\t\t\t\t\t$statutarray=array('0' => $langs->trans(\"ProductStatusNotOnBatch\"), '1' => $langs->trans(\"ProductStatusOnBatch\"));\n\t\t\t\t\tprint $form->selectarray('status_batch',$statutarray,$object->status_batch);\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}\n\t\t\t}", " // Barcode\n $showbarcode=empty($conf->barcode->enabled)?0:1;\n if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;", "\t if ($showbarcode)\n\t {\n\t\t print '<tr><td>'.$langs->trans('BarcodeType').'</td><td>';\n\t\t if (isset($_POST['fk_barcode_type']))\n\t\t {\n\t\t \t$fk_barcode_type=GETPOST('fk_barcode_type');\n\t\t }\n\t\t else\n\t\t {\n\t \t\t$fk_barcode_type=$object->barcode_type;\n\t\t \tif (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;\n\t\t }\n\t\t require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';\n\t $formbarcode = new FormBarCode($db);\n\t\t print $formbarcode->select_barcode_type($fk_barcode_type, 'fk_barcode_type', 1);\n\t\t print '</td><td>'.$langs->trans(\"BarcodeValue\").'</td><td>';\n\t\t $tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode;\n\t\t if (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object,$type);\n\t\t print '<input size=\"40\" class=\"maxwidthonsmartphone\" type=\"text\" name=\"barcode\" value=\"'.dol_escape_htmltag($tmpcode).'\">';\n\t\t print '</td></tr>';\n\t }", " // Description (used in invoice, propal...)\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"Description\").'</td><td colspan=\"3\">';", " // We use dolibarr_details as type of DolEditor here, because we must not accept images as description is included into PDF and not accepted by TCPDF.\n $doleditor = new DolEditor('desc', $object->description, '', 160, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%');\n $doleditor->Create();", " print \"</td></tr>\";\n print \"\\n\";", " // Public Url\n print '<tr><td>'.$langs->trans(\"PublicUrl\").'</td><td colspan=\"3\">';\n\t\t\tprint '<input type=\"text\" name=\"url\" class=\"quatrevingtpercent\" value=\"'.$object->url.'\">';\n print '</td></tr>';", " // Stock\n /*\n if ($object->isProduct() && ! empty($conf->stock->enabled))\n {\n print \"<tr>\".'<td>'.$langs->trans(\"StockLimit\").'</td><td>';\n print '<input name=\"seuil_stock_alerte\" size=\"4\" value=\"'.$object->seuil_stock_alerte.'\">';\n print '</td>';", " print '<td>'.$langs->trans(\"DesiredStock\").'</td><td>';\n print '<input name=\"desiredstock\" size=\"4\" value=\"'.$object->desiredstock.'\">';\n print '</td></tr>';\n }\n else\n {\n print '<input name=\"seuil_stock_alerte\" type=\"hidden\" value=\"'.$object->seuil_stock_alerte.'\">';\n print '<input name=\"desiredstock\" type=\"hidden\" value=\"'.$object->desiredstock.'\">';\n }*/", " // Nature\n if($object->type!= Product::TYPE_SERVICE)\n {\n print '<tr><td>'.$langs->trans(\"Nature\").'</td><td colspan=\"3\">';\n $statutarray=array('-1'=>'&nbsp;', '1' => $langs->trans(\"Finished\"), '0' => $langs->trans(\"RowMaterial\"));\n print $form->selectarray('finished',$statutarray,$object->finished);\n print '</td></tr>';\n }", " if ($object->isService())\n {\n // Duration\n print '<tr><td>'.$langs->trans(\"Duration\").'</td><td colspan=\"3\"><input name=\"duration_value\" size=\"3\" maxlength=\"5\" value=\"'.$object->duration_value.'\">';\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"h\"'.($object->duration_unit=='h'?' checked':'').'>'.$langs->trans(\"Hour\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"d\"'.($object->duration_unit=='d'?' checked':'').'>'.$langs->trans(\"Day\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"w\"'.($object->duration_unit=='w'?' checked':'').'>'.$langs->trans(\"Week\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"m\"'.($object->duration_unit=='m'?' checked':'').'>'.$langs->trans(\"Month\");\n print '&nbsp; ';\n print '<input name=\"duration_unit\" type=\"radio\" value=\"y\"'.($object->duration_unit=='y'?' checked':'').'>'.$langs->trans(\"Year\");\n print '</td></tr>';\n }\n else\n\t\t\t{\n // Weight\n print '<tr><td>'.$langs->trans(\"Weight\").'</td><td colspan=\"3\">';\n print '<input name=\"weight\" size=\"5\" value=\"'.$object->weight.'\"> ';\n print $formproduct->select_measuring_units(\"weight_units\", \"weight\", $object->weight_units);\n print '</td></tr>';\n if (empty($conf->global->PRODUCT_DISABLE_SIZE))\n {\n \t\t\t// Length\n \t\t\tprint '<tr><td>'.$langs->trans(\"Length\").' x '.$langs->trans(\"Width\").' x '.$langs->trans(\"Height\").'</td><td colspan=\"3\">';\n \t\t\tprint '<input name=\"size\" size=\"5\" value=\"'.$object->length.'\">x';\n \t\t\tprint '<input name=\"sizewidth\" size=\"5\" value=\"'.$object->width.'\">x';\n \t\t\tprint '<input name=\"sizeheight\" size=\"5\" value=\"'.$object->height.'\"> ';\n \t\t\tprint $formproduct->select_measuring_units(\"size_units\", \"size\", $object->length_units);\n \t\t\tprint '</td></tr>';\n }\n if (empty($conf->global->PRODUCT_DISABLE_SURFACE))\n {\n // Surface\n print '<tr><td>'.$langs->trans(\"Surface\").'</td><td colspan=\"3\">';\n print '<input name=\"surface\" size=\"5\" value=\"'.$object->surface.'\"> ';\n print $formproduct->select_measuring_units(\"surface_units\", \"surface\", $object->surface_units);\n print '</td></tr>';\n }\n if (empty($conf->global->PRODUCT_DISABLE_VOLUME))\n {\n // Volume\n print '<tr><td>'.$langs->trans(\"Volume\").'</td><td colspan=\"3\">';\n print '<input name=\"volume\" size=\"5\" value=\"'.$object->volume.'\"> ';\n print $formproduct->select_measuring_units(\"volume_units\", \"volume\", $object->volume_units);\n print '</td></tr>';\n }\n }\n \t// Units\n\t if($conf->global->PRODUCT_USE_UNITS)\n\t {\n\t\t print '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td>';\n\t\t print '<td colspan=\"3\">';\n\t\t print $form->selectUnits($object->fk_unit, 'units');\n\t\t print '</td></tr>';\n\t }", "\t // Custom code\n \t if (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO))\n \t{\n\t print '<tr><td>'.$langs->trans(\"CustomCode\").'</td><td><input name=\"customcode\" class=\"maxwidth100onsmartphone\" value=\"'.$object->customcode.'\"></td>';\n\t // Origin country\n\t print '<td>'.$langs->trans(\"CountryOrigin\").'</td><td>';\n\t print $form->select_country($object->country_id, 'country_id', '', 0, 'minwidth100 maxwidthonsmartphone');\n\t if ($user->admin) print info_admin($langs->trans(\"YouCanChangeValuesForThisListFromDictionarySetup\"),1);\n\t print '</td></tr>';\n \t}", " // Other attributes\n $parameters=array('colspan' => ' colspan=\"3\"', 'cols'=>3);\n $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n print $hookmanager->resPrint;\n if (empty($reshook) && ! empty($extrafields->attribute_label))\n {\n \tprint $object->showOptionals($extrafields,'edit');\n }", "\t\t\t// Tags-Categories\n if ($conf->categorie->enabled)\n\t\t\t{\n\t\t\t\tprint '<tr><td class=\"tdtop\">'.$langs->trans(\"Categories\").'</td><td colspan=\"3\">';\n\t\t\t\t$cate_arbo = $form->select_all_categories(Categorie::TYPE_PRODUCT, '', 'parent', 64, 0, 1);\n\t\t\t\t$c = new Categorie($db);\n\t\t\t\t$cats = $c->containing($object->id,Categorie::TYPE_PRODUCT);\n\t\t\t\t$arrayselected=array();\n\t\t\t\tforeach($cats as $cat) {\n\t\t\t\t\t$arrayselected[] = $cat->id;\n\t\t\t\t}\n\t\t\t\tprint $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%');\n\t\t\t\tprint \"</td></tr>\";\n\t\t\t}", " // Note private\n\t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n\t\t\t{\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"NoteNotVisibleOnBill\").'</td><td colspan=\"3\">';", " $doleditor = new DolEditor('note_private', $object->note_private, '', 140, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_4, '90%');\n $doleditor->Create();", " print \"</td></tr>\";\n\t\t\t}", " print '</table>';", " print '<br>';", " print '<table class=\"border\" width=\"100%\">';", "\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell\n\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\t\tprint '<td>';\n\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_sell, 'accountancy_code_sell', 1, '', 1, 1);\n\t\t\t\tprint '</td></tr>';", "\t\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t\t{\n\t\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\t\tprint '<td>';\n\t\t\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, '', 1, 1);\n\t\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t\t}", "\t\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\t\tprint '<td>';\n\t\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_sell_export, 'accountancy_code_sell_export', 1, '', 1, 1);\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_buy\n\t\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\t\tprint '<td>';\n\t\t\t\tprint $formaccounting->select_account($object->accountancy_code_buy, 'accountancy_code_buy', 1, '', 1, 1);\n\t\t\t\tprint '</td></tr>';\n\t\t\t}\n\t\t\telse // For external software\n\t\t\t{\n\t\t\t\t// Accountancy_code_sell\n\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellCode\").'</td>';\n\t\t\t\tprint '<td><input name=\"accountancy_code_sell\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_sell.'\">';\n\t\t\t\tprint '</td></tr>';", "\t\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t\t{\n\t\t\t\t\t// Accountancy_code_sell_intra\n\t\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t\t{\n\t\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellIntraCode\").'</td>';\n\t\t\t\t\t\tprint '<td><input name=\"accountancy_code_sell_intra\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_sell_intra.'\">';\n\t\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t\t}", "\t\t\t\t\t// Accountancy_code_sell_export\n\t\t\t\t\tprint '<tr><td class=\"titlefield\">'.$langs->trans(\"ProductAccountancySellExportCode\").'</td>';\n\t\t\t\t\tprint '<td><input name=\"accountancy_code_sell_export\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_sell_export.'\">';\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy_code_buy\n\t\t\t\tprint '<tr><td>'.$langs->trans(\"ProductAccountancyBuyCode\").'</td>';\n\t\t\t\tprint '<td><input name=\"accountancy_code_buy\" class=\"maxwidth200\" value=\"'.$object->accountancy_code_buy.'\">';\n\t\t\t\tprint '</td></tr>';\n\t\t\t}\n\t\t\tprint '</table>';", "\t\t\tdol_fiche_end();", "\t\t\tprint '<div class=\"center\">';\n\t\t\tprint '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Save\").'\">';\n\t\t\tprint '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';\n\t\t\tprint '<input type=\"submit\" class=\"button\" name=\"cancel\" value=\"'.$langs->trans(\"Cancel\").'\">';\n\t\t\tprint '</div>';", "\t\t\tprint '</form>';\n\t\t}\n // Fiche en mode visu\n else\n\t\t{\n $showbarcode=empty($conf->barcode->enabled)?0:1;\n if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;", "\t\t $head=product_prepare_head($object);\n $titre=$langs->trans(\"CardProduct\".$object->type);\n $picto=($object->type== Product::TYPE_SERVICE?'service':'product');", " dol_fiche_head($head, 'card', $titre, -1, $picto);", " $linkback = '<a href=\"'.DOL_URL_ROOT.'/product/list.php?restore_lastsearch_values=1&type='.$object->type.'\">'.$langs->trans(\"BackToList\").'</a>';\n $object->next_prev_filter=\" fk_product_type = \".$object->type;", " $shownav = 1;\n if ($user->societe_id && ! in_array('product', explode(',',$conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0;", " dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref');", "\n print '<div class=\"fichecenter\">';\n print '<div class=\"fichehalfleft\">';", " print '<div class=\"underbanner clearboth\"></div>';\n print '<table class=\"border tableforfield\" width=\"100%\">';", "\t\t\t// Type\n\t\t\tif (! empty($conf->produit->enabled) && ! empty($conf->service->enabled))\n\t\t\t{\n\t\t\t\t// TODO change for compatibility with edit in place\n\t\t\t\t$typeformat='select;0:'.$langs->trans(\"Product\").',1:'.$langs->trans(\"Service\");\n\t\t\t\tprint '<tr><td class=\"titlefield\">'.$form->editfieldkey(\"Type\", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat).'</td><td colspan=\"2\">';\n\t\t\t\tprint $form->editfieldval(\"Type\", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat);\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", " if ($showbarcode)\n {\n // Barcode type\n print '<tr><td class=\"nowrap\">';\n print '<table width=\"100%\" class=\"nobordernopadding\"><tr><td class=\"nowrap\">';\n print $langs->trans(\"BarcodeType\");\n print '</td>';\n if (($action != 'editbarcodetype') && $usercancreate && $createbarcode) print '<td align=\"right\"><a href=\"'.$_SERVER[\"PHP_SELF\"].'?action=editbarcodetype&amp;id='.$object->id.'\">'.img_edit($langs->trans('Edit'),1).'</a></td>';\n print '</tr></table>';\n print '</td><td colspan=\"2\">';\n if ($action == 'editbarcodetype' || $action == 'editbarcode')\n {\n require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php';\n $formbarcode = new FormBarCode($db);\n\t\t\t\t}\n if ($action == 'editbarcodetype')\n {\n $formbarcode->form_barcode_type($_SERVER['PHP_SELF'].'?id='.$object->id,$object->barcode_type,'fk_barcode_type');\n }\n else\n {\n $object->fetch_barcode();\n print $object->barcode_type_label?$object->barcode_type_label:($object->barcode?'<div class=\"warning\">'.$langs->trans(\"SetDefaultBarcodeType\").'<div>':'');\n }\n print '</td></tr>'.\"\\n\";", " // Barcode value\n print '<tr><td class=\"nowrap\">';\n print '<table width=\"100%\" class=\"nobordernopadding\"><tr><td class=\"nowrap\">';\n print $langs->trans(\"BarcodeValue\");\n print '</td>';\n if (($action != 'editbarcode') && $usercancreate && $createbarcode) print '<td align=\"right\"><a href=\"'.$_SERVER[\"PHP_SELF\"].'?action=editbarcode&amp;id='.$object->id.'\">'.img_edit($langs->trans('Edit'),1).'</a></td>';\n print '</tr></table>';\n print '</td><td colspan=\"2\">';\n if ($action == 'editbarcode')\n {\n\t\t\t\t\t$tmpcode=isset($_POST['barcode'])?GETPOST('barcode'):$object->barcode;\n\t\t\t\t\tif (empty($tmpcode) && ! empty($modBarCodeProduct->code_auto)) $tmpcode=$modBarCodeProduct->getNextValue($object,$type);", "\t\t\t\t\tprint '<form method=\"post\" action=\"'.$_SERVER[\"PHP_SELF\"].'?id='.$object->id.'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"action\" value=\"setbarcode\">';\n\t\t\t\t\tprint '<input type=\"hidden\" name=\"barcode_type_code\" value=\"'.$object->barcode_type_code.'\">';\n\t\t\t\t\tprint '<input size=\"40\" class=\"maxwidthonsmartphone\" type=\"text\" name=\"barcode\" value=\"'.$tmpcode.'\">';\n\t\t\t\t\tprint '&nbsp;<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Modify\").'\">';\n\t\t\t\t\tprint '</form>';\n }\n else\n {\n\t\t\t\t\tprint $object->barcode;\n }\n print '</td></tr>'.\"\\n\";\n }", "\t\t\t// Accountancy sell code\n\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\tprint $langs->trans(\"ProductAccountancySellCode\");\n\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t{\n\t\t\t\t$accountingaccount = new AccountingAccount($db);\n\t\t\t\t$accountingaccount->fetch('',$object->accountancy_code_sell,1);", "\t\t\t\tprint $accountingaccount->getNomUrl(0,1,1,'',1);\n\t\t\t} else {\n\t\t\t\tprint $object->accountancy_code_sell;\n\t\t\t}\n\t\t\tprint '</td></tr>';", "\t\t\tif ($conf->global->MAIN_FEATURES_LEVEL)\n\t\t\t{\n\t\t\t\t// Accountancy sell code intra-community\n\t\t\t\tif ($mysoc->isInEEC())\n\t\t\t\t{\n\t\t\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\t\t\tprint $langs->trans(\"ProductAccountancySellIntraCode\");\n\t\t\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t\t\t{\n\t\t\t\t\t\t$accountingaccount2 = new AccountingAccount($db);\n\t\t\t\t\t\t$accountingaccount2->fetch('',$object->accountancy_code_sell_intra,1);", "\t\t\t\t\t\tprint $accountingaccount2->getNomUrl(0,1,1,'',1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint $object->accountancy_code_sell_intra;\n\t\t\t\t\t}\n\t\t\t\t\tprint '</td></tr>';\n\t\t\t\t}", "\t\t\t\t// Accountancy sell code export\n\t\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\t\tprint $langs->trans(\"ProductAccountancySellExportCode\");\n\t\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t\t{\n\t\t\t\t\t$accountingaccount3 = new AccountingAccount($db);\n\t\t\t\t\t$accountingaccount3->fetch('',$object->accountancy_code_sell_export,1);", "\t\t\t\t\tprint $accountingaccount3->getNomUrl(0,1,1,'',1);\n\t\t\t\t} else {\n\t\t\t\t\tprint $object->accountancy_code_sell_export;\n\t\t\t\t}\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", "\t\t\t// Accountancy buy code\n\t\t\tprint '<tr><td class=\"nowrap\">';\n\t\t\tprint $langs->trans(\"ProductAccountancyBuyCode\");\n\t\t\tprint '</td><td colspan=\"2\">';\n\t\t\tif (! empty($conf->accounting->enabled))\n\t\t\t{\n\t\t\t\t$accountingaccount4 = new AccountingAccount($db);\n\t\t\t\t$accountingaccount4->fetch('',$object->accountancy_code_buy,1);", "\t\t\t\tprint $accountingaccount4->getNomUrl(0,1,1,'',1);\n\t\t\t} else {\n\t\t\t\tprint $object->accountancy_code_buy;\n\t\t\t}\n\t\t\tprint '</td></tr>';", " // Batch number management (to batch)", " if (! empty($conf->productbatch->enabled))", " {\n\t\t\t\tif ($object->isProduct() || ! empty($conf->global->STOCK_SUPPORTS_SERVICES))\n\t\t\t\t{\n \t\tprint '<tr><td>'.$langs->trans(\"ManageLotSerial\").'</td><td colspan=\"2\">';\n \t if (! empty($conf->use_javascript_ajax) && $usercancreate && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {\n \t print ajax_object_onoff($object, 'status_batch', 'tobatch', 'ProductStatusOnBatch', 'ProductStatusNotOnBatch');\n \t } else {\n \t print $object->getLibStatut(0,2);\n \t }\n \t print '</td></tr>';\n\t\t\t\t}\n }", " // Description\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"Description\").'</td><td colspan=\"2\">'.(dol_textishtml($object->description)?$object->description:dol_nl2br($object->description,1,true)).'</td></tr>';", " // Public URL\n print '<tr><td>'.$langs->trans(\"PublicUrl\").'</td><td colspan=\"2\">';\n\t\t\tprint dol_print_url($object->url);\n print '</td></tr>';", " //Parent product.\n if (!empty($conf->variants->enabled) && $object->isProduct()) {", " $combination = new ProductCombination($db);", " if ($combination->fetchByFkProductChild($object->id) > 0) {\n $prodstatic = new Product($db);\n $prodstatic->fetch($combination->fk_product_parent);", " // Parent product\n print '<tr><td>'.$langs->trans(\"ParentProduct\").'</td><td colspan=\"2\">';\n print $prodstatic->getNomUrl(1);\n print '</td></tr>';\n }\n }", " print '</table>';\n print '</div>';\n print '<div class=\"fichehalfright\"><div class=\"ficheaddleft\">';", " print '<div class=\"underbanner clearboth\"></div>';\n print '<table class=\"border tableforfield\" width=\"100%\">';", " // Nature\n if($object->type!= Product::TYPE_SERVICE)\n {\n print '<tr><td class=\"titlefield\">'.$langs->trans(\"Nature\").'</td><td colspan=\"2\">';\n print $object->getLibFinished();\n print '</td></tr>';\n }", " if ($object->isService())\n {\n // Duration\n print '<tr><td class=\"titlefield\">'.$langs->trans(\"Duration\").'</td><td colspan=\"2\">'.$object->duration_value.'&nbsp;';\n if ($object->duration_value > 1)\n {\n $dur=array(\"h\"=>$langs->trans(\"Hours\"),\"d\"=>$langs->trans(\"Days\"),\"w\"=>$langs->trans(\"Weeks\"),\"m\"=>$langs->trans(\"Months\"),\"y\"=>$langs->trans(\"Years\"));\n }\n else if ($object->duration_value > 0)\n {\n $dur=array(\"h\"=>$langs->trans(\"Hour\"),\"d\"=>$langs->trans(\"Day\"),\"w\"=>$langs->trans(\"Week\"),\"m\"=>$langs->trans(\"Month\"),\"y\"=>$langs->trans(\"Year\"));\n }\n print (! empty($object->duration_unit) && isset($dur[$object->duration_unit]) ? $langs->trans($dur[$object->duration_unit]) : '').\"&nbsp;\";", " print '</td></tr>';\n }\n else\n {\n // Weight\n print '<tr><td class=\"titlefield\">'.$langs->trans(\"Weight\").'</td><td colspan=\"2\">';\n if ($object->weight != '')\n {\n print $object->weight.\" \".measuring_units_string($object->weight_units,\"weight\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n if (empty($conf->global->PRODUCT_DISABLE_SIZE))\n {\n // Length\n print '<tr><td>'.$langs->trans(\"Length\").' x '.$langs->trans(\"Width\").' x '.$langs->trans(\"Height\").'</td><td colspan=\"2\">';\n if ($object->length != '' || $object->width != '' || $object->height != '')\n {\n print $object->length;\n if ($object->width) print \" x \".$object->width;\n if ($object->height) print \" x \".$object->height;\n print ' '.measuring_units_string($object->length_units,\"size\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n }\n if (empty($conf->global->PRODUCT_DISABLE_SURFACE))\n {\n // Surface\n print '<tr><td>'.$langs->trans(\"Surface\").'</td><td colspan=\"2\">';\n if ($object->surface != '')\n {\n print $object->surface.\" \".measuring_units_string($object->surface_units,\"surface\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n }\n if (empty($conf->global->PRODUCT_DISABLE_VOLUME))\n {\n // Volume\n print '<tr><td>'.$langs->trans(\"Volume\").'</td><td colspan=\"2\">';\n if ($object->volume != '')\n {\n print $object->volume.\" \".measuring_units_string($object->volume_units,\"volume\");\n }\n else\n {\n print '&nbsp;';\n }\n print \"</td></tr>\\n\";\n }\n }", "\t\t\t// Unit\n\t\t\tif (! empty($conf->global->PRODUCT_USE_UNITS))\n\t\t\t{\n\t\t\t\t$unit = $object->getLabelOfUnit();", "\t\t\t\tprint '<tr><td>'.$langs->trans('DefaultUnitToShow').'</td><td>';\n\t\t\t\tif ($unit !== '') {\n\t\t\t\t\tprint $langs->trans($unit);\n\t\t\t\t}\n\t\t\t\tprint '</td></tr>';\n\t\t\t}", " \t// Custom code\n \tif (! $object->isService() && empty($conf->global->PRODUCT_DISABLE_CUSTOM_INFO))\n \t{\n\t print '<tr><td>'.$langs->trans(\"CustomCode\").'</td><td colspan=\"2\">'.$object->customcode.'</td>';", " \t// Origin country code\n \tprint '<tr><td>'.$langs->trans(\"CountryOrigin\").'</td><td colspan=\"2\">'.getCountry($object->country_id,0,$db).'</td>';\n \t}", " // Other attributes\n $parameters=array('colspan' => ' colspan=\"'.(2+(($showphoto||$showbarcode)?1:0)).'\"');\n include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';", "\t\t\t// Categories\n\t\t\tif($conf->categorie->enabled) {\n\t\t\t\tprint '<tr><td valign=\"middle\">'.$langs->trans(\"Categories\").'</td><td colspan=\"3\">';\n\t\t\t\tprint $form->showCategories($object->id,'product',1);\n\t\t\t\tprint \"</td></tr>\";\n\t\t\t}", " // Note private\n\t\t\tif (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))\n\t\t\t{\n \t\t\tprint '<!-- show Note --> '.\"\\n\";\n print '<tr><td class=\"tdtop\">'.$langs->trans(\"NotePrivate\").'</td><td colspan=\"'.(2+(($showphoto||$showbarcode)?1:0)).'\">'.(dol_textishtml($object->note_private)?$object->note_private:dol_nl2br($object->note_private,1,true)).'</td></tr>'.\"\\n\";\n print '<!-- End show Note --> '.\"\\n\";\n\t\t\t}", " print \"</table>\\n\";\n \t\tprint '</div>';", " print '</div></div>';\n print '<div style=\"clear:both\"></div>';", " dol_fiche_end();\n }", " }\n else if ($action != 'create')\n {\n exit;\n }\n}", "// Load object modCodeProduct\n$module=(! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON)?$conf->global->PRODUCT_CODEPRODUCT_ADDON:'mod_codeproduct_leopard');\nif (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php')\n{\n $module = substr($module, 0, dol_strlen($module)-4);\n}\n$result=dol_include_once('/core/modules/product/'.$module.'.php');\nif ($result > 0)\n{\n\t$modCodeProduct = new $module();\n}", "$tmpcode='';\nif (! empty($modCodeProduct->code_auto)) $tmpcode=$modCodeProduct->getNextValue($object,$object->type);", "// Define confirmation messages\n$formquestionclone=array(\n\t'text' => $langs->trans(\"ConfirmClone\"),\n array('type' => 'text', 'name' => 'clone_ref','label' => $langs->trans(\"NewRefForClone\"), 'value' => empty($tmpcode) ? $langs->trans(\"CopyOf\").' '.$object->ref : $tmpcode, 'size'=>24),\n array('type' => 'checkbox', 'name' => 'clone_content','label' => $langs->trans(\"CloneContentProduct\"), 'value' => 1),\n array('type' => 'checkbox', 'name' => 'clone_prices', 'label' => $langs->trans(\"ClonePricesProduct\").' ('.$langs->trans(\"FeatureNotYetAvailable\").')', 'value' => 0, 'disabled' => true),\n);\nif (! empty($conf->global->PRODUIT_SOUSPRODUITS))\n{\n $formquestionclone[]=array('type' => 'checkbox', 'name' => 'clone_composition', 'label' => $langs->trans('CloneCompositionProduct'), 'value' => 1);\n}", "// Confirm delete product\nif (($action == 'delete' && (empty($conf->use_javascript_ajax) || ! empty($conf->dol_use_jmobile)))\t// Output when action = clone if jmobile or no js\n\t|| (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)))\t\t\t\t\t\t\t// Always output when not jmobile nor js\n{\n print $form->formconfirm(\"card.php?id=\".$object->id,$langs->trans(\"DeleteProduct\"),$langs->trans(\"ConfirmDeleteProduct\"),\"confirm_delete\",'',0,\"action-delete\");\n}", "// Clone confirmation\nif (($action == 'clone' && (empty($conf->use_javascript_ajax) || ! empty($conf->dol_use_jmobile)))\t\t// Output when action = clone if jmobile or no js\n\t|| (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile)))\t\t\t\t\t\t\t// Always output when not jmobile nor js\n{\n print $form->formconfirm($_SERVER[\"PHP_SELF\"].'?id='.$object->id,$langs->trans('CloneProduct'),$langs->trans('ConfirmCloneProduct',$object->ref),'confirm_clone',$formquestionclone,'yes','action-clone',260,600);\n}", "\n/* ************************************************************************** */\n/* */\n/* Barre d'action */\n/* */\n/* ************************************************************************** */\nif ($action != 'create' && $action != 'edit')\n{\n print \"\\n\".'<div class=\"tabsAction\">'.\"\\n\";", " $parameters=array();\n $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook\n if (empty($reshook))\n\t{\n\t\tif ($usercancreate)\n {\n if (! isset($object->no_button_edit) || $object->no_button_edit <> 1) print '<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"'.$_SERVER[\"PHP_SELF\"].'?action=edit&amp;id='.$object->id.'\">'.$langs->trans(\"Modify\").'</a></div>';", " if (! isset($object->no_button_copy) || $object->no_button_copy <> 1)\n {\n if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))\n {\n print '<div class=\"inline-block divButAction\"><span id=\"action-clone\" class=\"butAction\">'.$langs->trans('ToClone').'</span></div>'.\"\\n\";\n }\n else\n \t\t\t{\n print '<div class=\"inline-block divButAction\"><a class=\"butAction\" href=\"'.$_SERVER[\"PHP_SELF\"].'?action=clone&amp;id='.$object->id.'\">'.$langs->trans(\"ToClone\").'</a></div>';\n }\n }\n }\n $object_is_used = $object->isObjectUsed($object->id);", " if ($usercandelete)\n {\n if (empty($object_is_used) && (! isset($object->no_button_delete) || $object->no_button_delete <> 1))\n {\n if (! empty($conf->use_javascript_ajax) && empty($conf->dol_use_jmobile))\n {\n print '<div class=\"inline-block divButAction\"><span id=\"action-delete\" class=\"butActionDelete\">'.$langs->trans('Delete').'</span></div>'.\"\\n\";\n }\n else\n \t\t\t{\n print '<div class=\"inline-block divButAction\"><a class=\"butActionDelete\" href=\"'.$_SERVER[\"PHP_SELF\"].'?action=delete&amp;id='.$object->id.'\">'.$langs->trans(\"Delete\").'</a></div>';\n }\n }\n else\n \t\t{\n print '<div class=\"inline-block divButAction\"><a class=\"butActionRefused\" href=\"#\" title=\"'.$langs->trans(\"ProductIsUsed\").'\">'.$langs->trans(\"Delete\").'</a></div>';\n }\n }\n else\n \t{\n print '<div class=\"inline-block divButAction\"><a class=\"butActionRefused\" href=\"#\" title=\"'.$langs->trans(\"NotEnoughPermissions\").'\">'.$langs->trans(\"Delete\").'</a></div>';\n }\n }", " print \"\\n</div>\\n\";\n}", "/*\n * All the \"Add to\" areas\n */", "if (! empty($conf->global->PRODUCT_ADD_FORM_ADD_TO) && $object->id && ($action == '' || $action == 'view') && $object->status)\n{\n //Variable used to check if any text is going to be printed\n $html = '';\n\t//print '<div class=\"fichecenter\"><div class=\"fichehalfleft\">';", " // Propals\n if (! empty($conf->propal->enabled) && $user->rights->propale->creer)\n {\n $propal = new Propal($db);", " $langs->load(\"propal\");", " $otherprop = $propal->liste_array(2,1,0);", " if (is_array($otherprop) && count($otherprop))\n {\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftProposals\").'</td><td>';\n \t$html .= $form->selectarray(\"propalid\", $otherprop, 0, 1);\n \t$html .= '</td></tr>';\n }\n else\n {\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftProposals\").'</td><td>';\n \t$html .= $langs->trans(\"NoDraftProposals\");\n \t$html .= '</td></tr>';\n }\n }", " // Commande\n if (! empty($conf->commande->enabled) && $user->rights->commande->creer)\n {\n $commande = new Commande($db);", " $langs->load(\"orders\");", " $othercom = $commande->liste_array(2, 1, null);\n if (is_array($othercom) && count($othercom))\n {\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftOrders\").'</td><td>';\n \t$html .= $form->selectarray(\"commandeid\", $othercom, 0, 1);\n \t$html .= '</td></tr>';\n }\n else\n\t\t{\n \t$html .= '<tr><td style=\"width: 200px;\">';\n \t$html .= $langs->trans(\"AddToDraftOrders\").'</td><td>';\n \t$html .= $langs->trans(\"NoDraftOrders\");\n \t$html .= '</td></tr>';\n }\n }", " // Factures\n if (! empty($conf->facture->enabled) && $user->rights->facture->creer)\n {\n \t$invoice = new Facture($db);", " \t$langs->load(\"bills\");", " \t$otherinvoice = $invoice->liste_array(2, 1, null);\n \tif (is_array($otherinvoice) && count($otherinvoice))\n \t{\n \t\t$html .= '<tr><td style=\"width: 200px;\">';\n \t\t$html .= $langs->trans(\"AddToDraftInvoices\").'</td><td>';\n \t\t$html .= $form->selectarray(\"factureid\", $otherinvoice, 0, 1);\n \t\t$html .= '</td></tr>';\n \t}\n \telse\n \t{\n \t\t$html .= '<tr><td style=\"width: 200px;\">';\n \t\t$html .= $langs->trans(\"AddToDraftInvoices\").'</td><td>';\n \t\t$html .= $langs->trans(\"NoDraftInvoices\");\n \t\t$html .= '</td></tr>';\n \t}\n }", " //If any text is going to be printed, then we show the table\n if (!empty($html))\n {\n\t print '<form method=\"POST\" action=\"'.$_SERVER[\"PHP_SELF\"].'?id='.$object->id.'\">';\n \tprint '<input type=\"hidden\" name=\"token\" value=\"'.$_SESSION['newtoken'].'\">';\n \tprint '<input type=\"hidden\" name=\"action\" value=\"addin\">';", "\t print load_fiche_titre($langs->trans(\"AddToDraft\"),'','');", "\t\tdol_fiche_head('');", " \t$html .= '<tr><td class=\"nowrap\">'.$langs->trans(\"Quantity\").' ';\n \t$html .= '<input type=\"text\" class=\"flat\" name=\"qty\" size=\"1\" value=\"1\"></td>';\n $html .= '<td class=\"nowrap\">'.$langs->trans(\"ReductionShort\").'(%) ';\n \t$html .= '<input type=\"text\" class=\"flat\" name=\"remise_percent\" size=\"1\" value=\"0\">';\n \t$html .= '</td></tr>';", " \tprint '<table width=\"100%\" class=\"border\">';\n print $html;\n print '</table>';", " print '<div class=\"center\">';\n print '<input type=\"submit\" class=\"button\" value=\"'.$langs->trans(\"Add\").'\">';\n print '</div>';", " dol_fiche_end();", " print '</form>';\n }\n}", "\n/*\n * Documents generes\n */", "if ($action != 'create' && $action != 'edit' && $action != 'delete')\n{\n print '<div class=\"fichecenter\"><div class=\"fichehalfleft\">';\n print '<a name=\"builddoc\"></a>'; // ancre", " // Documents\n $objectref = dol_sanitizeFileName($object->ref);\n $relativepath = $comref . '/' . $objectref . '.pdf';\n $filedir = $conf->produit->dir_output . '/' . $objectref;\n $urlsource=$_SERVER[\"PHP_SELF\"].\"?id=\".$object->id;\n $genallowed=$usercanread;\n $delallowed=$usercancreate;", " $var=true;", " print $formfile->showdocuments($modulepart,$object->ref,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,28,0,'',0,'',$object->default_lang, '', $object);\n $somethingshown=$formfile->numoffiles;", " print '</div><div class=\"fichehalfright\"><div class=\"ficheaddleft\">';", " $MAXEVENT = 10;", " $morehtmlright = '<a href=\"'.DOL_URL_ROOT.'/product/agenda.php?id='.$object->id.'\">';\n $morehtmlright.= $langs->trans(\"SeeAll\");\n $morehtmlright.= '</a>';", " // List of actions on element\n include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';\n $formactions = new FormActions($db);\n $somethingshown = $formactions->showactions($object, 'product', 0, 1, '', $MAXEVENT, '', $morehtmlright);\t\t// Show all action for product", " print '</div></div></div>';\n}", "\nllxFooter();\n$db->close();" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>\n * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>\n * Copyright (C) 2007-2011 Laurent Destailleur <eldy@users.sourceforge.net>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n * \\file htdocs/societe/ajax/company.php\n * \\brief File to return Ajax response on thirdparty list request\n */", "if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal\nif (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1');\nif (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1');\nif (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1');\nif (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1');\nif (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1');", "require '../../main.inc.php';", "$htmlname=GETPOST('htmlname','alpha');\n$filter=GETPOST('filter','alpha');\n$outjson=(GETPOST('outjson','int') ? GETPOST('outjson','int') : 0);\n$action=GETPOST('action', 'alpha');\n$id=GETPOST('id', 'int');\n$showtype=GETPOST('showtype','int');", "\n/*\n * View\n */", "//print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER[\"PHP_SELF\"]).'?'.dol_escape_htmltag($_SERVER[\"QUERY_STRING\"]).' -->'.\"\\n\";", "dol_syslog(join(',', $_GET));\n//print_r($_GET);", "if (! empty($action) && $action == 'fetch' && ! empty($id))\n{\n\trequire_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';", "\t$outjson=array();", "\t$object = new Societe($db);\n\t$ret=$object->fetch($id);\n\tif ($ret > 0)\n\t{\n\t\t$outname=$object->name;\n\t\t$outlabel = '';\n\t\t$outdesc = '';\n\t\t$outtype = $object->type;", "\t\t$outjson = array('ref' => $outref,'name' => $outname,'desc' => $outdesc,'type' => $outtype);\n\t}", "\techo json_encode($outjson);\n}\nelse\n{\n\trequire_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';", "\t$langs->load(\"companies\");", "\ttop_httphead();", "\tif (empty($htmlname)) return;", "\t$match = preg_grep('/('.$htmlname.'[0-9]+)/',array_keys($_GET));\n\tsort($match);\n\t$id = (! empty($match[0]) ? $match[0] : '');", "\t// When used from jQuery, the search term is added as GET param \"term\".\n\t$searchkey=(($id && GETPOST($id, 'alpha'))?GETPOST($id, 'alpha'):(($htmlname && GETPOST($htmlname, 'alpha'))?GETPOST($htmlname, 'alpha'):''));", "\tif (! $searchkey) return;\n", "\t$form = new Form($db);", "\t$arrayresult=$form->select_thirdparty_list(0, $htmlname, $filter, 1, $showtype, 0, null, $searchkey, $outjson);", "\t$db->close();", "\tif ($outjson) print json_encode($arrayresult);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>\n * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>\n * Copyright (C) 2007-2011 Laurent Destailleur <eldy@users.sourceforge.net>\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */", "/**\n * \\file htdocs/societe/ajax/company.php\n * \\brief File to return Ajax response on thirdparty list request\n */", "if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1); // Disables token renewal\nif (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1');\nif (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1');\nif (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1');\nif (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1');\nif (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1');", "require '../../main.inc.php';", "$htmlname=GETPOST('htmlname','alpha');\n$filter=GETPOST('filter','alpha');\n$outjson=(GETPOST('outjson','int') ? GETPOST('outjson','int') : 0);\n$action=GETPOST('action', 'alpha');\n$id=GETPOST('id', 'int');\n$showtype=GETPOST('showtype','int');", "\n/*\n * View\n */", "//print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER[\"PHP_SELF\"]).'?'.dol_escape_htmltag($_SERVER[\"QUERY_STRING\"]).' -->'.\"\\n\";", "dol_syslog(join(',', $_GET));\n//print_r($_GET);", "if (! empty($action) && $action == 'fetch' && ! empty($id))\n{\n\trequire_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';", "\t$outjson=array();", "\t$object = new Societe($db);\n\t$ret=$object->fetch($id);\n\tif ($ret > 0)\n\t{\n\t\t$outname=$object->name;\n\t\t$outlabel = '';\n\t\t$outdesc = '';\n\t\t$outtype = $object->type;", "\t\t$outjson = array('ref' => $outref,'name' => $outname,'desc' => $outdesc,'type' => $outtype);\n\t}", "\techo json_encode($outjson);\n}\nelse\n{\n\trequire_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';", "\t$langs->load(\"companies\");", "\ttop_httphead();", "\tif (empty($htmlname)) return;", "\t$match = preg_grep('/('.$htmlname.'[0-9]+)/',array_keys($_GET));\n\tsort($match);\n\t$id = (! empty($match[0]) ? $match[0] : '');", "\t// When used from jQuery, the search term is added as GET param \"term\".\n\t$searchkey=(($id && GETPOST($id, 'alpha'))?GETPOST($id, 'alpha'):(($htmlname && GETPOST($htmlname, 'alpha'))?GETPOST($htmlname, 'alpha'):''));", "\tif (! $searchkey) return;\n", "\tif (! is_object($form)) $form = new Form($db);", "\t$arrayresult=$form->select_thirdparty_list(0, $htmlname, $filter, 1, $showtype, 0, null, $searchkey, $outjson);", "\t$db->close();", "\tif ($outjson) print json_encode($arrayresult);\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [1065, 1563, 1727, 91], "buggy_code_start_loc": [1047, 75, 292, 90], "filenames": ["htdocs/core/class/html.form.class.php", "htdocs/main.inc.php", "htdocs/product/card.php", "htdocs/societe/ajax/company.php"], "fixing_code_end_loc": [1069, 1566, 1727, 91], "fixing_code_start_loc": [1047, 75, 292, 90], "message": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dolibarr:dolibarr_erp\\/crm:7.0.3:*:*:*:*:*:*:*", "matchCriteriaId": "062A2152-D154-43D2-806C-E71F97F3F49E", "versionEndExcluding": null, "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SQL injection vulnerability in product/card.php in Dolibarr ERP/CRM version 7.0.3 allows remote attackers to execute arbitrary SQL commands via the status_batch parameter."}, {"lang": "es", "value": "Una vulnerabilidad de inyecci\u00f3n SQL en product/card.php en Dolibarr ERP/CRM 7.0.3 permite que atacantes remotos ejecuten comandos SQL arbitrarios mediante el par\u00e1metro status_batch."}], "evaluatorComment": null, "id": "CVE-2018-13450", "lastModified": "2018-09-05T19:20:50.167", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-08T16:29:00.500", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/Dolibarr/dolibarr/commit/36402c22eef49d60edd73a2f312f8e28fe0bd1cb"}, "type": "CWE-89"}
36
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/*********************************************************************\n class.sla.php", " SLA\n Peter Rotich <peter@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com", " Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.", " vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/", "class SLA extends VerySimpleModel\nimplements TemplateVariable {", " static $meta = array(\n 'table' => SLA_TABLE,\n 'pk' => array('id'),\n );", " const FLAG_ACTIVE = 0x0001;\n const FLAG_ESCALATE = 0x0002;\n const FLAG_NOALERTS = 0x0004;\n const FLAG_TRANSIENT = 0x0008;", " var $_config;", " function getId() {\n return $this->id;\n }", " function getName() {\n return $this->getLocal('name');\n }", " function getGracePeriod() {\n return $this->grace_period;\n }", " function getInfo() {\n $base = $this->ht;\n $base['isactive'] = $this->flags & self::FLAG_ACTIVE;\n $base['disable_overdue_alerts'] = $this->flags & self::FLAG_NOALERTS;\n $base['enable_priority_escalation'] = $this->flags & self::FLAG_ESCALATE;\n $base['transient'] = $this->flags & self::FLAG_TRANSIENT;\n return $base;\n }", " function getCreateDate() {\n return $this->created;\n }", " function getUpdateDate() {\n return $this->updated;\n }", " function isActive() {\n return $this->flags & self::FLAG_ACTIVE;\n }", " function isTransient() {\n return $this->flags & self::FLAG_TRANSIENT;\n }", " function sendAlerts() {\n return 0 === ($this->flags & self::FLAG_NOALERTS);\n }", " function alertOnOverdue() {\n return $this->sendAlerts();\n }", " function priorityEscalation() {\n return $this->flags && self::FLAG_ESCALATE;\n }", " function getTranslateTag($subtag) {\n return _H(sprintf('sla.%s.%s', $subtag, $this->getId()));\n }", " function getLocal($subtag) {\n $tag = $this->getTranslateTag($subtag);\n $T = CustomDataTranslation::translate($tag);\n return $T != $tag ? $T : $this->ht[$subtag];\n }", " static function getLocalById($id, $subtag, $default) {\n $tag = _H(sprintf('sla.%s.%s', $subtag, $id));\n $T = CustomDataTranslation::translate($tag);\n return $T != $tag ? $T : $default;\n }", " // TemplateVariable interface\n function asVar() {\n return $this->getName();\n }", " static function getVarScope() {\n return array(\n 'name' => __('Service Level Agreement'),\n 'graceperiod' => __(\"Grace Period (hrs)\"),\n );\n }", " function update($vars, &$errors) {", "", " if (!$vars['grace_period'])\n $errors['grace_period'] = __('Grace period required');\n elseif (!is_numeric($vars['grace_period']))\n $errors['grace_period'] = __('Numeric value required (in hours)');\n elseif ($vars['grace_period'] > 8760)\n $errors['grace_period'] = sprintf(\n __('%s cannot be more than 8760 hours'),\n __('Grace period')\n );", " if (!$vars['name'])\n $errors['name'] = __('Name is required');\n elseif (($sid=SLA::getIdByName($vars['name'])) && $sid!=$vars['id'])\n $errors['name'] = __('Name already exists');", " if ($errors)\n return false;", " $this->name = $vars['name'];\n $this->grace_period = $vars['grace_period'];\n $this->notes = Format::sanitize($vars['notes']);\n $this->flags =\n ($vars['isactive'] ? self::FLAG_ACTIVE : 0)\n | (isset($vars['disable_overdue_alerts']) ? self::FLAG_NOALERTS : 0)\n | (isset($vars['enable_priority_escalation']) ? self::FLAG_ESCALATE : 0)\n | (isset($vars['transient']) ? self::FLAG_TRANSIENT : 0);", " if ($this->save())\n return true;", " if (isset($this->id)) {\n $errors['err']=sprintf(__('Unable to update %s.'), __('this SLA plan'))\n .' '.__('Internal error occurred');\n } else {\n $errors['err']=sprintf(__('Unable to add %s.'), __('this SLA plan'))\n .' '.__('Internal error occurred');\n }", " return false;\n }", " function save($refetch=false) {\n if ($this->dirty)\n $this->updated = SqlFunction::NOW();", " return parent::save($refetch || $this->dirty);\n }", " function delete() {\n global $cfg;", " if(!$cfg || $cfg->getDefaultSLAId()==$this->getId())\n return false;", " //TODO: Use ORM to delete & update\n $id=$this->getId();\n $sql='DELETE FROM '.SLA_TABLE.' WHERE id='.db_input($id).' LIMIT 1';\n if(db_query($sql) && ($num=db_affected_rows())) {\n db_query('UPDATE '.DEPT_TABLE.' SET sla_id=0 WHERE sla_id='.db_input($id));\n db_query('UPDATE '.TOPIC_TABLE.' SET sla_id=0 WHERE sla_id='.db_input($id));\n db_query('UPDATE '.TICKET_TABLE.' SET sla_id='.db_input($cfg->getDefaultSLAId()).' WHERE sla_id='.db_input($id));\n }", " return $num;\n }", " /** static functions **/\n static function getSLAs($criteria=array()) {", " $slas = self::objects()\n ->order_by('name')\n ->values_flat('id', 'name', 'flags', 'grace_period');", " $entries = array();\n foreach ($slas as $row) {\n $row[2] = $row[2] & self::FLAG_ACTIVE;\n $entries[$row[0]] = sprintf(__('%s (%d hours - %s)'\n /* Tokens are <name> (<#> hours - <Active|Disabled>) */),\n self::getLocalById($row[0], 'name', $row[1]),\n $row[3],\n $row[2] ? __('Active') : __('Disabled'));\n }", " return $entries;\n }", " static function getSLAName($id) {\n $slas = static::getSLAs();\n return @$slas[$id];\n }", " static function getIdByName($name) {\n $row = static::objects()\n ->filter(array('name'=>$name))\n ->values_flat('id')\n ->first();", " return $row ? $row[0] : 0;\n }", " static function create($vars=false, &$errors=array()) {", "", " $sla = new static($vars);\n $sla->created = SqlFunction::NOW();\n return $sla;\n }", " static function __create($vars, &$errors=array()) {\n $sla = self::create($vars);\n $sla->save();\n return $sla;\n }\n}\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [210], "buggy_code_start_loc": [109], "filenames": ["include/class.sla.php"], "fixing_code_end_loc": [212], "fixing_code_start_loc": [109], "message": "include/class.sla.php in osTicket before 1.14.2 allows XSS via the SLA Name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "40AC6A28-57EF-482A-8D89-9DBB94CACD37", "versionEndExcluding": "1.14.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "include/class.sla.php in osTicket before 1.14.2 allows XSS via the SLA Name."}, {"lang": "es", "value": "En el archivo include/class.sla.php en osTicket versiones anteriores a la versi\u00f3n 1.14.2, permite un ataque de tipo XSS por medio del Nombre SLA."}], "evaluatorComment": null, "id": "CVE-2020-12629", "lastModified": "2020-05-06T20:44:34.660", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-05-04T13:15:13.047", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/compare/v1.14.1...v1.14.2"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osticket/osticket/commit/fc4c8608fa122f38673b9dddcb8fef4a15a9c884"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "https://www.exploit-db.com/exploits/48413"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osticket/osticket/commit/fc4c8608fa122f38673b9dddcb8fef4a15a9c884"}, "type": "CWE-79"}
37
Determine whether the {function_name} code is vulnerable or not.
[ "<?php\n/*********************************************************************\n class.sla.php", " SLA\n Peter Rotich <peter@osticket.com>\n Copyright (c) 2006-2013 osTicket\n http://www.osticket.com", " Released under the GNU General Public License WITHOUT ANY WARRANTY.\n See LICENSE.TXT for details.", " vim: expandtab sw=4 ts=4 sts=4:\n**********************************************************************/", "class SLA extends VerySimpleModel\nimplements TemplateVariable {", " static $meta = array(\n 'table' => SLA_TABLE,\n 'pk' => array('id'),\n );", " const FLAG_ACTIVE = 0x0001;\n const FLAG_ESCALATE = 0x0002;\n const FLAG_NOALERTS = 0x0004;\n const FLAG_TRANSIENT = 0x0008;", " var $_config;", " function getId() {\n return $this->id;\n }", " function getName() {\n return $this->getLocal('name');\n }", " function getGracePeriod() {\n return $this->grace_period;\n }", " function getInfo() {\n $base = $this->ht;\n $base['isactive'] = $this->flags & self::FLAG_ACTIVE;\n $base['disable_overdue_alerts'] = $this->flags & self::FLAG_NOALERTS;\n $base['enable_priority_escalation'] = $this->flags & self::FLAG_ESCALATE;\n $base['transient'] = $this->flags & self::FLAG_TRANSIENT;\n return $base;\n }", " function getCreateDate() {\n return $this->created;\n }", " function getUpdateDate() {\n return $this->updated;\n }", " function isActive() {\n return $this->flags & self::FLAG_ACTIVE;\n }", " function isTransient() {\n return $this->flags & self::FLAG_TRANSIENT;\n }", " function sendAlerts() {\n return 0 === ($this->flags & self::FLAG_NOALERTS);\n }", " function alertOnOverdue() {\n return $this->sendAlerts();\n }", " function priorityEscalation() {\n return $this->flags && self::FLAG_ESCALATE;\n }", " function getTranslateTag($subtag) {\n return _H(sprintf('sla.%s.%s', $subtag, $this->getId()));\n }", " function getLocal($subtag) {\n $tag = $this->getTranslateTag($subtag);\n $T = CustomDataTranslation::translate($tag);\n return $T != $tag ? $T : $this->ht[$subtag];\n }", " static function getLocalById($id, $subtag, $default) {\n $tag = _H(sprintf('sla.%s.%s', $subtag, $id));\n $T = CustomDataTranslation::translate($tag);\n return $T != $tag ? $T : $default;\n }", " // TemplateVariable interface\n function asVar() {\n return $this->getName();\n }", " static function getVarScope() {\n return array(\n 'name' => __('Service Level Agreement'),\n 'graceperiod' => __(\"Grace Period (hrs)\"),\n );\n }", " function update($vars, &$errors) {", " $vars = Format::htmlchars($vars);", " if (!$vars['grace_period'])\n $errors['grace_period'] = __('Grace period required');\n elseif (!is_numeric($vars['grace_period']))\n $errors['grace_period'] = __('Numeric value required (in hours)');\n elseif ($vars['grace_period'] > 8760)\n $errors['grace_period'] = sprintf(\n __('%s cannot be more than 8760 hours'),\n __('Grace period')\n );", " if (!$vars['name'])\n $errors['name'] = __('Name is required');\n elseif (($sid=SLA::getIdByName($vars['name'])) && $sid!=$vars['id'])\n $errors['name'] = __('Name already exists');", " if ($errors)\n return false;", " $this->name = $vars['name'];\n $this->grace_period = $vars['grace_period'];\n $this->notes = Format::sanitize($vars['notes']);\n $this->flags =\n ($vars['isactive'] ? self::FLAG_ACTIVE : 0)\n | (isset($vars['disable_overdue_alerts']) ? self::FLAG_NOALERTS : 0)\n | (isset($vars['enable_priority_escalation']) ? self::FLAG_ESCALATE : 0)\n | (isset($vars['transient']) ? self::FLAG_TRANSIENT : 0);", " if ($this->save())\n return true;", " if (isset($this->id)) {\n $errors['err']=sprintf(__('Unable to update %s.'), __('this SLA plan'))\n .' '.__('Internal error occurred');\n } else {\n $errors['err']=sprintf(__('Unable to add %s.'), __('this SLA plan'))\n .' '.__('Internal error occurred');\n }", " return false;\n }", " function save($refetch=false) {\n if ($this->dirty)\n $this->updated = SqlFunction::NOW();", " return parent::save($refetch || $this->dirty);\n }", " function delete() {\n global $cfg;", " if(!$cfg || $cfg->getDefaultSLAId()==$this->getId())\n return false;", " //TODO: Use ORM to delete & update\n $id=$this->getId();\n $sql='DELETE FROM '.SLA_TABLE.' WHERE id='.db_input($id).' LIMIT 1';\n if(db_query($sql) && ($num=db_affected_rows())) {\n db_query('UPDATE '.DEPT_TABLE.' SET sla_id=0 WHERE sla_id='.db_input($id));\n db_query('UPDATE '.TOPIC_TABLE.' SET sla_id=0 WHERE sla_id='.db_input($id));\n db_query('UPDATE '.TICKET_TABLE.' SET sla_id='.db_input($cfg->getDefaultSLAId()).' WHERE sla_id='.db_input($id));\n }", " return $num;\n }", " /** static functions **/\n static function getSLAs($criteria=array()) {", " $slas = self::objects()\n ->order_by('name')\n ->values_flat('id', 'name', 'flags', 'grace_period');", " $entries = array();\n foreach ($slas as $row) {\n $row[2] = $row[2] & self::FLAG_ACTIVE;\n $entries[$row[0]] = sprintf(__('%s (%d hours - %s)'\n /* Tokens are <name> (<#> hours - <Active|Disabled>) */),\n self::getLocalById($row[0], 'name', $row[1]),\n $row[3],\n $row[2] ? __('Active') : __('Disabled'));\n }", " return $entries;\n }", " static function getSLAName($id) {\n $slas = static::getSLAs();\n return @$slas[$id];\n }", " static function getIdByName($name) {\n $row = static::objects()\n ->filter(array('name'=>$name))\n ->values_flat('id')\n ->first();", " return $row ? $row[0] : 0;\n }", " static function create($vars=false, &$errors=array()) {", " $vars = Format::htmlchars($vars);", " $sla = new static($vars);\n $sla->created = SqlFunction::NOW();\n return $sla;\n }", " static function __create($vars, &$errors=array()) {\n $sla = self::create($vars);\n $sla->save();\n return $sla;\n }\n}\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [210], "buggy_code_start_loc": [109], "filenames": ["include/class.sla.php"], "fixing_code_end_loc": [212], "fixing_code_start_loc": [109], "message": "include/class.sla.php in osTicket before 1.14.2 allows XSS via the SLA Name.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:enhancesoft:osticket:*:*:*:*:*:*:*:*", "matchCriteriaId": "40AC6A28-57EF-482A-8D89-9DBB94CACD37", "versionEndExcluding": "1.14.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "include/class.sla.php in osTicket before 1.14.2 allows XSS via the SLA Name."}, {"lang": "es", "value": "En el archivo include/class.sla.php en osTicket versiones anteriores a la versi\u00f3n 1.14.2, permite un ataque de tipo XSS por medio del Nombre SLA."}], "evaluatorComment": null, "id": "CVE-2020-12629", "lastModified": "2020-05-06T20:44:34.660", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "LOW", "cvssData": {"accessComplexity": "MEDIUM", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "NONE", "baseScore": 3.5, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:M/Au:S/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 6.8, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": true}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 5.4, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "CHANGED", "userInteraction": "REQUIRED", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "version": "3.1"}, "exploitabilityScore": 2.3, "impactScore": 2.7, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2020-05-04T13:15:13.047", "references": [{"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osTicket/osTicket/compare/v1.14.1...v1.14.2"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/osticket/osticket/commit/fc4c8608fa122f38673b9dddcb8fef4a15a9c884"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory", "VDB Entry"], "url": "https://www.exploit-db.com/exploits/48413"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-79"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/osticket/osticket/commit/fc4c8608fa122f38673b9dddcb8fef4a15a9c884"}, "type": "CWE-79"}
37
Determine whether the {function_name} code is vulnerable or not.
[ "This file shows the changes in recent releases of MODX. The most current release is usually the\ndevelopment release, and is only shown to give an idea of what's currently in the pipeline.", "MODX Revolution 2.7.0-pl (TBD)\n====================================", "", "- Update phpThumb to 1.7.15-201806071234 #13938\n- Require minimal PHP version (in composer.json) #13939\n- Prefer ampersand replacement of the the translit class [#13931]\n- Add iconv_ascii transliteration [#13932]\n- Add set_sudo permission [#13807]\n- Log setlocale errors [#13878]\n- Various improvements regarding password generation and validation [#13923]\n- Make error.log location customizable [#13768]\n- Add system setting for partial resource cache clearing feature [#13588]\n- Prevent line-wrap in error log [#13843]\n- Add template icon for resources in search results in the uberbar [#13882]\n- Remove duplicate code of password generator and fix an issue with the empty value of password_generated_length setting [#13909]\n- Add ID number to manager pages (resources and elements) [#13914]\n- Add option to supply waitMsg on submit in MODX windows [#13915]\n- Show validation errors when setting a new user password [#13585]\n- Add CLI install script for use with composer create-project [#13790]\n- Allow extension packages to have an empty table_prefix [#13716]\n- Add wildcard support to form customization actions [#13775]\n- Make HTTPS server check accept any non-empty value [#13794]\n- Add ability to search by id on all objects in manager search [#13804]\n- Add automatic_template_assignment feature [#13700]\n- Media Browser optimizations [#13805]\n- Add \"Purge Old Versions\" button to the package version listing to clean up old versions [#12818]\n- New resource option \"Use current alias in alias path\" to allow hiding resources from the URI [#11153]\n- Make $modx->setDebug support E_LEVEL constants (e.g. E_NOTICE/E_ERROR) and fix setting debug to 1 not working [#12579]\n- Use stricter check for string type in resource tree to avoid uncaught error in edge cases [#13262]\n- Allow plugins OnDocFormRender to set templates with $resource->set('template', 3) [#13049]\n- Add \"filterPathSegment\" output filter to turn a string into url-safe string [#13699]\n- Make sure requests to containers without the container suffix are redirected to the right url with container suffix [#13142]\n- Ignore spaces in allowedExtensions properties and relevant system settings to ensure the right file types show up [#13702]\n- Add list of recent manager log entries to the Resource Overview page [#13734]\n- Prevent notices for undefined Smarty placeholders [#13748]\n- Remove some unused images [#13788]\n- Fix incorrect hex colors in TV input options description [#13776]\n- Change modResource.description column to text [#13802]", "MODX Revolution 2.6.4-pl (June 7, 2018)\n====================================\n- Fix sorting by access column in Template Access tab of Template Variable edit view [#13893]\n- Make sure category is not null before checking add_children permission when creating chunks [#13906]\n- Address various minor XSS issues in the manager [#13887]\n- Update xPDO to 2.7.0 to solve bug with getIterator and MODX Resource Group ACLs [#13889]\n- Update phpmailer from 5.2.21 to 5.2.26 to fix various security issues [#13886]", "MODX Revolution 2.6.3-pl (April, 19, 2018)\n====================================\n- Fix installation of transport packages with setup options [#13861]", "MODX Revolution 2.6.2-pl (March 30, 2018)\n====================================\n- Display context name and key in Context dropdown [#13839]\n- Only save properties modified from the default for an element in Property Sets [#13799]\n- Replace usages of each() to avoid deprecated warnings in PHP 7.2 [#13829]\n- Prevent adding ./ to filepath when in root of a mediasource [#13778]\n- Fix error with getonline processor on systems with only_full_group_by sql_mode [#13835]\n- Prevent logging errors for comments or empty tags [#13771]\n- Fix typo preventing verbose CURL option from being set in modRest [#13798]\n- Prevent http headers from being overwritten in modRest [#13797]\n- Fix sending messages to wrong recipients in message/create processor [#13796]\n- Stop sending too much data on package install request [#13813]\n- Add events permission to Administrator policy on new installs [#13830]\n- Remove max width from the tree sidebar [#13637]\n- Select the correct media source when editing a static element [#13750]\n- Fix the setup language being reset to English in the last step [#13611]\n- Fix incorrect view url after changing the resource url [#13768]\n- Fix silent fail on login without manager access [#12706]\n- Fix incorrect media source being used on image TVs when creating new resource in different context [#13609]", "MODX Revolution 2.6.1-pl (December 15, 2017)\n====================================\n- Increase efficiency of cache refresh on autopublish events [#13572]\n- Remove concatenated key from name field in Contexts grid [#13372]\n- Prevent infinite loop when a modSymLink refers to itself [#13710]\n- Get only unique template paths for manager controllers [#13717]\n- Ensure dashboard widget exists before calling methods on it [#13604]\n- Fix phpthumb issue in files tree and media browser [#13704]\n- Show correct Resource type icon in search results [#13705]\n- Allow callback if nothing is selected in MODx.browser [#13684]\n- Fix Flush Your Permissions top menu item [#13690]\n- Improve changelog display in package browser [#13677]\n- Revert behavior of image_width and image_height for media source images [#13672]\n- Fix CLI installation to properly detect MySQL server version [#13680]\n- Fix title format in various manager views [#13668]\n- Fix javascript issue on resources containing quotes [#13669]\n- Fix console error when editing resources with tv tab [#13683]\n- Fix invokeEvent call for new OnResourceCacheUpdate event [#13676]", "MODX Revolution 2.6.0-pl (November 1, 2017)\n====================================\n- Add top padding to .modx-alert and .modx-confirm classes [#13652]\n- Improve setUserGroups/addUsers methods [#13653]\n- Enable sorting by 'assigned' column in template variable grid [#13598]\n- Return better error message if group name already exists [#13600]\n- Hide empty template variable tabs in the resource panel [#13649]\n- Add .less, .scss, .sass and .css.map as default allowed upload file types [#13592]\n- Enable context setting overrides in modResource->cleanAlias() [#13622]\n- Add OPTIONS request method to modRestController [#13636]\n- Fix redirect when deleting elements [#13644]\n- Fix format of chunk title [#13643]\n- Prevent connector errors from invalid ctx parameter [#13627]\n- Fix processing of noncacheable elements inside cached [#13530]\n- Fix site_status issue when a session is not available [#13635]\n- Fix endless loop when error log is too big [#13632]\n- Fetch Lexicon lang and topic lists from database [#13599]\n- Add CSS class to TV containers [#13602]\n- Add OnResourceCacheUpdate event [#13590]\n- Add new Who's Online dashboard widget [#13545]\n- Additional SVG preview improvements [#13629]\n- Enable rendering of SVG previews in Media Browser [#13517]\n- Add stream upload support for binary files to modRestService [#13164]\n- Remove null-byte character check [#13581]\n- Add search/filtering to plugin event list [#13552]\n- Search improvements for user management [#13551]\n- Improve description of TemplateVariable Input Option Values [#13550]\n- Replace all hardcoded http versions by $_SERVER['SERVER_PROTOCOL'] [#13518]\n- Make searchbar accessible via assistive tech landmarks [#13437]\n- Make ContextResource optional in query for rebuilding contexts [#13360]\n- Reduce varchar and text index prefixes for utf8mb4 support in mysql [#13559]\n- Change new installs to create tables with InnoDB engine on mysql [#13462]\n- Fix set height of error log [#13566]\n- Reset user session token if it is set but value is empty [#13577]\n- Fix chmod feature on directories [#13580]\n- Fix resource tree ignoring hide_children_in_tree value [#13578]\n- Skip date format check when using resource quick update [#13534]\n- Fix ability to drag files more than once [#13533]\n- Fix permission check for updating user group settings [#13544]\n- Fix collapsing secondary buttons [#13558]\n- Add unique index for modTemplateVarResource values [#13535]\n- Fix media browser active state in tree [#13496]\n- Fix media browser tree refresh after creating a directory [#13501]\n- Prevent \"New User Group\" button being covered with long translations [#13555]\n- Add modx_media_sources_elements when a context is duplicated [#13529]\n- Remove resource template values when context is removed (cherry-pick) [#13525]\n- Fixed issue with incorrect signature during installing two packages with setup options (cherry-pick) [#13557]\n- Added loading error log only via ajax to avoiding blank page in case bad characters in log file [#13560]\n- Added DKIM attributes to PHPMailer [#13303]\n- Hide user group tree panel splitbar if center panel is hidden (cherry-pick) [#13520]\n- Added missing setting for primary user group during creating a new user [#13528]\n- Remove exposing of full path from error message when controller not found in the Manager [#13430]\n- Remove hardcoded modUser references in user processors [#13532]\n- Secondary button height fixes [#13543]\n- Add newNameField to modObjectDuplicateProcessor to correct error messages [#13521]\n- Added ability to duplicate a context from the contexts grid & while editing a context [#13540]\n- Honor the failed_login_attempts setting [#13516]\n- Added option to allow double encoding to htmlentities output modifier [#13325]\n- System events are now listed with their attached plugins [#13324]\n- Added ability to return custom error message via plugin when a user authenticates [#13204]\n- Create a new \"please wait\" windows on any package download instead of hide/show [#13506]\n- News & security feeds in the manager welcome page are now loaded using AJAX [#13507]\n- Added resource pagetitle & ID when deleting a resource [#13497]\n- Remove unused path_search and url_search processors in setup [#13433]\n- Fix logging an empty value in modUser->joinGroup() [#13445]\n- Fix featured flag in package listing not interpreting the string value [#13470]\n- Re-style the templated package provider thumbnail grid [#13274]\n- No addition on a JS string! [#13401]\n- Sessions are marked as staled after creating/updating/removing a user group/policy [#13311]\n- Clearing cache from the manager is now logged in manager actions [#13350]\n- Context sorting in trees is now enabled by default [#13356]\n- Add events for package install, uninstall, and remove [#12936]\n- Add setting to log when snippets are called that don't exist [#12984]\n- Added option to disable EVAL binding in TVs [#13224]\n- Allowing using keyboard modifiers to open some links in new tabs [#13103]\n- Pass properties to the OnRichTextBrowserInit event [#13110]\n- Add tag [^m^] to show used memory [#12981]\n- Add Delete button to chunk/snippet/plugins-window [#13245]\n- Add after(append) and before(prepend) output filters [#13021]\n- Add class_key and item filter to the Manager Log [#13005]\n- Change view_ permissions to edit_ permissions for elements in uberbar search [#13095]\n- Allow manually editing rank of contexts [#13097]\n- Pass the namespace to OnManagerPageInit event [#13104]\n- Add new line and spaces regex to input filter [#13115]\n- Add \"UserProfile events\" [#13153]\n- List empty as default template in system settings [#12975]\n- Add .x-form-display-field style [#12955]\n- Add the ability to generate custom manager \"top menus\" [#12554]\n- Replace dirname(dirname(__FILE__)) with dirname(__DIR__) [#13147]\n- Add User Group description to UserGroups grid (with row toggle) [#13130]\n- Add ExtJS Manager headers and descriptions components [#13118]\n- Made modX::addEventListener & modX::removeEventListener actually work\n- Correct email subscription form on help page [#13463]\n- Add ability to see changelog of extras before downloading the update [#13410]\n- Fix session_start error \"Session callback expects true/false\" on PHP 7 [#13041, #13073]\n- Prevent \"Call to member function get() on array\" error, caused by TinyMCE [#13085]\n- Prevent drag/dropping contexts when context_tree_sort is disabled [#13363]\n- Improve user messaging with an outbox and improved message listing [#13390]\n- Prevent dashboard breaking if a widget is missing a file [#13367]\n- Fix positioning of TVs on the first resource tab [#13318]\n- Prevent error on PHP 7 when using invalid output conditions [#13167]\n- Allow use of date/strftime output filter on date strings without strtotime output filter [#8161]\n- Make the save button available immediately when removing locks from the resource update page [#12028]\n- Add option to skip duplicating resources when duplicating a context [#13277]\n- Expand relative base paths in the file media source [#13295]\n- Added pagetitle of the resource that has been duplicating into the title of duplication window [#13475]\n- Fix incorrect pending changes warning when a resource was set to the empty template [#13483]\n- Add optional $byName attribute to modResource->joinGroup to force joining a numeric group [#4014]\n- Allow default TV values to use @BINDINGs [#3454]\n- Make sure log_target being empty defaults to FILE instead of ECHO [#7659]\n- Allow javascript handlers to be executed in the user-nav [#13094]\n- Make sure the scripts cache uses the right file permissions [#12677]\n- Add support for new_folder_permissions_cache and new_file_permissions_cache settings to change permissions on cache folders [#12677]\n- Add new modDirectory->getFiles() method to list files/folders in a directory [#13096]\n- Some modRest refactoring to clean up code style and doctypes [#13133]\n- Fix output filter handling of non-existent TV tags to be consistent with placeholders [#13203]\n- Automatically change to the resource tab that holds an error when encountering a validation error saving a resource [#13202]\n- Move OnFileManagerBeforeUpload event so it can also be used to prevent uploads or change file info [#13067]\n- Lower memory usage of duplicating contexts with lots of children [#13217]", "MODX Revolution 2.5.8-pl (TBD)\n====================================\n- Use pageSize from system settings for system settings grid [#13493]\n- Fix date format for created field of package in the package provider [#13509]\n- Add a mouseout listener to the 'Clear Filter' buttons across the manager [#13510]\n- Add view_template:true for the \"Content Editor\" access policy [#13508]\n- Refresh the parent (resource) node when creating the first children [#13499]\n- Refresh element in tree after changing name in element's panel [#13502]\n- Remove unused path_search and url_search processors\n- Fix logging an empty value\n- Update xPDO to fix issue with validation rules", "MODX Revolution 2.5.7-pl (April 20, 2017)\n====================================\n- Try all available methods when attempting to download transport packages [#13419]\n- Prevent stored XSS in UserGroup names and various other fields [#13418]\n- Prevent user/email enumeration in forgot password feature [#13408]\n- Prevent XSS cache poisoning via Host header [#13426]\n- Proper use of json_encode and error handling for outputArray() in processors [#13389]\n- Prevent reflected XSS in setup [#13424]\n- Fix local file inclusion vulnerability in setup action parameter [#13422]\n- Fix various local file inclusion preventions to also protect on windows [#13428]\n- Remove htaccess from allowed file types on new installations [#13423]\n- Prevent stored XSS in resource pagetitle [#13415]\n- Make search bar work as expected on Chrome & Firefox [#13405]", "MODX Revolution 2.5.6-pl (March 28, 2017)\n====================================\n- Enable Resource Group access column to be sorted [#12426]\n- Prevent warning from array_key_exists when aliasMap not available [#13297]\n- Fix broken images in File tree when media source above doc root [#13292]\n- Encode HTML in the template description to prevent potential XSS [#13290]\n- Use (but limit) setting for results per page in package management grid [#12518]\n- Added validation for min and max length of text TV configuration [#9039]\n- Allow value '0' for multi select TV items [#9492]\n- Fix \"undefined\" on package management breadcrumb when updating [#12567]\n- Reduce log level to INFO for links not found by modContext->makeUrl() [#13268]\n- Fix error in Firefox preventing using enter in the uberbar [#12714]\n- Fix error when deleting a file from a TV [#12417]\n- On new installs set base_help_url setting to the new docs subdomain [#13309]\n- Refresh resource tree and context grid on create and delete [#12495]\n- Only call generateContext once when saving a resource [#13347]\n- In get/setTVValue, consider numeric strings as ID instead of name [#12542]\n- Validate chmod input [#13352]\n- Prevent drag/drop of directories messing up directory structures [#13165]\n- Get rid of duplicate scrollbars in the help window [#12914]\n- Show proper error page when viewing an inaccessible symlink [#12380]\n- Avoid duplication of modLexiconEntry objects when updating context settings [#12823]\n- Fix system info's database tables tab on sqlsrv [#9854]\n- Add comment to config.core.php files that its contents are overwritten on update [#10299]\n- Fix double dots in the filename of downloaded static resources [#10267]\n- Fix duplicating resource children which are hidden from the tree [#13298]\n- Show proper error message when trying to rename a file/folder that already exists [#13256]\n- Fix missing caption when duplicating a TV via the Edit TV page [#13317]\n- Fix empty error popup when adding a usergroup to a media source without a policy [#12701]\n- Fix close button on resource overview page [#12822]\n- Hide database username, password and database name from advanced setup [#13090]\n- Fix \"Cannot read property 'style' of undefined\" error when resizing viewport after closing a modal [#13294]\n- Fix \"o.field is undefined\" error when checking a resource group [#13296]\n- Fix phpdoc for modAccessibleObject->checkPolicy [#13301]", "MODX Revolution 2.5.5-pl (February 8, 2017)\n====================================\n- Respect new_file_permissions setting when create/upload files in manager [#13246]\n- Escape regular expression special characters in last query string of a superboxselect [#13236]\n- Improve logging of bad links [#13268]\n- Fix a few Smarty variables not being defined [#13117]\n- Only load manager layout when the controller is not \"browser\" [#13135]\n- Add autoHeight in the Create/UpdateSetting window [#13220]\n- Address various potential security issues in setup [#13261]\n- Validate file extension when renaming/creating files in file browser [#13240]\n- Examples to rewrite all domains of one installation with/without www [#13249]\n- Update MODX Transport Provider to use SSL URL [#13260]\n- Add site name to the login title [#13254]\n- Fix File Unzip feature [#13223]\n- Fix truncating filename at space by downloading via filemanager [#13171]", "MODX Revolution 2.5.4-pl (January 3, 2017)\n====================================\n- Update xPDO to 2.5.3 release to avoid xPDOQuery class not found error", "MODX Revolution 2.5.3-pl (January 3, 2017)\n====================================\n- Fix listing packages on systems with non-utf8 locales [#13182]\n- Update PHPMailer to 5.2.21 for CVE-2016-10045 patch [#13229]\n- Access chunk array instead of chunk object instance [#13210]\n- Update PhpMailer to 5.2.19 to protect against RCE vulnerability [#13227]\n- Add various missing permission checks to processors [#13174]\n- Update xPDO to 2.5.2 release\n- Improve phpThumb InitializeTempDirSetting [#13151]\n- Validate Resources when dropped onto weblinks and symlinks [#13212]\n- Fix Resources not loading in the tree in sqlsrv [#12845]\n- More specific removal of critical settings in MODX.config [#13180]\n- Fix broken list of previously installed package versions [#13179]\n- Fix incorrect media source name on Files tab [#12596]\n- Update Font Awesome to 4.7.0\n- Remove placeholders from login screen to fix accessibility bug/confusing screenreading [#13186]", "MODX Revolution 2.5.2-pl (November 14, 2016)\n====================================\n- [SECURITY] Hide critical settings in MODx.config [#13170]\n- [SECURITY] Prevent local file inclusion/traversal/manipulation [#13177]\n- [SECURITY] Prevent path traversal in $modx->runProcessor [#13176]\n- [SECURITY] Prevent unauthenticated access to processors [#13175]\n- [SECURITY] Prevent path traversal in modConnectorResponse action param [#13173]\n- [SECURITY] Update xPDO to 2.5.1 release\n- Add security/login support for action based connector [#13158]\n- Make one single connector file possible [#13157]\n- Don't create a DirectoryIterator on non existing folders [#13127]\n- Fixing tvLabel output filter empty needle warning [#13138]\n- Fix session extension call using action based connector [#13146]\n- Select modTemplateVarTemplate.rank for MySQL 5.7 ONLY_FULL_GROUP_BY SQL Mode [#13098]\n- Fix new category option duplicating view of elements [#13137]\n- Consistency in error messages, based on error type [#13126]\n- Make sure things do not break when no valid json/empty string is returned OnMediaSourceGetProperties event [#13119]\n- Removed superfluous code in the manager \"gateway\" [#13120]\n- Set temporary directory for files processing in phpThumb [#13128]\n- Upgraded phpThumb to 1.7.14-201608101311 [#13125]\n- Force display errors during setup [#13107]\n- Added duplicating caption field for TVs [#13100]\n- Fix PHP warning if the response message is empty [#13111]\n- Removed duplicate element ID [#13105]", "MODX Revolution 2.5.1-pl (July 21, 2016)\n====================================\n- Preserve original behavior for 3PC RTE TVs [#13071]\n- Fix with of install button after text change [#13078]\n- Fix server port check in setup start script [#13037]\n- Update phpThumb to version 1.7.14 [#13039]\n- Show image preview in file tree for S3 media source [#13059]\n- Fix problem with S3 bucket names containing dots [#13031]\n- Add missing properties in modX class [#13035]\n- Fix pagination in the \"New event create\" dialog [#13062]\n- Fixing padding-top issue in MODx.Window [#13038]\n- Use sans-serif font for TV textareas [#13045]\n- Prevent reflected XSS in connector's JSONP support [#13051]\n- Fix a SQL injection [#13052]\n- Fix uberbar user search return invalid User ID [#13056]\n- Fix width of the install button [#13057]\n- Extended grunt build tasks [#13026]\n- Remove deprecated curl option [#13032]\n- Show resources marked as container with a folder icon in the tree, even if it has no children. [#13027]\n- Restore missing Duplicate buttons on weblinks and symlinks [#12910]\n- Fix changing labels via manager customisations on checkboxes [#12890]\n- Fix extracting the title if it contains newlines when importing HTML [#12937]\n- Fix code smell issues in modPhpThumb [#13022]\n- Prevent using double quotes in extended user fields and containers to prevent breaking the context menu [#13012]\n- Fix saving a resource if the pagetitle of the parent contains tags [#13017]\n- Fix JavaScript error when editing an extended user field that contains markup [#12841]\n- Increase the delay for opening top nav menu items to 0.5s to prevent misclicks [#12931]\n- Allow email addresses validated by the extjs email vtype to have longer TLDs [#12940]\n- Fix updating user settings [#12988]\n- Fixed permissions for new files [#13000]\n- Fix for 500 error after install using STRICT_TRANS_TABLES mode in mySQL [#13001]\n- Fixed typo in scss [#12993]\n- Remove all traces of manager HTML5 cache manifest [#12985]\n- Fix rare database connection setup error (new installs/advanced upgrades) [#12997]\n- Remove :first-of-type, reduce padding on container [#12973]\n- Fix problem with multiple placeholders in a system setting [#12692]\n- Set correct title to edit fc set [#12974]\n- Corrected $_lang array index and $_lang string typo [#12979]\n- Error 500 + installer fails when MYSQL Strict SQL Mode is ON [#12838]\n- Use rawurlencode in modparser [#12675]\n- Reference to values passed by reference got lost [#12951]\n- Add uri to mysql/modcontext.class.php [#12971]\n- Add missing viewport meta tag needed to enable the responsive manager [#12977]\n- Avoid empty manager theme [#12989]\n- Fix: expression is always true [#12956]\n- Make sure uberbar resource search respects ACLs [#12960]", "MODX Revolution 2.5.0-pl (April 21, 2016)\n====================================\n- Fix issue where site_start and default_template settings get the wrong ID on certain environments [#12959]\n- Replace hard-coded charset in Default template with MODX setting [#12916]", "MODX Revolution 2.5.0-rc2 (April 6, 2016)\n====================================\n- Set the leaf property to true instead of 1 [#12734]\n- Increase the space between the content and the logo areas in the base template [#12898]\n- Add missing preserve_menuindex setting [#12905]\n- Fix displaying categories in Package Manager\n- Update FileAPI to 2.0.20\n- Fixing partial import of content with UTF-8 chars inside [#12896]\n- Fix Media Browser when compress_js is enabled [#12899]\n- Restore backwards compatibility in updated Smarty [#12897]", "MODX Revolution 2.5.0-rc1 (February 3, 2016)\n====================================\n- Implement X-Powered-By header to send \"MODX Revolution\" on all requests [#12885]\n- Add cleanup script to remove legacy files during upgrades\n- Fix installed package list in package detail page when the package's name has spaces [#12870]\n- Add filter and search to the templates grind in TV panel [#12873]\n- Add typeahead for templates in resource panel [#12872]\n- Fix session warning on HHVM [#12868]\n- Add new stripmodxtags output filter [#12860]\n- Add new base template and resource content [#12855]\n- Fix re-definition of function mkdirs\n- Add `createdon` date field to modUser [#12581]\n- Ensure $restarted in templates/language.tpl always exists [#12847]\n- Update LinkedIn link description on Help page [#12851]\n- Fix undefined index in modOutputFilter->filter [#12856]\n- Add new output filter 'htmlspecial' [#12861]\n- compress_js no longer dynamically minifies javascript, instead it uses a prebuilt min.js for better performance [#12611]\n- Autoload third party packages when viewing manager actions [#11866]\n- Fix example core/ht.access file to properly lock down access to the core when used [#12503]\n- Fix selecting values on the tag TV input type [#12627]\n- Fix the insert element by drag & drop feature remembering properties it shouldn't [#12729]\n- Potential improved speed on certain pages thanks to processElementTags optimisation [#12717]\n- Fix checking for duplicate URIs when resources are unpublished [#12844]\n- Add border for grids\n- Change modResource Children to Composite relation [#12279]\n- Allow searching by Resource ID in Uberbar [#12783]\n- Add modParsedManagerController which can be used for developing CMPs with snippets and chunks [#12555]\n- Allow custom redirect method for each action button in action bar\n- Fire emptyTrash event after emptying recycle bin [#12673]\n- Add anonymous_sessions to allow session-less access for anonymous users [#12616]\n- Make the manager a lot more mobile friendly [#12776]\n- Fix .icon-coffee class to show a coffee cup, use .icon-coffeescript for the code icon [#12784]\n- Update Font Awesome to 4.5 (includes `icon-modx`!) [#12774]\n- Make use of the maximum available height when viewing the error log [#12746]\n- Improve usability of the tree by limiting click target for editing containers to the name [#12773]\n- Add published_resources and unpublished_resources to result of OnResourceAutoPublish event [#12747]\n- Improve keyboard navigation and screen reader support on the login screen [#12784]\n- Update PHPMailer to 5.2.14: https://github.com/PHPMailer/PHPMailer/releases/tag/v5.2.14 [#12808]\n- Update Smarty to 3.1.27: https://github.com/smarty-php/smarty/blob/v3.1.27/change_log.txt [#12807]\n- Allow uberbar labels and icons to be set server-side in extended search processors [#12749]\n- Add ability to unpack zip files in the file tree / media manager [#12775]\n- Ensure setup can continue if date.timezone is not set [#12738]\n- Make modPhpThumb class compatible with PHP7 [#12809]", "MODX Revolution 2.4.4-pl (April 5, 2016)\n====================================\n- Make sure only recipient can mark user messages read/unread [#12944]\n- Do not attempt to clean cache_db_handler if cache_db not enabled [#12942]\n- Fix broken output filters on undefined placeholders introduced by #12835 [#12906]", "MODX Revolution 2.4.3-pl (February 11, 2016)\n====================================\n- Various config_check improvements [#12628]\n- Fix error embedding images in modPhpMailer [#12645]\n- Prevent uncacheable elements from being cached in cacheable elements [#12835]\n- Fix the DocBlock comment for leaveGroup() [#12877]\n- Fix modX->getUser to force load settings when parameter is passed [#12840]\n- Fix issue with parent name not showing when creating a new resource under a parent [#12849]\n- Fix system settings pagination issue if default_per_page is > 30 [#12862]\n- Remove the 'Installed on' part of the language string.\n- Fix getOption call in modUser->getProfilePhoto\n- Sets correct responseType in the rest service for multiple packages via a single request [#12669]\n- Fix loading rich text editors on non-document resource types [#12632]\n- Fix dashboard and dashboard widget save button [#12711]\n- Fix failure message in Export processor [#12709]\n- Fix tree style for deactivated plugin [#12712]\n- Fix fatal error if user not found [#12772]\n- Fix warning generated by configcheck dashboard widget if safe_mode or open_basedir is enabled [#12745]\n- Include a random hash for core assets being loaded to refresh browser caches [#12700]\n- Fix fatal errors in the manager on PHP7 [#12741]\n- Fix \"Remember Me\" on the manager login [#12802]\n- Show message after triggering a URI refresh [#12800]", "MODX Revolution 2.4.2-pl (October 6, 2015)\n====================================\n- Fix emptying property sets on element save [#12580]\n- Different tree styles for unpublished + hidemenu [#12699]\n- Add patch for ExtJS Drag & Drop issue [#12617]\n- Fix initialization of modUserGroupSettingUpdateProcessor processor [#12678]\n- Add resource title in Manager Log for edited resources [#12589]\n- Update Font-Awesome to 4.4 [#12598]\n- Update setup to check the minimum supported PHP version [#12637]\n- Add hover effect to tree expand/collapse icon [#12664]\n- Fix not rendering output properties of custom TVs [#12635]\n- Fix image width and add transparency pattern [#12670]\n- Disable trash icon and set proper tooltip after removing resources [#12672]\n- Pass 0 as id of default property set instead of \"Default\" [#12674]", "MODX Revolution 2.4.1-pl (September 23, 2015)\n====================================\n- Update PHPMailer to v5.2.13\n- Make user grid in ACL view consistent with user group view\n- Update xPDO to 2.4.1-pl\n- Fix dropping elements in template [#12572]\n- On policy template update sync policies with policy template [#12654]\n- Restore backwards compatibility for addons interacting with modTransportProvider [#12633]", "MODX Revolution 2.4.0-pl (August 18, 2015)\n====================================\n- Preselect core namespace if it is available in namespace combo box [#12562]\n- Fix namespace and policy filter in namespace access grid [#12560]\n- Escape Site name in header\n- Fix double nocompress option in advanced install", "MODX Revolution 2.4.0-rc1 (August 12, 2015)\n====================================\n- Fix installing package dependencies when there are setup options [#12556]\n- Fix potential E_RECOVERABLE (and other) errors in package download [#12543]\n- Add missing return statement in the package download processor [#12539]\n- Allow comma-separated list of constraints in Form Customization [#11239]\n- Prevent firing OnDoc*Form* Events on the Resource Overview page [#11865]\n- Automatically select the setup language based on Accept Language headers [#12011]\n- Change the modUserProfile.country field to use ISO codes rather than localised country names [#12534]\n- Add ability to prefill certain resource values in OnDocFormRender [#12535]\n- Allow setup options in packages to execute javascript [#12298]\n- Allow pressing enter in text areas [#12524]\n- Make sure registered CSS/JS are loaded on deprecated manager controllers [#12529]\n- New setting manager_use_fullname will show the fullname of the logged in user, instead of the username [#12527]\n- Parse the forgot_login_email message using the parser, to allow lexicons or other tags in the email [#12266]\n- Show error message when grid autosave fails\n- Disable setup options button when dependencies are not met [#12531]\n- Add config check to make sure the core folder is not web accessible [#12504]\n- Add ability to search for resources by template in resource/search processor [#12268]\n- Add download() method to modFileHandler [#11371]\n- Remove unnecessary caching headers from the manager request [#12254]\n- Fix logout from manager in case of broken javascript [#12344]\n- Fix limited width of TV descriptions [#12494]\n- Convert usergroup tree to usergroup tree & grid in ACL page\n- Prevent dashboard widgets with no output to be displayed\n- Add a reference of executed modPlugin object in modSystemEvent\n- Add JSONP support to the modConnectorResponse\n- Travis-CI automated test suite\n- Enhance config check style & add check for min PHP version\n- Log login action\n- Log empty trash action\n- Prevent displaying packages without a name from package provider\n- Fix adding anonymous use group to ACL groups\n- Clean \"onAjaxException\" to remove full HTML document tag to avoid breaking manager\n- Target user menu wrapper to change \"sub menu direction\" instead of targeted IDs\n- Implement new use_frozen_parent_uris option to respect frozen parent URIs in generating child URIs\n- System Events Manager page\n- Anonymous username as System Setting\n- Prevent JS error when Media Source is not in the first combo store page\n- Add regexp validation into text TV\n- Various MySQL performance optimizations via new database indexes\n- Fix TV's output properties column name in get properties processor\n- Auto suggest setting key in contexts and users settings\n- Add namespace permissions\n- Added Property Set file and color input field\n- Added option to not submit the emptyText of a form field\n- Links in description for extras opens in new tabs\n- Added ability send to provider information about language\n- Fixing cancel button not actually closing the popup window\n- a11y enhancements\n- Added qtip for tree root nodes & media sources to display their description\n- Updated setting groupingConfig options to grid\n- Media browser improvements\n- Fixed import HTML unicode error\n- Added tvLabel output modified\n- Added user photo profile field to user panel\n- Added system settings to enable customization of the top bar navigation\n- Added modMenu.description as tooltip in menu tree\n- Added ability to customize media source icons\n- Added ability to edit a media source from the files tree\n- Added ability to customize context icons\n- Added rank parameter to modUser->joinGroup method\n- Added rank to categories\n- Fixed package browser tree\n- Added package dependencies\n- Added contentType=string option to modRestCurlClient service [#11279]\n- Added realtime resource alias generation [#11799]\n- Added saveObject and removeObject methods to create and update processors [#12345]\n- Improved error message styling in the manager [#12349]\n- Added new option to date TV to hide the time from the users [#12348]", "MODX Revolution 2.3.6-dev\n====================================\n- Unset modx.user.userGroups in leaveGroup [#12410]\n- Fix fatal error when the database password contains a quote [#12528]\n- Fix several \"language string not found\" errors [#12546, #12545]\n- Add ability to disable on the fly compression to traditional installs [#12486]\n- Fix output of [^p^] tag on certain locales [#12514]\n- Fix counting rank of dashboard widgets [#12437]\n- Prevent XSS in file create/update processors [#12513]\n- Fix checking modMenu permissions with the same action value [#12361, #12255]\n- Fix missing pagination on category dropdowns [#12469]\n- Setup Options window is now bigger and grows as needed [#12297]\n- Set request-specific cultureKey option dynamically [#12227]\n- Make sure object processors pass a generic $object alongside the $objectType-based variable [#12243]\n- Fix issue editing users when extended fields contain multibyte characters [#12484]\n- Limit the size of images in Image TVs to 400px [#12498]\n- Show MODX version and flavor as tooltip on the MODX logo [#12496]\n- Normalize thumbnail size for image TV\n- Set default background color for thumbs to WHITE instead of BLACK\n- Updated default uploadable file types, including SVG and TIFF [#12526]", "MODX Revolution 2.3.5-pl (June 25, 2015)\n====================================\n- Fix Account dropdown hover on small screens\n- Compile Sass with libsass\n- Update npm packages\n- Update and Relax bower packages\n- Fix D&D resource sort when auto_isfolder setting is enabled", "MODX Revolution 2.3.4-pl (June 23, 2015)\n====================================\n- Allow access via id or alias when request_method_strict is false\n- Fix resource caching in multiple contexts\n- Bypass aliasMap for preview urls in manager\n- Fix custom theme CSS\n- Add Element/Resource name to the Quick update window's title\n- Improve drag & drop resource sorting\n- Fix row edit in site schedule grid\n- Fix float value of input options\n- Correct permission for Contexts menu item to \"view_context\"\n- Show the template icons at the template tree section\n- Fix saving binary field when creating content type\n- Fix edit action for S3 media source\n- Prevent using Ext.getCmp() when not needed in resource tree\n- Improvement to news and security widget DNS check\n- Better modMenu management\n- Set media source config in RTE media browser\n- Don't count Resources hidden from tree as children\n- Hide the \"Forgot your login?\" link if allow_manager_login_forgot_password is set to false\n- Update logo on setup page\n- Remove unnecessary DIV from file TV tpl\n- Remove unnecessary DIV from image TV tpl\n- Remove resource locks correctly based on current user\n- Fix tooltip full viewport width\n- Update Font Awesome to version 4.3.0\n- Update bower to build css correctly", "MODX Revolution 2.3.3-pl (January 29, 2015)\n====================================\n- Add OnCacheUpdate event to refresh() method\n- Check for valid google.com DNS before trying to load feeds\n- Fix case of table_prefix and service_class in modX->_loadExtensionPackages()\n- Fixed showing RTE in all resource types\n- Fixed sorting in MODX browser\n- Fixed updating resources from recent resources in user's profile\n- Fixed duplicating user\n- Unset modx.user.userGroups in joinGroup()\n- Use window.location.search to populate MODx.request\n- Added option to delete property from Property Set using the UI\n- Fixed preserving locked attribute in elements after quick update\n- Allow copy&paste system information page\n- Fixed urlAbsolute path in media sources\n- Fixed column width grid head/content\n- Fixed connector's URL when getting media source list\n- Make syncsite checkbox a system setting\n- Added system setting for automatic/manual switching container property in resources\n- Fixed showing lock tree icon for locked resources\n- Fixed @INHERIT binding in TVs\n- Make FC profiles sortable by template\n- Removed limit to getnodes for menu items\n- Fixed error message and missed lexicon for create chunk\n- Fix timezone problem\n- Fix javascript error while revert to default new property\n- Hide Duplicate buttons from Resource panel when user don't have permissions\n- Fix Password tab visible in edit profile to users without permission\n- Remove C:\\fakepath\\ from filename when importing property sets\n- Fix unnecessary scrollbars in windows\n- Fix wrong error message for creating new namespace\n- Remove limit from modx-combo-category combobox\n- Improved generateContext method to be quicker\n- Fixed loading theme based styles on login screen\n- Fixed selecting the same file to upload again\n- Fixed removing plugin from an event via the Update plugin event window\n- Fixed autoredirect after creating user\n- Fix context settings remove and update from window\n- Fixed showing minLength and maxLength value in error msg for text TVs\n- Prevent $this->resourceArray['resource_groups'] from being undefined\n- Fixed disabling caching of a chunk's output\n- Fixed Duplicate resource button visibility\n- Updated memberof output filter to return integer\n- Fixed setting resource as it's own parent\n- Trim setting's key before saving\n- Sort plugin events by enabled\n- Restore permission for menu help\n- Fixed processor path in user panel\n- Move refreshURIs() call from clear cache to new menu item Refresh URIs\n- Fix uploading packages on Windows", "MODX Revolution 2.3.2-pl (October 21, 2014)\n====================================\n- Fixed issue with S3 buckets containing dots\n- Fixes issue with Form Customizations containing multiple constraints on TVs\n- Single-Select TVs now retain custom values in the dropdown select options\n- Fixed birthdate on 1970/01/01 resulting in false\n- Restores horizontal scrolling to the Resource tree [#11949]\n- Language simplification for context menu items\n- Fixed property set creation which allowed empty 'name'\n- Fix for arrow that pointed wrong way in collapse areas\n- Fixed rendering TVs to modx-resource-content by Manager customizations\n- Fix default category name when creating a new element instead of showing 0\n- Fix store load if init combobox value is 0\n- Display context name in combo box\n- Fixed elements search results icons\n- Removed listeners/actions on Media browser data view double click\n- Added visual indication in elements trees when an element is edited (active class)\n- Removed unused code in Resource Tree Panel\n- Enable path style on AWS driver if the bucket's name contains a dot\n- More use of 'manager_date_format' in the manager\n- Use FontAwesome checkbox icons instead of sprite images\n- Made MODx.combo.Browser Media Source defaulting to the defined default Media source instead of hard coded id \"1\"\n- Replace security/forms/set/export processor with a class based one and fix\n- Fixed issue where batch removing access policies was only allowed for \"core\" policies (instead of preventing deletion for core policies)\n- Updated alias length to 255 in ExtJS\n- Fix superbox selects in toolbars\n- Prevent combobox lists being taller than the screen, mainly from windows\n- Fix MODx.Ajax.request ot handle multiple concurrent requests\n- Fix loading default manager controller without changing the manager theme when the manager theme does not include the requested controller\n- Fix encoded htmlspecialchars in resource overview > cache output tab\n- Fix creation of folders in S3 media source root\n- Disable keyboard shortcut to focus the search bar\n- Updated \"far\" parameter to \"C\" (to provide correct thumbnails aspect ratio) in modfilemediasource\n- When using resource_tree_node_tooltip system setting, make sure the given field is not empty before displaying the quick tip\n- Updated welcome url for 2.3\n- User / User Group Settings update and delete fix\n- Fixed modx_user_group_settings table on SQLServer\n- Make sure modContext config is \"prepared\" before using makeUrl()\n- Have [[++server_port]] report the port number\n- Consider dev version lower than alpha\n- Handles \"site preview\" when default_context is not \"web\" context or when manager is on its own (sub)domain\n- Fixes missing Permissions tabs for anonymous User Group\n- Updated modPHPMailer to use getService instead of creating new instance of modError\n- Refresh context's name in tree after changing it\n- Use modx_browser_default_sort setting for sorting in RTE browser\n- Fix front-end user group comparison bug when assigning new user groups [#11399]\n- Prevent XSS via GET param for manager controller action [#11966]\n- Fix CRC icons in tree\n- Refresh/expand appropriate tree node when creating a resource using \"quick create\"\n- Limit property set name/description length\n- Added ability to update a namespace within a window\n- Use lexicon strings instead of hard coded ones in manager login form\n- Display an error when updating a user from grid with duplicate email address\n- Create new instance of console on every action with package manager\n- Reset addresses list on failure send\n- Fixed superboxselect close button in Safari\n- Fixed typo forcing empty calls to modError::addError() for all sent emails\n- Fixed issue with tree node \"jump\" on expand/collapse\n- Added some client side validation when creating a new user group\n- Fixed mimetype issue on s3 Media Source\n- Do not display setting modification date if no modification has been done [#11762]\n- Moved user groups access tabs within a single permissions tab [#11769]\n- Make use of FontAwesome for files icons [#11851]\n- Fixed issue where required field was not highlighted [#11826]\n- Updated NodeJS dependencies [#11827]\n- Removed limit on Media Sources in the tree panel [#11834]\n- File and directory sorting improvements, more natural and consistent [#10286]\n- Accessibility improvements for new checkbox / radios [#11772]", "MODX Revolution 2.3.1-pl (July 22, 2014)\n====================================\n- Make Gravatar optional (enabled by default)\n- Update logos, login and help view\n- Update base_help_url to be protocol relative\n- Fix login after a session expired [#11763]\n- Fix manager menus for sqlsrv driver [#11677]\n- Refactor validation of a connector being included [#11738]\n- Updated RSS security feed to be Revo specific [#9440]\n- Do not output modScript include result w/o explicit string return [#11705]\n- Move OnInitCulture event to parser service [#10366]\n- Fix password reset feature [#11725]\n- Adjust appearance of saving window for new design\n- Fix labels / TVs in custom FC tabs [#11758]\n- Fix hover-preview thumbnail border width in Files tree\n- Fix long category name overflow in vertical tabs [#11728]\n- Enable usernav menus for mobile devices\n- Update phpthumb release to v1.7.13 [#11742]\n- Fix pagination in Topic combobox [#11713]\n- Simplify Gravatar profile image fallback [#11716]\n- Correct duplicate method declarations in phpthumb class [#11700]", "MODX Revolution 2.3.0-pl (July 15, 2014)\n====================================\n- Respect automatic_alias regardless of friendly_urls\n- Prevent use of GET vars in login controller/processor\n- Restrict returnUrl in login processor to url of login context\n- Added drag/drop reordering of template variables on the templates TV grid [#11560]\n- Added ability to use conditional custom output modifiers [#11610]\n- Updated MagpieRSS Snoopy to 2.0.0\n- Add strftime as alias for date output filter [#11550]\n- Validate and sanitize _ctx placeholder used by ResourceManagerController\n- Fixed incorrect sorting by rank in TV grid on template create/update screen\n- Remove references to deprecated modX::getMicroTime()\n- Fix parent ResourceGroup inheritance on create\n- Preserve order of selected values in multiselect\n- Updated PHPMailer to v5.2.8\n- Updated phpThumb to 1.7.12-pre (current GitHub status)\n- Added resource_tree_node_name_fallback system setting\n- [#11297] Allow passing options to modRestCurlClient\n- Ease reuse of media sources panel\n- [#9245] Fix context menu position on custom resources that define a certain menu\n- Added OnResourceAutoPublish system event\n- Fix incorrect sorting by rank in TV grid on template create/update screen\n- Fixed Categories with a sub-category would always be shown in an Element's tree even if it didn't contain any elements of that type\n- Fix media source directive in TV when accessed from another context\n- List only user related resources in recently edited resources widget\n- Fixed colors/states not changing on subsequent database connection attempts in installer\n- Make ddGroups unique for resource, element and file tree\n- Fixed collapsing tree after quick creating an element\n- Add back Legacy modX.getFullTableName() method\n- Make OnFileManagerBeforeUpload event selectable\n- Added ability to define a default package provider via default_provider setting\n- Return nothing when toPlaceholder output filter is used\n- Added replace closing php tag for inline php dashboard widget\n- Fix to tv,chunk,snippet name validator per scottboryses observation\n- New manager theme\n- Move fax field near other telephone related fields\n- Option to disable CSS/JS compression during setup\n- Changed extension of JSON content type from .js to .json\n- Added modResource.isMember and modResource.getResourceGroupNames methods\n- Replaced uploaddialog with more modern multiuploaddialog\n- Added Other gender\n- Fixed events called in modResourceGroupCreateProcessor\n- Added dedicated page with media manager\n- Add icon/markup to modMenu items, allow new entries for topmenu and usermenu\n- An instance of modError added to modMail\n- Make sure connector responses return application/json content type\n- Removed hard coded \"index.php\" in manager assets\n- Preselect media source in static elements browser\n- Added ability to refresh a media source (tree)\n- Prevent duplication in context root if new_document_in_root != true\n- Sanitize filename when editing a file\n- Adds validateOldPassword flag to optionally skip passwordMatches() call\n- Make preview possible if session_enabled = 0\n- Improved widget of active users\n- Calling modUser->joinGroup sets rank to count(UserGroupMembers) instead of to 0\n- Call getNodesFormatted with parent property in modResourceSortProcessor\n- Hide back button during installation\n- Fixed regex for element names\n- Added system settings to change default action\n- Check for \"theme_path/js/layout.js\" before trying to load it\n- Clean modx->user on context init\n- Added shift modifier to tree click, that will open resource in a new window\n- Removing duplicate windows\n- Updated context setting's update window to appear as a create window\n- Load setting topic to allow 3PC components to use it for system setting translations\n- Allow filtering of namespace by request on lexicon page\n- Add proper validation for modSession id\n- Updated phpmailer class to 5.2.7\n- Fallback http_host to prevent cache issues under HTTP/1.0\n- Added ctx option to isloggedin/isnotloggedin output filters\n- Ensure opcache.revalidate_freq is set to 0 during setup\n- Clear menus cache on actions with menu\n- [#11123] Added \"success\":true to modProcessor response\n- [#11182] Fix issue where grid stores loaded only 20 records by default when pagination were disabled\n- [#828] handlePreview is called only if the deleted value changed\n- Update xPDO for additional SQL injection protection\n- [#11186][#11176][#9880][#2896][#5850] Disabled dirty check on save button in Resource's panel\n- Validate context key provided to modX::initialize()\n- [#11170] Added pdf to content type\n- [#675] Add upload functionality directly to package manager grid\n- [#703] Added OnElementNotFound system event\n- [#11149] Make sure hitting the close button does not trigger double prevent navigation warnings\n- Add refreshURIs call as part of clearing the site cache\n- Update parent field in Resource panel after drag and drop current resource\n- Check if template exissts before using it's icon in getNodes processor\n- Prevent content duplication when using [css|js|html]To[Head|Bottom]\n- [#11099] Removed C:\\fakepath\\ from filename during uploads\n- Fix path issue with phpthumb after 1.7.11-beta update\n- Prevent redirect of base_url when query string exists\n- Enable Template-based icons in Resource tree\n- Increase message_limit for ExtJS HttpStateProvider\n- Fix lexicon getList processor\n- Improve Confirm Navigation feature and make configurable\n- Confirm navigation when unsaved changes exist in resource panel\n- Fix deprecated returnValue to prevent confirm navigation alert\n- Fix xPDO->parseBindings bug triggering modDbRegisterMessage errors\n- Prevent processor property overwriting in modX::runProcessor()\n- Add open in new window action to middle mouse button click in trees\n- Preserve value types in modSystemEvent::output()\n- Prevent removal of user groups after validation fails\n- Remove extra dot in filename for Content Disposition attachment\n- Fix unescaped backslash in file and image TV\n- Remove cache clearing logic from system setting model\n- Update phpthumb to 1.7.11-beta to close security vulnerability\n- Add options and context filtering to modX::getTree()\n- Auto-resize modal window height to fit browser height\n- Add modSoftRemoveProcessor for marking records deleted\n- Ensure property not set when creating new property in Property Set\n- Implement auto-save on Content Types grid\n- Support PHP use statements in Snippets and Plugins\n- Add in/inarray conditional output filter\n- Add preg_quote to friendly_alias_word_delimiters characters\n- Do not prepend base_url when baseUrlRelative in modFileMediaSource\n- Add filterPathSegment() methods to modX and modResource\n- Remove check for children on Categories in Elements Tree\n- Allow Categories to have same name with different parents\n- Add case-insensitive contains/containsnot conditional output filters\n- Add modResource::clearCache() to clear cache for single Resource\n- Remove all dependency on mysql extension (deprecated in PHP >= 5.5)\n- Add extended field support and more to userinfo filter\n- [#9484] Add UserGroup Settings\n- [#10135] Fix output from multiple plugins OnSiteSettingsRender\n- Make path param optional in modFileMediaSource::getBases()\n- Clear register before calling clear cache\n- Add clear flag to modRequest::registerLogging()\n- Add modRegister::clear() method\n- Show custom xPDO class names in Manager Log\n- Fix context setting overrides in modX::_initContext()\n- Fix MODx.Console.onComplete when provider not set\n- Fix notice when resource not set in modX::sendForward()\n- [#9841] Add access to resource OnLoadWebPageCache\n- [#9072] Set upload_maxsize to php upload_max_filesize value on install\n- [#10146] Add embedded image support to modMail\n- [#9133] Fix various issues with Number TV\n- Fix visibility of Quick Edit independent of allowChildrenResources\n- [#8453] Add several File Management system events\n- [#7866] Add columns option to Checkbox TV\n- Add OnMODXInit event in modX::initialize()\n- Add name field to Contexts\n- Add preserve menuindex/alias options to Duplicate Context\n- Allow Namespace-based loading of custom TV files\n- Deprecate usage of modAction objects in favor of modNamespace base controller path", "MODX Revolution 2.2.10-pl (October 7, 2013)\n====================================\n- Increase modTransportPackage version columns range to smallint\n- [#10211] Fix parser state bug triggered by media sources\n- Fix loading modResource derivatives in class_key dropdown\n- [#9973] Prevent extended user classes being set to modUser\n- Upgrade xPDO to 2.2.9-pl\n- [#10182] Improve sanitization of processor_err_nf response", "MODX Revolution 2.2.9-pl (August 28, 2013)\n====================================\n- Avoid critical error when resource tree not initialized\n- Avoid suppressed warnings with ob_get_level()\n- Upgrade xPDO to 2.2.8-pl\n- [#10043] Fix class-loading LFI in registerLogging\n- [#6937] Fix Persistent/Reflected XSS in User Messaging\n- Set default error_handler_types to error_reporting()\n- Upgrade to ExtJS 3.4.1.1 and add ExtJS debug support\n- [#9976] Fix cross-context symlink caching\n- [#10093] Add create/update methods to S3 Media Sources\n- [#9902] Added error window when package download fails\n- [#10070] fix potential SQL injection vulnerability in modImport\n- [#9843] Added lang_topics field to create and update action window\n- [#10094] Defaults overwriting properties in ResourceCreateProcessor\n- [#10007] Fix parser logic when processing elements via API\n- [#10087] Avoid stat warnings with missing static sources\n- [#9809] Remove empty ULs in topmenu\n- [#7569] Add bottom border to collapsed panels\n- [#146] Also fire field change event on change event\n- Fix contextsAffected in resource/sort processor\n- [#9815] Improved manager redraw on browser resize\n- Fix clearcache timing issue with MODx.Console\n- Prevent accumulation of MODx.Console onMessage callbacks\n- Prevent session write errors from phpthumb cache\n- [#9964] Fix Import HTML to use context of parent\n- [#9916] Add TABLE to TRUNCATE command in flushSessions (SQLSRV)\n- [#9527] Fix password reset by user email\n- Fix login processor to use absolute url redirects for mgr\n- [#9826] Fix errant creation of Policy Templates", "MODX Revolution 2.2.8-pl (June 4, 2013)\n====================================\n- Prevent empty HTTP_MODAUTH from succeeding\n- [#9450] Prevent non-existent Context initialization\n- [#9896] Improve performance of modTemplateVar::getRenderDirectories()\n- [#9859] Prevent conditional output filter recursion\n- [#6138] Handle offline errors in RSS feeds\n- Refresh file tree after removing file\n- [#9946] Do not cache modResource::$_isForward\n- Force browser to root on Media Source change\n- Refresh file tree after root upload\n- Fix remove file from root if no folder selected\n- [#8877] Fix inline grid datefield icon\n- [#6945] Fix datefield icon in grid toolbars\n- [#9825] Revert width increase of file and image TVs\n- [#9901] Fix empty resourceMap in sqlsrv\n- [#9912] Fix length of modResource.uri index\n- [#9846] Fix incorrect parameter order passed to findResource\n- [#9814] Fix empty cross-context links using link tags", "MODX Revolution 2.2.7-pl (April 9, 2013)\n====================================\n- [#9634] Fix notices in system/settings/update processor\n- [#9768] Fix array merge in xPDOObject::getMany()\n- [#9773] Fix classKey errors viewing manager actions\n- [#9774] Prevent resource/unpublish on site_start\n- [#8312] Allow sorting users by blocked status\n- [#1] Allow Element duplication when editing\n- [#9237] Return object from ContextSetting create/update\n- [#8327] Don't close context menu on click\n- [#8980] Fix lexicon when updating user password\n- [#9258] List languages and topics alphabetically\n- [#9152] Use default_context for New Resource toolbar actions\n- [#8138] Fix Combo Settings not saving from update dialog\n- [#9571] Fix template/update always refreshing cache\n- [#9093] Make collapsed tree panel tab more visible\n- [#8859] Add button to refresh error log\n- [#9772] Fix deprecated value for CURLOPT_SSL_VERIFYHOST\n- [#9728] Fix empty create Dashboard Widget tab\n- [#9734] Fix save button state on Content Types grid\n- Fix resizing of error log textarea\n- [#9287] Enable save button when switching templates\n- [#9132] Refresh cache when enabling/disabling plugin\n- [#9690] Fix various issues with server_offset_time\n- [#9738] Prevent working context overriding user settings\n- Fix error getting MediaSource table classes on cached Resources\n- [#9368][#9437] Fix modProcessorResponse->isError()\n- [#9681] Allow country/getlist processor to work more than once\n- Fix Auto-Tag TV value sorting\n- Make caching the aliasMap optional to reduce memory usage\n- [#9672] Fix invalid ini_get call in modDbRegister\n- [#8489] Add compound index to modTemplateVarResource\n- [#9592] Iterate all inherited parent FC rules\n- Replace location redirects with MODx.loadPage proxy\n- Add MODx.beforeLoadPage event to modExt components\n- [#9143] Fix destructors in modExt components\n- Allow loading of modExt files asynchronously\n- [#9359] Report errors about unpublishing site_start to user\n- [#9197] Load RTE for SymLinks in manager\n- [#9364] Allow Unicode chars via modX::sanitizeString()\n- [#9631] Fix image preview with special chars in filename\n- [#9608] Remove connections data from MODx.config\n- Fix invalid ini boolean evaluation in config_check processor\n- Allow modX::getParser() to get an extended modParser instance\n- [#9524] Fix invalid context assignment in modX::switchContext()\n- [#9517] modPackageGetAttributeProcessor returning wrong PACKAGE_ACTION\n- [#9451] Add modx-combo-source as settings type\n- [#5515] MODx.Browser UX improvements\n- Increase width of file and image TVs\n- [#9282] Fix Minify errors when manager on different subdomain\n- Various Manager UI Fixes\n- [#6150] Fix issues with auto_publish when encountering invalid data\n- [#8936] Fix modTemplateVarRender::_loadLexiconTopics()\n- [#9257] Fix workspace/lexicon/getlist strict notice in PHP 5.4+\n- [#9339] Use Resource context_key in update processor when not specified\n- [#9212] Fix SQL syntax error in modTemplateVar->findPolicy()\n- [#9239] Make sure class_key is passed when switching templates\n- [#8101] Add support for httpOnly session cookies in PHP 5.2+\n- [#8420] Provide multi-node support to flock-independent file locking\n- [#8420] Remove LOCK_EX from flock-independent file locking method", "MODX Revolution 2.2.6-pl (December 3, 2012)\n====================================\n- [#9178] Use PHP time for valid check in modDbRegisterMessage::getValidMessages()\n- [#9165] Fix modError::hasError false positives when loaded via getService\n- [#9029] Remove modRequest->loadErrorHandler dependency in runProcessor\n- [#9156] Fix reload data for rendering multi-value TV types properly\n- [#7916] Fix Area functionality in Element Properties and Property Sets\n- [#9097] Fix leftbar tree toolbar resizing issues\n- Image optimization applied across distribution\n- [#9006] Fix ImageMagick which convert issue (PHP 5.3.2+)\n- [#9069] Remove math output filter\n- [#9080] Fix modX::stripTags() bug allowing script execution vulnerability\n- [#9007] Prevent MODx.Browser closing window when manager loaded in a new tab\n- [#8928] Error saving Resource with access-restricted TemplateVars\n- [#8978] Fix issue where change template was not fired due to onsave check overriding listener\n- [#9026] Prevent new Content Types from having binary checked", "MODX Revolution 2.2.5-pl (October 2, 2012)\n====================================\n- [#8753] Fix variable name in security/user/removemultiple processor\n- [#7654] Fix Update processor for ResourceGroup-restricted TVs\n- [#8196] Enable save button when combo selections are made\n- [#8186] Apply FC rules to Resources when changing Template\n- [#8790] Add ability to hide changed password in Update Profile\n- [#7551] Ensure static element path is not existing directory\n- [#7631] Fix duplicate beforeSave() in modObjectCreateProcessor::process()\n- [#8754] Change elementType to objectType in various processors\n- [#4430] Return 404 error if static resource target is invalid\n- [#8767] Fix MODx.panel.Resource to inherit config.url\n- [#8545] Add ability to localize ExtJS pre-loading message\n- [#8089] Fix ability to disable drag/drop in Resource tree\n- [#7661] Prevent changing template from unsetting Empty Cache\n- [#8620] Enable type-ahead on User and Country combos\n- [#8529] Prevent empty multi-value TVs from saving as '||'\n- [#8018] Fix file creation/editing on non-default Media Source\n- [#8556] Ensure regClient functions inject only once\n- CSS Style fixes for IE 9 (8, 7)\n- [#8560] Fix Context Admin ACL automation and use Context Policy\n- [#8432] Package Browser tree not reloading on Provider change\n- [#8482] RTE Output Option for TVs does not render on frontend\n- Add Quick Create/Update File feature in Files tab\n- [#6522] Retain page in Package Manager after install/upgrade\n- [#7630] Save modUserGroupMember rank upon creation\n- [#8420] Provide flock-independent file locking to avoid cache corruption\n- [#7498] Fix Media Source error reporting for file uploads\n- [#8299] Clear action_map (and menus) in system/action create/update processors\n- [#8168] Fix JS error when compress_js=Off and compress_js_groups=On\n- [#8341] Allow Resource data pages to be extended by CRCs\n- [#6695] Close sessions before min scripts terminate\n- [#6918] Fix importing access policy items always being checked\n- [#8329] Fix syncsite checkbox being unchecked by default on resource/create\n- [#8296] Fix function passed by reference in ellipsis output filter\n- Allow numeric value in modWebLink to redirect to Resource by id\n- [#7763] Fix additional Media Source path issues with static elements\n- [#8208] Fix modDbRegister->read() with include_keys option\n- Fix PropertySet switching from Element create/update controllers\n- [#7392] Get correct modMediaSource derivative in modParser->getElement()", "MODX Revolution 2.2.4-pl (June 14, 2012)\n====================================\n- [#8105], [#8051] Fix modFileHandler::sanitizePath() infinite recursion", "MODX Revolution 2.2.3-pl (June 13, 2012)\n====================================\n- Add setting to be able to set default context for new Resources\n- Pass http_host in provider requests\n- [#7933] Add friendly_urls_strict to optionally enable non-canonical redirects\n- [#6428] Fix help tooltip for new namespace window\n- [#8054] Fix transport provider verify processor consistency\n- [#8051] Added extra sanitization for modFileHandler.sanitizePath\n- [#7925] Fix error editing Resources in multi-context sites\n- [#8052] Fix empty()/isset() on hydrated fields/related objects\n- [#7798] Avoid E_NOTICE in PHP 5.4 from array_diff_assoc in xPDO::loadClass()\n- [#7796] Fix issue with phpthumb calling non-static methods statically\n- [#7764] Compress and default to open Resource Group access wizard in window\n- [#7762] Fix issue with add/decr output filter not adding 0 if 0 is passed\n- [#7793] Fix issue with saving a new media source access on user group edit screen\n- [#7712] Fix Resource quick update showing 2 checkboxes", "MODX Revolution 2.2.2-pl (May 2, 2012)\n====================================\n- Preserve GET parameters for container_suffix redirects\n- Allow custom FURLs via URL rewriting again\n- [#7427] Fix request_method_strict with FURLs off\n- Add ability to extend manager session by relogging in without leaving manager screen\n- Add better handling for AJAX exceptions, displaying AJAX errors\n- [#7649] Prevent E_NOTICE when using ago filter within <1sec difference\n- [#7568] Add JSON to default content types\n- [#7549] Open new window for phpinfo in system info page\n- [#7531] Add manager setting for first day of week in datepicker\n- Flip page title on manager pages for easier readability in browser tabs\n- [#7543] Add extra sanity checks for ellipsis output filter\n- CLI upgrades not loading MODX config data\n- [#7652] Sessionless contexts allowing anonymous access to unpublished resources\n- [#7610] User.sudo field invalid for sqlsrv\n- [#7619] Fix issue with TV FC rules and template constraints\n- [#7613] Add ability to duplicate user\n- [#7590] Fix lazy loading errors in xPDO layer\n- [#7608] Prevent ttl=0 set on modDbRegister from expiring immediately\n- Add wizard for User Group creation to speed up ACL workflow\n- Add Context policy for proper managing of access to non-mgr Contexts\n- Add wizard for Resource Group creation to speed up ACL workflow", "MODX Revolution 2.2.1-pl (April 3, 2012)\n====================================\n- Override modAccess->getOne for Principal aggregate\n- Add GroupPrincpal/UserPrincipal aggregates to modAccess\n- [#7387] Add New Category button to Element tree toolbar\n- [#7518] Fix issue that prevented absolute URLs in media-source bound TVs\n- [#7521] Allow filtering of usergroup by request on users page\n- Add assets_path field to modNamespace\n- [#7447] Change default root node name of Files tab to \"Media\" to prevent confusion when a non-default source is selected\n- Drop no-longer used, deprecated modAction.parent field\n- [#7503] Change Duplicate Values text to Duplicate Resource Values to clear up intended behavior\n- [#7499] Fix DOM ID issues with Quick Update when multiple windows are loaded\n- [#7500] Make consistent positioning of published checkbox in quick update and normal edit page\n- [#7491] Prevent Media Source dropdown from showing in MODx.Browser when loaded from a TV\n- [#6894] Move Import button on Access Policy and Access Policy Template grids to top toolbar\n- [#7391] Fix UI error causing resource group checkboxes on TV edit page to not render correctly\n- [#7481] Fix issue with reloading resource when changing templates and the context alias cache\n- Add \"sudo\" user attribute, which bypasses access permissions for said user; upgrade to 2.2.1 makes Super Users in Administrator group sudo users\n- [#7445] Fix issues with TVs not respecting Resource Groups limiting access\n- [#7446] Added extra checks to protect against parse errors with :then and :else output filters\n- [#7455] Fallback to TV name if caption not found when displaying TV inputs\n- [#7456] Fix for minify not modified status in fastcgi environments\n- [#6931] Workaround for template changing issue on servers that have misconfigured date_timzeone setting\n- [#6687] Fix duplicated OK buttons in MODx.Console in certain situations\n- [#6501] Fix SuperBoxSelect selections spanning multiple rows\n- [#6496] Fix quick edit modal windows for elements on smaller screens.\n- [#6864] Fix rare issue where primary group is not set for user, and custom dashboard for their group does not propagate\n- [#7011] Prevent infinite recursion error in modElement::isStaticSourceMutable\n- [#7333] Prevent error when id is undefined in resource edit controller\n- [#7364] Add setting to set default sort field of MODx.Browser view\n- [#7363] Check for this.stateful in MODx.tree.Tree::_saveState\n- Add missing index to modSession.access\n- [#7357] Prevent viewing of Profile if user does not have change_profile permission\n- [#7322] Fix issue where certain regions were not able to be hid via FC; clarified FC set labels\n- [#7362] Fix issue with conflicting FC Sets when User belongs to more than one User Group with a Set\n- Update to xPDO 2.2.3-pl\n- Prevent fatal error if invalid class_key is passed to Resource edit/create page\n- [#7052] Prevent username/host/dbname from being set as a system setting placeholder\n- [#3860] Fix session issue with modUser joinGroup/leaveGroup methods\n- [#7315] Standardize default sorting for User Group access grids\n- Fixed ellipsis filter to not cut off html tags in property\n- [#7326] Fix inability to unset a TV's Input Option Values field\n- [#7306] Sanity check for reload data for resource groups when changing template of new resource\n- [#7279] Handle edge case where processor classes might already be loaded with CRCs causing issues with runProcessor\n- Add dashboard name to dashboard title\n- [#3818] Add UI/processing to set response code for weblinks\n- [#7061] Prevent Static Element access to the core/config/ directory\n- [#7088] Tweak column widths for settings grids\n- [#7102] Improve memory_limit checks to properly check for values that are not formatted to PHP standards\n- [#7191] Fix invalid api doc link in link_tag_scheme description\n- [#7194] Fix issue where save button did not enable when reordering groups on user edit screen\n- [#3818] Change modWebLink default responseCode to 301\n- [#6611] Fix issue where MODx.Browser did not sort files by name by default\n- [#7070] Do not overwrite user changes in default media sources during upgrade process\n- [#7066] Allow search locally in Package Management if cURL is not installed\n- [#7063] Fix issue with retreiving Element Media Source cache data\n- [#7036] Fix issue with multiple grid store loading when searching\n- Allow for non-PHP Dashboard File Widgets that are just HTML files\n- [#6711] Fix issue with using MODx.Browser with file nodes and clicking loading edit page\n- [#6936] Add sanity check for database tables getlist processor if user did not grant SHOW TABLES permissions for sql\n- [#6942] Add missing resource duplicate ACL permission description lexicon string\n- [#6970] Reload error log page after clearing too large error log file\n- [#6956] Fix wrong groupname for OnMediaSourceDuplicate plugin event\n- [#7013] Fix issue where modUser->getUserGroupNames was buggy with non-self users\n- [#6960] Fix rendering issue when tree_root_id is set\n- [#7031] Ensure setting from addr in modMail sets return-path as well\n- [#7010] Add in rootId config option for MODx.Browser mgr widget\n- [#6874] Fix issue where duplicating a TV did not copy Media Source relationships correctly\n- [#6582] Fix clear cache checkbox persistence in Resource page when reloading via Template change\n- Add modX::getInstance() factory method\n- Allow for MODX tags within Media Source properties\n- [#5410] Add lock_ttl to System Settings for controlling ttl for resource locks\n- [#6575] Ensure that downloads of packages work behind proxies if allow_url_fopen is on\n- [#4879] Add language selector to login page\n- [#6826] Add activate/deactivate to context menu for Plugins in tree\n- [#6509] Fix minify issue in windows environments due to doc root pathing\n- Fix CSS for active tabs in mgr in IE\n- Prevent ENTER key from firing save in textareas in various modals\n- [#6712] Fix issue with Resource Group tree being limited to 10 groups\n- Bypass modSystemSetting->clearCache() when OPT_SETUP is true\n- Allow display of custom messages from form processors\n- Fix issue with extra slashes in URIs\n- Add ability to reload permissions for all authenticated users\n- [#6651] Add properties field and API methods for modResource\n- [#6613] Ensure page redirects if removing Element via tree that is currently being edited\n- [#6608] Fix search text in package management when doing empty search\n- [#6633] Ensure change password fieldset checkbox toggles dirty status for user form\n- [#6567] Fix Suhosin check to disable compress_js setting\n- [#6587] Fix issue with combobox rendering in editable grids by providing combocolumn xtype for proper data rendering\n- [#6583] Fix duplicate upload_files values\n- Prevent editing and deleting of core standard Roles", "MODX Revolution 2.2.0-pl2 (January 4, 2012)\n====================================\n- [#6564] Fix issue where save button on New Resource does not work due to JS DOM error\n- [#6470] Fix issue where Media Sources could not be protected on new installs only", "MODX Revolution 2.2.0-pl (January 4, 2012)\n====================================\n- [#6559] Fix issue with save btn on resources not enabling after template change\n- Better handling of dynamic lexicon topic adding and deprecated manager controllers\n- [#5905] Refactor new package versions to run ACTION_UPGRADE\n- [#6120] Improve static element behavior with immutable sources\n- [#6551] Fix issue where ID instead of name of Template showed on resource combo\n- [#6509] Fix minify issue when DOCUMENT_ROOT is a symlink\n- [#6546] Reposition setting grid filter dropdowns to clarify behavior\n- [#4146] Fix issue where Content Types were always binary when created\n- [#6470] Fix issue where Media Sources could not be protected due to missing reference in principal_targets setting\n- [#6520] Fix issue with Quick Create Resource and default settings\n- [#6510] Fix minify issue with virtual dirs inside the document root\n- [#5229] Fix issue where changing parent did not reload Resource edit page\n- [#6513] Better handling for large error.log files in mgr\n- [#6519] Ensure JS config gets working context config\n- [#6507] Add missing Media Source plugin events\n- [#6505] Remove htmlentities on date output filter\n- Allow PDO driver options to be defined in MODX config\n- [#6383] Add index.php to minify paths in mgr templates", "MODX Revolution 2.2.0-rc-3 (December 22, 2011)\n====================================\n- [#6247] Fix additional minify issues with CMP controllers in MODX_ASSETS_PATH\n- [#6428] Fix improperly designated tooltip and UI for create namespace window\n- Fix various regression issues with rename/delete files/directories in the Files tree\n- Ensure hideFiles property works for the files tree\n- [#6383] Add index.php to minify paths\n- Prevent TVs tab from showing in Resources if the only TVs are of type \"hidden\"\n- [#6413] Fix missing date_timezone setting description\n- [#6297] Prevent invalid characters in property set names\n- [#5997] Fix issue where components dirs were being created in assets with non-standard assets directory paths\n- Fix issue where resource ID was not being passed to FC rule checks\n- [#6417] Fix issue with modResource class_key being incorrectly set\n- Adjust modResponse contentType loading to allow overriding in custom resource classes\n- Fix critical timezone issue introduced for [#6077]", "MODX Revolution 2.2.0-rc-2 (December 16, 2011)\n====================================\n- [#3033] Add method to reload Context data in same request\n- [#6372] Add explicit resource_duplicate permission for duplicating a resource\n- [#6364] Fix incorrect lexicon reference in package versions grid\n- [#6365] Add manager_login_url_alternate setting which allows for setting a custom manager login URL\n- [#6077] Override PHP default timezone via System/Context Settings\n- [#5709] Fix issue where drag/drop in left trees did not work when package management was open\n- [#6153] Prevent enter key from sending Message when typing in messages page\n- [#6349] Properties can now belong to areas, and are grouped in grid by area\n- [#6344] Fix various pathing issues when drag/dropping files into content\n- [#5941] Add anonymous Load Only ACL when creating contexts\n- [#6247] Fix minify issues outside of $_SERVER['DOCUMENT_ROOT']\n- Improve skipFiles attribute for file media sources to allow MODX tags and hiding directories\n- [#6336] Fix error when updating property via window in media source properties grid\n- Fix various issues with permissions and ACLs on Media Sources\n- [#6306] Fix issue with close button always prompting changes made when changes may not have been made\n- [#6317] Fix issue with combo editor rendering in grids\n- [#6307] Save button now properly resets to disabled after save\n- [#6313] Fix issue with renaming content field label on derivative resource types\n- [#6084] Fix upgrade from 2.0.x releases\n- Add OnManagerPageBeforeRender and OnManagerPageAfterRender events\n- [#6207] Prevent overwriting static element file content when changing a static source\n- [#6255] Escape html tags in readme, license and changelog files for downloaded Packages\n- [#6096] Fix more issues with Resource reloading after changing a template by making the Resource Access grid local\n- [#5418] Add ability to export/import Access Policies\n- Add ability to import/export Policy Templates, as well as a base export/import processor class\n- [#6242] Actions on regular Resources break with Custom Resource Class extended fields\n- [#6096] Fix issue where reload token in Resource create would not allow save after validation\n- [#6238] Fix rendering issue when opening multiple quick create resource windows at once\n- Fix various issues with TV input and output renders by properly objectifying them into base abstract classes\n- [#5763] Allow for 3rd-level deep category nesting\n- [#6215] Fix issues with derivative resources and non-standard manager themes\n- [#6237] Add ability to sort users by active status in mgr grid\n- [#6197] Refresh old and new context caches when moving Resource\n- Update to xPDO 2.2.1-pl\n- [#6080] Fix revert to default properties on Source Properties grid\n- [#6204] Fix issue where multiple languages could not be loaded per page in the lexicon\n- [#6196] Ensure that MODx.Browser view updates when changing a media source from dropdown in tree\n- [#6198] Fix issue with saving user groups on a new user that caused duplicate role saving\n- [#6159] Implement OnBeforeUserActivate, OnUserActivate, OnBeforeUserDeactivate, and OnUserDeactivate events\n- [#6063] Add extra settings and checks to allow for better handling of manager CSS/JS minification on servers that do not allow DOCUMENT_ROOT access\n- [#6147] Fix element processors not firing proper events and passing wrong variables to plugins.\n- [#6060] Fix issue where resources were getting class_key of modResource rather than modDocument\n- [#6030] Fix issue where alt attribute was duplicated on image output renders\n- [#6122] Clarify text for removing a dashboard widget from a dashboard\n- [#6124] Fix issue where element associations of various elements were not saved in respective create processors\n- [#6145] Allow sorting of plugin events by enabled flag\n- [#6065] Fix issue with missing paths in certain environments for new installs in setup\n- Fix provider select window width in Chrome/Windows\n- [#6081] Fix issue in modFileMediaSource that prevented source properties from being read in certain processors\n- [#5141] Remove dependency for navbar.tpl in manager templates\n- [#5760] Fix memberof filter if user is not logged in\n- [#6090] Fix issue with removing Content Types in 2.2-rc1\n- [#6088] Fix issue with :date output filter and umlauts\n- [#6093] Make for easier translations of Element context menu items\n- [#6099] Fix incorrect index name for modWorkspace", "MODX Revolution 2.2.0-rc-1 (November 17, 2011)\n====================================\n- [#6019] Configure log_level, log_target, and debug via Settings\n- [#4798] Resource create/edit: Template can be switched without saving\n- Update to xPDO 2.2.0-pl\n- [#6039] Fix issue where Resources could be improperly dropped into the right tree in the Resource Groups screen\n- [#5715] Fix issue with resetting of header in Element panels\n- [#6025] Fix issue with renaming checkbox fields via Form Customization\n- [#5697] Fix issue with allow_multiple_emails in user creation\n- [#121] Add option for Elements to pre-process default property/property set values\n- [#6017],[#2774] Add more Permissions to Administrator policy for managing security functions\n- [#5064] Fix issue where access_permissions Permission was required for creating new users\n- Improve Package Management UI\n- Add modManagerController::addLexiconTopic for easier adding of lexicon topics dynamically within mgr controllers and dashboard widgets\n- [#6009] Add ability to hide left-hand trees when rendering a Dashboard\n- [#6007] Stop upgrade from overwriting session_cookie_path system setting\n- [#5998] Add \"Create File\" option for stream-based media sources\n- [#4794] Add custom Permissions for restricting creation of core derivative Resource Types\n- [#4958] Add Resource ID to node of Resource in Resource Groups tree\n- [#5434] Change manager page title to use site_name as prefix instead of MODX\n- [#4875] Add ability to download file from Files tree\n- [#5997] Fix issue where in advanced installs with moved web path, assets directory is improperly created\n- [#5990] Fix issue where content types were not listable in Resource dropdowns\n- [#232] Enable option to render target URL for WebLinks\n- [#5963] Fix issue with Static Elements and their Source being None\n- [#5936] Fix issue where Quick Update Resource was too high on smaller screens\n- Fix issue with phpThumb and zoom crop\n- [#5983] Fix adding/updating a provider window duplicating \"username\" field.[#5948] Ensure that menu item for Change Profile is added on build\n- [#5985] Fix updating a provider not showing username\n- [#5978] [ReUp] [#5978] Fix missing fields/tabs in actions XML causing issues with form customization on resource/create\n- [#5938] Optimize modResource->getTVValue() using parser source cache when available\n- [#5973] Prevent empty user groups being loaded for anonymous users\n- [#5962] Fix phptype in modContextResource.resource field definition\n- [#5050], [#5366], [#5781] Various xPDO Database Caching Fixes (xPDO 2.2.0-rc2)\n- [#4830] Prevent removal of Content Types that are in use\n- [#5293] Prevent drag/drop from Resource Group tree to Resource tree in Resource Group page\n- [#4433] Validate paths in setup for trailing slash\n- [#564], [#4506] Make Workspace path portable by allowing path setting replacements\n- [#5086] Fix issues with Package Management when open_basedir is in effect\n- [#4947] Adjust ensuring of admin access to context to only needed policies\n- [#5078] Have default resource field context settings, such as default_template, respected in Quick create\n- [#5909] Allow blank extensions in Add Content Type window\n- [#5931] Fix code that prevents easy renaming of assets directory with package management\n- [#5841] Properly color active state for tabs in mgr ui\n- [#3287] Fix issue with dob User field in editing panel in mgr\n- [#5060], [#5043] Fix issue with openTo and TVs for MODx.Browser\n- [#3396] Allow MODX_API_MODE in mgr context\n- [#4230] Add ODF and OOXML to default uploadable file types setting\n- [#5315] Use automatic_alias behavior when updating site_start regardless of setting\n- [#3535] Fix issue with tree_default_sort not being respected on the resource tree\n- [#5892] Add for default_media_source setting for specifying the default media source for a site\n- [#5896] Make console window always closable\n- [#5757] Allow text in grids to be selectable\n- [#5471] Add publishing options to Duplicate Resource window\n- [#5879] Ensure html tags are stripped on titles in the Resource edit view\n- [#5855] Ensure if no parents are specified, resourcelist input option works as expected\n- [#5852] Fix issue where input options are wiped on quick update TV\n- Add showNone option to source/getlist processor\n- [#5619] Enable modElements to store content in external files\n- [#5856] Implement ability for derivative Resource types to have their own translatable name\n- [#4726] Implement server-side state provider for modExt to fix size problems with cookies\n- [#5860] Fix FC SQL error when user is in no groups\n- [#5843] Add required asterisk to required Element fields\n- [#5723] Add Media Source tab to User Group Access screen\n- Change \"Cancel\" references to \"Close\" for clarity\n- [#4566] Fix online users manager dashboard widget grid\n- [#5809] Change \"Remove\" to \"Delete\" where appropriate to clarify language\n- Refactor processors to be class-based\n- [#90] 301 Redirect id method requests when request_method_strict is not enabled\n- [#90], [#5676] Improvements to strict routing with friendly_urls\n- [#5323] Add system events for moving Resources in and out of Resource Groups\n- [#4610] Add locale system setting for setting locale in MODX\n- Add HTML5 local caching as a toggleable option for manager ui\n- [#5788] Fix content not output to browser until after shutdown function\n- [#5777] Fix validation of TV names against Resource field names\n- Add ability to install and upgrade MODX from command line\n- [#5745] Ensure all core passwords are not transmitted through MODx.config JS array\n- [#4304] Add default_content_type Setting for setting the default Content Type for Resources\n- [#2735] Ensure menu permissions are checked for mgr action if action has menu associated\n- [#4606] Clarify connectors language in setup\n- [#5561] Add search toolbar to packages grid\n- [#5587] Fix issue with dashboard widgets and caching\n- [#5453] Add ability to disable forgot password on manager login screen\n- Add batch remove to Namespaces grid\n- [#5671] Add :toPlaceholder, :cssToHead, :htmlToHead, :htmlToBottom, :jsToHead, :jsToBottom output filters\n- Add delete user button to user editing page toolbar\n- [#5542] Add ability to drag/drop files and folders in the Files tab\n- [#5665] Remove console.log debug references in JS\n- Add Media Sources, which allow abstraction of file management in MODX\n- [#2737] Centralize logic for changing Context of modResource Children\n- [#5068] Move token check for new resources below error validation in processor to prevent bogus duplicate resource issue\n- [#4945] Remove weblink content maxlength restriction\n- [#5270] Enable container drag 'n drop in Extended Fields tree\n- [#4790] Add support for comment tag token, e.g. [[- comments here]]\n- [#5539] Add back in compress_css/js for allowing toggling of js/css compression in manager\n- [#5556] Enable connection pooling with master/slave support\n- [#5499] Ensure modFile create returns boolean\n- [#5501] Add sanity checks on FC rules renameTab and hideField\n- [#5505] Fix issue with dropdowns in Fx5\n- Enable modTag elements to accept property sets\n- Enable modElement->getPropertySet() to merge @propertyset in name with property set specified in setName parameter\n- Allow modParser->getElement() method to accept @propertySet in name parameter\n- Prevent modParser->parsePropertyString() from trimming all backticks at beginning and end of string\n- Improve parser efficiency by returning results of nested tags if elementOutput is null|false\n- [#5392] Fix bug where policy template descriptions were not translated\n- [#5377] Fix modParser->isProcessingTag() bug preventing filtering on placeholder tags\n- Pass content by reference to OnParseDocument event\n- Add message_key and json message_format option to system/registry/register/send processor\n- Allow raw messages to be returned from system/registry/register/read processor\n- Add include_keys option to modRegister implementations\n- [#5336] Prefix non-core actions in the MODx.action JS object with their namespace\n- Avoid setting description to null in element/propertyset/create processor\n- Improve modX->logManagerAction to avoid attempts to insert NULL values\n- Accept null options in modHashing->__construct()\n- [#4607], [#3463] Add rank field for contexts to allow custom sorting in tree, fix issues with context/resource dragging and dropping and ensure context name validation rules are consistent\n- Improve UI of User's groups to allow for assigning ranks to User Groups for a User\n- Add Custom Dashboards and Dashboard Widgets\n- [#4871] Fix Access Permissions not being copied when duplicating a context\n- [#4382] Forgot Manager Password now lookups using username to prevent issues when the 'allow_multiple_emails' system setting is enabled\n- Fix rendering of combo boxes in element properties\n- Add ability to select Primary User Group for User\n- [#4637] Fix RTE checkbox not saving correctly when using Quick Create Resource\n- [#5268] Add search toolbar for Resource tree\n- [#4080] Add Content Type and Content Disposition to Quick Create/Update Resource\n- [#5250] Add check for cURL in Package Management\n- [#5204] Add search by parent to mgr search page\n- Added much better handling for custom resource classes; deprecated custom_resource_classes setting\n- [#4601] Ensure children of protected Resources inherit by default their parent's Resource Groups in create UI\n- [#4016] Update description text in grid when adding/updating element properties without need for page reload\n- [#2860] Fix 'Sent On' date when viewing an expanded message\n- [#4984] Ensure tree highlighting of currently edited resource/element/file works consistently\n- [#2638] When updating an element's category, ensure old treenode is removed\n- [#5139] Fix issues with MODx.Browser and file/image TVs in other contexts\n- [#4958] Add IDs to Resource Groups in RG tree\n- Add ability to rename Resource Groups\n- [#5185] Improve core package already extracted validation for upgrades\n- Update xPDO and regenerate schema to get new maps of derivative classes\n- [#5195] Change TV value fields from TEXT to MEDIUMTEXT (mysql)\n- [#5141] Add ability to override specific controllers/templates in a custom manager theme w/ fallback to default\n- Add modResource::getControllerPath method for better abstraction of derivative resource types\n- Add show_in_tree and hide_children_in_tree fields to modResource for better support with custom Resource types\n- Abstract all manager controllers to classes to improve usability, testing and creation of controllers", "MODX Revolution 2.1.3-pl (July 21, 2011)\n====================================\n- [#5295] Fix parents input option for Resource List TV when 0 is specified\n- [#5190] Fix includeParent input option in Resource List TV\n- [#5222] Fix nested cacheable tags being skipped in non-cacheable tags\n- Fix delegateView recursion in Resource controllers on Windows\n- [#3966] Fix double slash issue in file paths when dragging into resource content from the Files tree\n- [#4565] Fix issue with Resource tree sorting\n- [#5026] Make directory tree in MODx.Browser instance launched from Files tab consistent with other instances of MODx.Browser\n- [#4960] Prevent method declaration error for modPHPMailer::reset()\n- [#3716] Ensure consistent handling of combo-boolean property values in the database\n- [#4586] Improve number detection for Radio and Checkbox TV values\n- [#5196] Unset uri_override when duplicating creates a duplicate uri", "MODX Revolution 2.1.2-pl (July 6, 2011)\n====================================\n- Fix issue with modUser::getSettings pulling a deprecated alias\n- Update to xPDO v2.1.5-pl\n- Implement DocBlox for documentation generation\n- [#5168] Fix element and tv permission queries for SQL Server\n- [#5146] Fix issue with Firefox and button widths\n- [#5164] Fix possible issue if a TV is stranded to a non-existent category\n- Update ExtJS to 3.4.0\n- Set a default session_gc_maxlifetime to avoid frequent logout issues\n- Refresh modExt trees when drag operations fail\n- [#4918] Limit save permission check to modified nodes in resource/sort processor\n- [#5065] Fix 404 error with cross-context symlinks when cacheable\n- [#5152] Fix nested non-cacheable tags from being cached in modResource->_content\n- [#5145] Update config check on dashboard to show correct core path if core is moved\n- [#5112] Add Settings for adjusting behavior of Context sorting in Resources tree\n- [#4341] Properly clarify text and function on Resource Tree context menu options for view/preview\n- [#5046] Fix issue where parent could not be changed for new resources via Form Customization\n- [#5112] Sort contexts by name ascending in the Resources tree\n- [#5102] Fix error removing older transport package versions\n- [#4940] Fix issue where CMPs that did not use ExtJS could not scroll\n- [#5097] Ensure browser toolbar button does not show when MODx.Browser is already open\n- [#4953] Improve modx.console.js to avoid message loss\n- [#4836] Make sure modFileRegister sorts messages before reading\n- [#5087] Fix issue where class_key was not respected when using Add Another in UI\n- [#260] Implement on-the-fly compression for css/js in manager\n- [#3464] Set xPDOTransport::ACTION_UPGRADE for already installed packages\n- [#4955] Package management actions refresh packages cache partition\n- [#5071] (SqlSrv) fix/refactor Plugin Events getList processor\n- [#2870] Change internalKey default value to NULL\n- [#5072] Add missing primary key index to modEvent\n- [#5005] Fix incorrect label on introtext field in weblink panel\n- Remove session_cookie_lifetime variable when logging out of context\n- Remove legacy SESSION variables and dependencies\n- [#4703] Remove user settings when logging out of a Context\n- [#2566] Improve tv output render url to take resource pagetitle when using resourcelist TV type\n- [#5020] Improve per page field on grids to handle ENTER key\n- [#5021] Improve modUser::joinGroup to check to see if user is already in group\n- [#5025] Fix issue where duplicate resource window did not show duplicate children option\n- [#5007] Only create Lexicon Entries for Settings if they are specified\n- [#5006] Fix issue with updating a policy template with no permissions\n- [#5001] Fix issue with modauth, wctx and RTE browser", "MODX Revolution 2.1.1-pl (June 1, 2011)\n====================================\n- Make modauth calculation independent of session_id\n- Ensure login/logout processors do not add Contexts with empty keys\n- [#3145] Ensure mail_smtp_pass and proxy_password System Settings use password xtype\n- [#4360] Show current context name on MODx.Browser window for reference\n- [#4881] Fix issue where modx-combo-language was missing from system setting editing screen\n- [#4896] Fix issue where New Category window is not cleared on each load\n- [#4934] Fix missing lexicon load call in package download processor\n- [#4927] Gray out disabled plugins in elements tree, italicize locked elements\n- [#4921] Ensure Category names are not ever capitalized when displayed as tabs\n- [#4865] Fix PDO error caused by missing charset for new MySQL installs on PHP 5.3.6+\n- Improve modSessionHandler and add Settings for advanced configuration\n- [#4750] Fix various issues with duplicating Resources, such as new name not prefixed and incorrect menuindex\n- [#4910] Fix bug where ResourceList TV type could not be marked as required\n- [#4915] Fix UI glitch when creating both an Access Policy and its Template on same page load\n- [#4916] Fix issue where cache clear checkbox was always being cleared on template save\n- [#4884] Remove PHP4 constructor on modRegister\n- Harden connector CSRF security by tying user session modauth to prevent hijacking of session if modauth is known\n- [#4863] Fix issue where template changing causes unintended alias\n- [#4854] Fix bug that caused update/rename file to be missing in Files tree context menu\n- [#4851] Improve safe_mode check in setup to check for non-boolean values\n- [#4856] Fix issue with MODx.Panel instances that have no textfields, causing scrollbar issues\n- Fix issue where MODX version was not being sent to provider during package update\n- [#4850] Fix issue with MODx.Window instances that have no textfields", "MODX Revolution 2.1.0-pl (May 24, 2011)\n====================================\n- [#4818] Fix SqlSrv query errors related to TVs\n- Add modX->$sourceCache data to cached Resources\n- Fix loading of cached Resource content and processed flag\n- Fix caching of empty policies for Resources\n- Fix modSessionHandler->write() cache flag if cache_db_session is not enabled\n- Update xPDO to v2.1.4-pl for cache_db bug fixes and improvements\n- [#4832] Fix issue with moving resource parent to root\n- [#4827] Make sure editing a file sends the working context along\n- Fix erroneous call to OnDocUnpublished event that should be OnDocUnPublished\n- [#4796] fix New Resource page heading during typing of page title\n- Add Usergroup filter to users grid\n- [#4785] Fix preview of files in left tree in non-standard contexts with absolute filemanager_ settings\n- [#4473] Add other common file types to upload_files system setting\n- [#4539] Fix issue with stretching of quick update chunk and small screen resolutions\n- Automatically focus cursor to first textfield on windows in mgr\n- [#4738] Fix issue with inconsistent results in resourcelist TV\n- [#4441] Fix FC issue when parent is constraint and trying to change default template\n- [#4764] Fix issue with timestamp display on manager log page\n- [#4680] Fix javascript error when typing Template name\n- [#4681] Fix path issue which was causing 404 errors in the manager, IE 7-9\n- [#4439] Add parentheses to list of disallowed password characters in installer\n- [#4669] Fix button target size to make it more responsive to most clicks\n- [#4625] Fix sizes of buttons and submit inputs in installer - IE 8 and 9\n- [#4617] Fix custom values not being shown on Context Installation page during Advanced Upgrade\n- [#4605] modX->switchContext() now checks load permission via Context ACLs\n- [#4595] Fix display of modified/accessed times on Edit File page\n- [#4594] Fix last login time displayed in Info block of Manager welcome page\n- [#4470] Fix frozen URI not displayed when editing resource\n- [#4572] Fix installer error log filenames (characters not allowed in Windows filenames)\n- [#4585] Fix database connection processors in advanced upgrade\n- Update xPDO to v2.1.3-pl\n- [#4567] Remove calls to xPDO->log() in xPDOCacheManager->writeFile()\n- [#4557] Minor fixes on Installer Options screen for Traditional package\n- [#4556] Fix js error on Welcome screen of Traditional package's installer\n- [#4076] Fix Edit/Quick Update context menu items in protected categories\n- Fix Context Access query broken in RC4 changes for #4502", "MODX Revolution 2.1.0-rc-4 (April 29, 2011)\n====================================\n- [#4543] Fix preview URLs when FURLs are turned Off\n- [#4537] Trigger refreshURIs when related settings are modified\n- Have modAccess*::loadAttributes() check access_*_enabled settings\n- [#4502] Enable custom targets in modUser->loadAttributes()\n- [#3692] Add policy checks for new_document_in_root and add_children to resource/sort processor\n- [#4526] Additional fixes for output filters on placeholders\n- [#4504] Ensure UserGroup ACLs are deleted along with UserGroups\n- [#4507] Fix usergroup description not being set when created\n- Change modResource->isDuplicateAlias() to return id of duplicate Resource\n- [#4495] Add duplicate URI check to resource/publish action\n- [#3857] Fix placeholder processing when output filters applied\n- [#4362] Fix path issues with Static Resources and base_urls of /\n- [#4074] Require list permission on Context for Resource searches\n- [#4439] Do not allow invalid characters in username / password\n- [#4485] Fix issue with scrolling on drag/drop Element Properties window in small resolutions\n- [#4352] Fix failedlogincount / user blocking logic in login processor\n- [#4373] Fix issue with htmltag TV output render and empty values\n- [#4374] Fix issue with updating files in the edit file page\n- [#4024] Fix issue with LocalProperty grids not rendering list type properties display values correctly\n- [#4400] Trim whitespace from Namespace paths when adding/updating them\n- [#4434] Fix issue with edit panel on contexts\n- [#4372] Fix View button not getting URI change after Save Resource (all Resource types)\n- [#4369] Ensure Save button is active after Template change on Weblink, Symlink, Static Resource\n- [#4471] Set Resource alias properly on update\n- [#4469] Guard against inadvertent creation of duplicate New Resources\n- Add options to configure cache file writing attempts when exclusive locks fail\n- [#4464] Prevent unnecessary TV queries on uncached Resources\n- [#4422] Fix problems updating Boolean settings (System, Context, User)\n- [#4453] Fix File Browser when paths contain \"n_\"\n- [#4447] Fix ACL grid in Edit Context view\n- [#4438] Fix error logging to custom log targets defined by array\n- [#4399] Fix IE8 javascript error on Resource and Element update pages", "MODX Revolution 2.1.0-rc-3 (April 11, 2011)\n====================================\n- Fix invalid merge retained in master branch from 2.1.0-rc-1\n- Fix modResource::save() to refresh uri if isfolder field is dirty.", "MODX Revolution 2.1.0-rc-2 (April 11, 2011)\n====================================\n- Refresh resource tree if resource's parent has changed\n- [#4327] Fix bug with auto-publishing\n- Fix positioning of right panel in mgr UI to make tree/nav static and isolated from scrolling of right panel\n- Make alias required field in resource/create processor when friendly_urls is on but automatic_alias is off\n- [#4280] Fix issue where transport package could not be removed if transport files were removed\n- [#4281] Utilize modX::sourceCache in modParser::processElement()\n- Fix issues with Namespace grid related to context menus and search\n- [#4257] Fix issue where context menus did not show in Contexts grid\n- [#4288] Fix issue with resource preview context menu\n- [#4279] Fix undefined collResources notice with empty Contexts\n- [#3119] Fix modResource->getAliasPath() to use id if set\n- Upgrade MagpieRSS to 0.72 to fix issues with atom feeds\n- [#3623] Fix TemplateVarTemplate foreign key definition in modTemplate\n- Replace specific references to MySQL with more general language\n- [#4185] Change modx logo in mgr to new logo\n- [#4217] Add rank field to modUserGroupMember table\n- [#4271] Highlight currently editing Resource on tree\n- Fix issue with image/file TV and uploading in MODx.Browser when using a custom basePath TV\n- [#4270] Fix issue where images could not be removed when using a custom basePath TV\n- Add User Group related events\n- [#4260] Change title tag in mgr UI to reflect current page\n- [#4256] Add caption field to Quick Create/Update TV\n- [#4261] Change keyboard save shortcut to CTRL+S\n- [#4262] Ensure that FC rules htmlencode their tab/field labels\n- [#4243] Ensure that files that are read-only do not show save button; fix file tree opening\n- [#4244] Add backwards compatibility for Element properties of list type with older indexes\n- [#4236] Fix bug in Template combo that hid category name\n- Improve compression of images in mgr to reduce load times and core transport zip size\n- [#4232] Fix Output Options being ignored in TVs in 2.1.0-rc1\n- Add options to allow ACL queries to be disabled for Contexts, Categories, and Resource Groups\n- [#3941] Fix issue where Resource TV values were not copied when duplicating a Context\n- [#4202] Fix issues with file/image TVs urls/paths when using modx path placeholders\n- Fix sorting/display bugs on UserGroup ACL grids, add grouping for better visibility\n- [#4175] Add modRequest->getClientIp() for better IP handling\n- [#4217] Add rank field to modUserGroup\n- Update version to 2.1.0-rc-2\n- [#4173] Fix issues with math-related output filters and floats\n- [#4205] Ensure old modxcms.com provider is removed after change to modx.com provider\n- [#4220] Fix modX::makeUrl() when friendly_urls not enabled\n- [#4207] Fix issues with checkboxes and Form Customization rules\n- [#4013] Fix modX::_log() to pass target to parent::_log() properly", "MODX Revolution 2.1.0-rc-1 (March 28, 2011)\n====================================", "- Fix issue with properties and i18n in Element properties and in drag/drop box\n- [#4146] Fix issue where new Content Types were always created as Binary\n- [#291] Add principal_targets setting to allow custom ACLs to be loaded by MODX Principals/Users\n- [#99] Allow SymLinks/modX->sendForward() to forward to Resources in external Contexts\n- [#4147] Changing ContentType extension in grid not refreshing URIs\n- [#3967] Fix issue with running user create/update processors more than once in a session\n- [#3542] Hide Template Variables tab on Resource create/update pages if no TVs are present\n- [#788] FC Rules for TVs now display distinctly for create or update\n- [#1118] Add more help for User fields in manager editing page\n- [#2578] Fix issues with manager log view page where sorting was off and grid was not sortable\n- Fix issue where user-created FC tabs were not removable from a Set\n- [#4096] Fix Package Management archive issue when using mapped Windows drives\n- [#3785] Add category filter and search box to TV grid on Template panel\n- [#65] Make locked Resources be read-only rather than unviewable\n- Improve Package Management to show changelog, more supports information in package browser\n- [#4120] Fix issue where TV sort order is reset on Quick Update\n- [#4115] Fix issue with modPhpThumb and filenames with + signs\n- [#2719] Fix reset behavior on autotag/tag TV inputs\n- [#3586] Adjust improper text on Content Types page\n- [#2652] Fix issue where Element could be drag/dropped onto another Element in tree\n- Add ability to select a blank value for ResourceList TV input type\n- [#54] Fix issues with phpThumb and DOCUMENT_ROOT by adding a custom phpthumb_document_root System Setting\n- [#4122] Fix order of execution of validation and plugin events for Element processors\n- [#4105] Add Spanish translation\n- Refactor duplicate alias checks into duplicate URI checks\n- Cleanup deprecated code in Resource templates\n- [#3765] Ensure entries editedon values are set when editing a Lexicon Entry\n- Update ExtJS to 3.3.1\n- [#4073] Add session_name, session_cookie_path, session_cookie_domain as System Settings with blank default values\n- [#4077] Add resource_quick_create and resource_quick_update Permissions to restrict access to Quick actions on Resource tree\n- [#4050] Add tree_show_resource_ids and tree_show_element_ids Permissions to show/hide IDs of Resources/Elements in tree panels\n- Add username field to modTransportProvider, and send it and UUID to providers during transmissions\n- [#3641] Add base URL for Help links in manager for easier management and customization of URLs\n- [#3552] Fix issue causing list-xtype properties to be swapped when using drag/drop into field functionality\n- [#4069] Ensure that you cannot delete the last User in the Administrator user group\n- Add fix for ie9 to get tree nodes to work properly\n- Prevent Category ACL queries on Elements if no entries for current context\n- [#2601] Improve text and drag/drop for weblink/symlink content fields\n- [#3636] Fix issue with empty values on options in list/dropdown/checkbox/radio TVs\n- [#4024] Fix issue with display value not always showing for list properties in element property grid\n- [#4056], [#4041] Add xtype password, template, user, usergroup, etc to available xtypes for System Settings\n- [#3350] Improvements to bugfix for PHP bug 53632\n- [#4054] Improve select binding to be able to use Resource fields via placeholders\n- [#142] Add modResource.setTVValue API method\n- [#4021] Add system setting to allow setting of a custom favicon for the manager\n- [#3589] Fix issue with Static Resource paths when using custom filemanager_path\n- [#4040] Fix issue where Users were always created as active in mgr UI\n- [#4043] Enable drag/drop of users and groups in User Group tree\n- [#4052] Fix issues with element property import and invalid characters causing freezing in UI\n- [#4042] Fix issue in phpThumb base class preventing far property from working\n- [#4049] Add resource_tree_node_tooltip for controlling field in Resource Tree tooltip\n- [#3511], [#2964], [#3601] Fix issues regarding form customization and Templates by removing ajax loading of TVs in Resource panels\n- Consolidate JS for derivative Resource panels to allow to inherit from main Resource panel\n- Add context param to modx.getParentIds\n- [#3754] Ensure Resources can not have their parent set as one of their descendants\n- Add context param to modX.getChildIds\n- [#3612] Improve CDATA filter to not add spaces at beginning or end\n- [#3764] Add delete to actionbar on Resource edit panel\n- [#3585] Add description field to modUserGroup\n- [#3020] Improve trees to expand node on click if no href target is set for tree node\n- [#4006] Show children count rather than IDs on categories in element tree to lessen id ambiguity\n- Fix issue where Quick Create was not respecting unchecked setting checkboxes\n- [#3673] Add \"Save and Close\" button to quick update windows\n- [#3970] Ensure extension is lowercased before checking for allowed status when uploading files\n- [#3920] Ensure modPHPMailer resets replyTo and custom header fields\n- Add UI for managing Resource uri and uri_override fields\n- Remove all deprecated methods and variables scheduled for removal in next minor release\n- Change modxcms.com references to modx.com\n- [#3898] Prevent any non-integer being set in ?a= in mgr interface\n- [#3926] Ensure security/user/create processor can take in a class_key parameter to set class_key for SSO\n- Improve user processors event handling to allow for better SSO integration that can stop save/remove/update\n- Refactor password reset not to send password hash as activation key\n- [#325] Allow configurable user password hashing with PBKDF2 default implementation\n- [#3111] Fix bug causing unnecessary writes to Resource cache files\n- Update xPDO to v2.1.1-pl2\n- Add modResource.uri_override to allow a uri to be manually set and locked per Resource\n- [#3111] Add modResource.uri field to allow context maps to be regenerated in a single query\n- [#3859] Remove redundant check for php bug\n- [#3858] Fix javascript errors from FC hideField rule\n- [#2812] Add link_tag_scheme to define default scheme for makeUrl() call in modLinkTag\n- [#3111] Remove resourceListing, documentListing, and documentMap from context cache\n- [#3111] Cache refactoring with proper file locking, partitioning, and multiple format support\n- [#3111] Update xPDO to release 2.1.0-pl for cache improvements\n- [#3740] Add proxy support to modTransportPackage.class.php\n- [#3693] Fix reversed content-disposition logic on static resources\n- [#3427] Fix issue where User Settings were not respected with filemanager_path/url\n- [#3702] Ensure file/image TVs can have files drag/dropped onto them\n- [#3465] Add sanity check for non-object to log call in modAccessibleObject::_loadInstance\n- [#3615] Fix issue with modx->user->getResourceGroups, set resource groups in \"modx.user.{$id}.resourceGroups\" session key\n- [#3568] Fix double error->failure reference in resource/create processor\n- [#3425] MODx.Browser now loads directory of TV's current value on load\n- [#3481], [#3571], [#3304], [#3569] Fix issue with filemanager_path in non-web contexts\n- [#3009] Add ability to assign TVs to specific directories and base paths, limit file extensions shown\n- [#2679] Add Input Options to TVs, allowing TV inputs to be customized and tweaked", "MODX Revolution 2.0.7-pl (January 14, 2011)\n====================================\n- [#3472] Fix issue due to tree impr that prevented element saving success response\n- Improve loading of mgr pages by preventing trees from rendering until activated\n- [#3205] FC fixes: Ensure Resource Content field can have values set/renamed, that rules on create respect template, and that default values on create are set\n- [#3165] Fix issue where resource/updatefromgrid processor was missing published value if user does not have publish permission\n- [#2] Fix issue in user extended fields where subkeys in 2 separate containers DOM IDs conflict and prevent editing\n- [#3422], [#3374], [#3197] Fix issue with filemanager_url and Image/File TVs and their relative end result URLs\n- [#3201], [#177] Add modResource.leaveGroup, modTemplate.hasTemplateVar, modTemplateVar.hasTemplate\n- [#3350] Fix for PHP bug: http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/\n- [#3326] Fix issue where TV radio/cb options with value of 0 couldnt be selected\n- [#3329] Fix edit and cancel buttons on view resource page\n- [#3329] Clarify Preview link on Resource action toolbar to be more correct \"View\"\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run\n- Introduce pdo_sqlsrv support\n- Add database_dsn to config\n- Update xPDO to release 2.1.0-pl", "MODX Revolution 2.0.6-pl2 (January 6, 2011)\n====================================\n- [#3350] Fix for PHP bug: http://bugs.php.net/bug.php?id=53632\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run", "MODX Revolution 2.0.6-pl (December 20, 2010)\n====================================\n- [#3143] Fix lexicon grid search to respond to enter key\n- [#3144] Fix issue with reset password and @ being stripped\n- [#3142] Ensure whitespace is stripped from tags in tag/autotag TV types\n- [#3118] Ensure defaults are set in resource/create processor if values are not sent\n- [#3105] Improve memory_limit check in setup to accept integer values from PHP instances\n- [#3106] Add sanity check to resource create/update processors to disallow invalid Resource Group ID references\n- [#3038] Fix problems with filemanager_path settings and absolute URLs in image TV values\n- [#3039] Add symlink_merge_fields setting to disable modSymLink merge behavior\n- [#3103] Alter modSession data field to store more than 64Kb\n- [#3091] Add missing specific dom ID to profile change password panel\n- [#3096] Fix issue with exporting default properties not in a set from an element\n- [#3099] Fix FC rules to respect class_key constraints\n- [#3097] Fix extension_packages to support modx path placeholders, as well as new serviceClass and serviceName parameters\n- [#3085] Ensure Files tree only refreshes active node when creating/updating a file/dir\n- Improve the Permission dropdown and add window in AP Template page\n- [#3083] Fix Form Customization issue when Resource has a blank Template\n- [#3082] Fix Form Customization issue where cacheable and ID fields not able to be hidden/altered\n- [#3034] Fix error creating Resources in Contexts other than web\n- Fix issue with incorrect active permission total in Access Policy grid\n- [#3023] Fix issue where topmenu did not respect manager_language\n- [#3080] Fix missing placeholder in error message when attempting to create a duplicate Element\n- Add new header image to match new site\n- [#3078] Fix issue with htmltag TV widget properties when using = in its value\n- [#3079] Ensure GPC vars are not sent into $scriptProperties array in $modx->runProcessor\n- [#2983] Add sanity check to prevent plugins from firing if disabled (redundancy)\n- [#3057] Fix issue where parent change causes fail to save in UI\n- [#3076] Fix bug where manager returnUrl was not working due to [#2918] fix\n- [#3059] Ensure createdby is set on resource creation\n- [#3041] Fix missing lexicon entry in resource processors\n- [#3043] Fix invalid 200 response header on sendError()", "MODX Revolution 2.0.5-pl (December 8th, 2010)\n====================================\n- Change remove() to removePackage() in modTransportPackage\n- Fix issue with package setup-options attribute not loading forms\n- [#2932] Fix redirect issue after setup and on manager login page caused by [#2918]\n- [#2931] Fix issue where FC rules weren't applying if no UserGroup was set in a Profile\n- Ensure non-Resource FC rules are removed on upgrade\n- [#2918] Address XSS vuln in manager login that allows JS injection\n- Fix issue where // is stripped from filemanager_url http address\n- [#2902] Fix issue where Administrator policy ACLs in non-Administrator groups couldnt be edited\n- [#2915] Ensure UserGroups restriction is enforced in FC Profiles\n- Fix bug when editing FC profiles from a grid, issue where UserGroup wasn't respected\n- Ensure radio TV values still can select if default value is 0\n- [#2869] Fix issue with parent display text in Resource panel\n- [#2892] Fix problem creating folders on filesystem from file manager and browser\n- [#22] Allow SymLinks metadata to override target Resource metadata\n- Cache Resource ACL Policies with the Resource\n- [#2888] Fix problem with elementCache in modX::sendForward()\n- [#2610] Allow Elements to be created under a Category when a Category Policy is in effect\n- [#2869] Standardize initial parent combo value text on Resource edit page\n- [#2736] Colon character \":\" added to default FURL Alias Character Restriction Pattern\n- [#2889] Ensure that a new Resource gets an alias generated if auto_alias is On\n- [#2837] Ensure element properties import escapes <> and provide better error checking\n- [#2886] Ensure SimpleXML and XMLWriter extensions are installed when using FC Set import/export\n- [#2882] Add hidemenu_default setting for setting default hide from menus on Resources\n- Fix issue with derivative Resource types and FC rules\n- [#2858] Extra sanity checks to ensure md5 pw is never sent across get/getlist processors for Users, even if user has access level\n- [#6] Fix issue with RTL text in nodes in Resource tree\n- [#2873] Fix relativity of image urls in drag/drop and TVs when using various filemanager_path/url settings\n- [#2878] Ensure resource panel is marked dirty when drag/dropping into TV\n- [#2828] Fix issue with incorrect content field name for FC rules\n- [#2863] Fix order of execution issues with FC rules and default values\n- [#2874] Enhance User blockedafter/blockeduntil fields to accept time as well as date values\n- [#2529] Fix automatic publish/unpublish\n- Adjust FC rule ranks to properly account for prior FC rules that may affect FC constraints\n- Update xPDO to 2.0.0-pl release\n- [#2661] Fix Template getList processor to respect authority\n- [#313] Fix header error with binary modStaticResource downloads\n- [#206] Fix session bug with opcode caching systems like APC, WinCache, eAccelerator\n- [#2846] Add tag syntax to description hover text for resource fields\n- [#2849] Add ability to drag/drop onto TV fields\n- [#2848] Fix issue with file edit and base paths\n- [#2802] Ensure Category tab is hidden when all TVs are hidden in that Category\n- [#2779] Added Content Editor policy to default list of policies\n- [#2819] Fix bug in FC rules where parent constraint was not traversing up tree to inherit parents\n- [#2744] Fix bug with empty template and TV values\n- [#2841] Fix bug with File Edit page and modFileHandler reference\n- [#2839] Fix bug with failed login count not being updated\n- Add ability to view permissions inherited when viewing an ACL row in a grid\n- [#2834] Fix issue where constraint class was not set on new FC rules\n- [#2819] Fix issue with FC rules and execution order due to setting default templates, constraints\n- [#2830] Permit ability to change FC Set Template when editing a FC Set\n- [#2827] Fix issues related to FC upgrade with Rules with comma-separated names, differing constraints, and template setting\n- Fix issue related to #2625 with deferred tabpanel rendering that caused unpublishing when using Quick Update/Create\n- [#2825] Append idx to each item DOM id when using HTML tag tv output widget\n- [#2823] Add missing lexicon entry for TV output type\n- [#2817] Reorder System top menu for easier navigation\n- [#2820] Add DOM id to Profile page tabs\n- [#2814] Add longtitle, description, template to Quick Update/Create\n- [#2789] Add check to make sure safe_mode is off in setup\n- [#2565] Improve Quick Create/Update Resource to move settings into tab rather than fieldset\n- [#2807] Add tree_default_sort System Setting for configuring the default sort setting for the Resource tree\n- [#2803] Fix css issue with portal blocks on manager dashboard in Fx\n- Add new Form Customization UI, including Form Customization Profiles and Sets; much easier editing of FC rules\n- Fix issue with modInstallSmarty constructor due to Smarty upgrade\n- [#2799] Remove ext3 debug files to save space\n- [#2801] Fix bug with checkbox tvs without specified value options\n- Upgrade Smarty to 3.0.4\n- [#2782] Add changelog to Package View page\n- [#2782] Add ability to view changelog when installing a package via the \"changelog\" package attribute (similar to readme)\n- [#2770] Ensure email TV input type validates email\n- [#2776] Fix issue where context settings grid was not filterable\n- [#2790] Ensure \"number\" TV types restrict input to numbers only\n- [#2730] Fix rendering issue with policy template/group grids\n- [#2794] Allow TV URL output render to handle values that are straight Resource IDs\n- [#2741] Fix bug where Resource Group associations were not copied when duplicating a Resource\n- [#2746] Fix bug where email was sent in registration email rather than username\n- [#2733] Fix bug where Template Var associations were not copied when duplicating a Template\n- [#2742] Fix deprecated evtid reference in plugin duplicate processor\n- Fix various bugs with context settings and wctx param\n- Fix bug where modX::getDocumentChildrenTVars ignores docsort parameter\n- [#2743] Connectors using wrong permissions with processors\n- [#2758] Add modProcessorResponse class to better handle processor responses and error messages\n- [#2758] Add $modx->runProcessor($action,$scriptProperties,$options) to better handle processor execution; deprecated $modx->executeProcessor\n- [#84] Make distribution name available in manager\n- [#2666] Prevent sendRedirect() from preserving request parameters unless specified\n- [#2721] Fixed issue with per page items in MODx.grid.Grid that was incorrectly handling int value\n- [#2691] Fixed issue with duplicate aliases when duplicating a Resource\n- [#2506] Flag properties as dirty when importing from a file on properties grid\n- [#2592] Prevent cache files from being allowed in upload_files setting\n- Improved areas dropdown filter to include number of settings that have that area\n- [#2694] Fixed positioning and scrollbar issue in Fx with success status message on save\n- Added setting clear_cache_refresh_trees that allows you to toggle whether the trees refresh on site cache clear; defaults to false\n- [#2709] Fixed bug where Object-Template policies were unavailable to certain grids\n- [#2597] Fixed bug where Context Setting xtype and area are reset on grid save\n- Upgraded extension_packages setting to JSON for more options with packages and easier editing in Extras scripts\n- Fixed bugs relating to using filemanager_path in a separate context, as well as other bugs with context-specific settings in mgr\n- [#2496] Fixed bug that prevented icon from resetting when dragging Resources into a new parent\n- [#713] Prevent children resources from being prefixed with \"Duplicate of\" when duplicating a resource unless explicitly told to do so\n- [#2581] Fixed bug with resourcelist TV input type to handle resources from multiple contexts\n- [#2518] Added delay to allow FC rules to load before RTEs load to allow RTE TVs to be moved\n- [#2611] Added workaround for ExtJS bug with checkboxes/radios and an inputValue of string 0 that would prevent toggling\n- [#2512] Have remove setup/ dir checked by default if not using Git version of MODx\n- [#2699] Fixed loading issues with help panel on slow connections\n- [#2701] Fixed issue where description did not show until refresh when adding a new Permission to an Access Policy Template\n- [#2695] Postfixed Template to names of Access Policy Templates for clarity\n- [#2700] Fixed bug with Access Policy Template editor that reset values on save\n- [#2690] Renamed Administrator Access Policy Template Group to Admin\n- [#2563] Fixed chmod action on directories from File Tree\n- [#2693] Properly sort country indicies to properly display in dropdowns\n- [#2562] Added confirm dialog and success response for emptying recycle bin\n- [#2634] Ensured context key is changed when changing parent of a Resource via Edit Resource page if context is different for new parent\n- [#2631] Fixed issue when drag/dropping categories onto other categories in Element tree\n- [#2659] Fixed issue where action buttons were overlapping tabs on edit pages\n- [#2668] Fixed issue with FC rules and labels on checkbox/radio fields\n- [#2582] Fixed bug with orm tree preventing attributes on the root node\n- Fix bug in phpthumb allowing remote src parameters regardless of settings\n- [#2555] Expose additional phpthumb options in System Settings\n- [#2503] \"Preview\" inaccurately described viewing current page/site. Changed to \"View\".\n- Fixed help message strings to correct URLs\n- Fixed missing options array call in modRestClient, isArray call in modRestCurlClient\n- [#2545] Added setting resource_tree_node_name to allow users to specify the field used for the node text on the Resource Tree\n- [#2639] Prevent user from specifying a FC rule with Action of none\n- [#2641] Fixed issue where template was reset incorrectly when canceled on template change\n- Fixed issue where Permissions were being duplicated on setup due to relational db issue\n- [#2646] Prevent removal/editing of default Administrator policy ACLs to prevent users from accidentally removing access to web context\n- Added modAccessPolicyTemplate and modAccessPolicyTemplateGroup for easier managing and editing of Access Policies, including a UI for managing Access Policy Templates\n- [#2483] Auto-generate alias when duplicating a Resource\n- [#2645] Set Resources unpublished when duplicating\n- Update to xPDO v2.0.0-rc3\n- [#2501] Fixed menu not being loaded on immediately-added policies without page refresh, added bulk actions to policy grid\n- [#2505] Save Property Set now shows feedback and success message\n- [#2507] Export properties now prefixes filename with property set name\n- [#2624] Improved Users grid to allow batch editing from right-click context menu\n- [#2609] Remove filter commands and modifiers from scriptProperties passed to modElement/modTag instances\n- [#2500] Improved CSS on welcome page for Fx users\n- [#2532] Improved Resource tree icons to better shown when a Resource has children as opposed to when it is marked as a container\n- [#2602] Improved language on Users access permissions grid to clarify action\n- [#2614] Expand comment field on modUserProfile to handle more than 255 characters\n- [#2613] Ensured User Groups in mgr are sorted alphanumerically\n- [#2599] Fixed issue where Add Element to Property Set window form values were not cleared on second loading\n- [#2596] Fixed issue where User Groups could not be removed\n- [#2542] Fixed hardcoded language lexicon load reference in policy/get processor\n- [#2573] Fixed issue with backslash in TV output render property values\n- [#2594] Fixed issue where special characters were being stripped from phone numbers in user profile\n- Fixed issue with file tree that prevented image thumbnails from showing\n- [#2525] Fixed filemanager_path issues by added filemanager_path_relative setting, and then calculating from that\n- [#2589] Fixed issue with port 80 feeds in magpie RSS feed parser\n- [#2544] Fixed issue with updatefromgrid processor with User Settings\n- [#2560] Fixed issue with resourcelist TV not persisting set value\n- [#2586] Add rank field to FC rules allowing organizing of order of execution\n- Update core schemas and regenerate maps for new xPDO index elements\n- [#69] Allow Transport Vehicles to abort installation when validation fails\n- Update xPDO version to 2.0.0-rc2 (official release)\n- [#2552] Fix scope issues when passing nested arrays in Chunk properties", "MODX Revolution 2.0.4-pl2 (October 15, 2010)\n====================================\n- [#2502] Fix fatal error with Resources protected by Resource Groups\n- Fixed issue with resourcelist TV", "MODX Revolution 2.0.4-pl (October 14, 2010)\n====================================\n- Fixed issue where redirect was not working after creating new derivative resource\n- [#2485] Fixed issue where placeholder was in duplicated Access Policy\n- [#2492] Fixed reference in menu to bugs.modx.com\n- [#2486] Removed hardcoded language reference in lexicon load in access permissions getList processor\n- [#126] Ensured clearing of cache when deleting a Template Variable\n- Fixed issue where cancel button did not work on Resources after save\n- Fixed issue with URL TV Output Render and empty input values\n- Fixed issues with checkboxes/radios in TVs and widths when hidden\n- Fixed various issues with thumbnails in MODx.Browser and return paths in separate contexts\n- Added toggle setting for drag/drop in Resource and Element trees\n- [#MODX-2346] Allow login/logout processors to handle multiple contexts\n- [#MODX-2405] Fixed issue with border on portal panels in mgr home screen\n- Fixed issue with TV output render that stripped whitespace in delimiter\n- Fixed hanging save issue that occurred when HTML was in pagetitle/longtitle in a Resource\n- Fixed issue where TV values were being erased when a TV was hidden via Form Customization\n- Updated reference to help in Form Customization page\n- Fixed trivial issues with widths in richtext tvs\n- [#MODX-2415] Added fix to prevent adding of orm tree attributes with the same key on the same level\n- Added resourcelist TV input type for easier listing of resources in a tv input\n- Updated ExtJS to 3.3.0\n- [#MODX-2378] Fixed issue where action toolbar was on left in IE7\n- [#MODX-2408] Fixed issue where sorting was not available for description field on search page\n- Fixed issue where modx->resource was not available to TV input option values or default values in mgr\n- [#MODX-2410] Fixed issue with urlencoded context key on context edit page\n- [#MODX-2407] Fixed issue where user settings were not respected in connectors in mgr\n- [#MODX-2279] Fix bad AJAX response if database does not exist or can't be created during setup\n- [#MODX-2404] Fixed issue with auto_menuindex and multiple contexts\n- [#MODX-2354] Fixed issue with image TV loading incorrect URL in thumbnail preview on initial load\n- [#MODX-2357] Properly addressed issue where FC hideTab rule was causing hidden tabs to show if they were active at load\n- Refactor modAccessibleObject to centralize load policy check in _loadInstance()\n- Update xPDO for several critical bug fixes\n- [#MODX-2402] In Package Browser, Most Popular/Recently Added package names are now links to auto-search in grid\n- [#MODX-2397] Added filtering and search to FC rule grid\n- [#MODX-2401] Adjusted JS version postfix code to not adjust .php (or non-js) files used as script src targets\n- Improved context menus on FC rule grid to allow for batch actions on selected items\n- Added `for_parent` field to FC rules, to allow for more fine-grained control of rule applications\n- [#MODX-2385] Fixed issue when Context ACL is using no policy that prevented grid loading\n- [#MODX-2380] Fixed issue with upgrades and rb_base_dir, rb_base_url and filemanager_path\n- [#MODX-2246] Added topmenu_show_descriptions system setting to be able to toggle the top menus description text\n- [#MODX-2375] Improved class key field in Resource panel to a dropdown, added modClassMap for easier querying of resource/element types\n- [#MODX-2391] Fixed issues with FC rules not being respected on resource/create with default values for new Resource\n- [#MODX-2382] Fixed dynamic width of fields in windows across ui\n- [#MODX-2383] Fix inability to update rank of TV's in template editor\n- [#MODX-2379] Fixed issue where permission checks were swapped in Resource context menu with regards to delete/undelete\n- [#MODX-2384] Fixed issue where treepanel still showed if all trees were hidden via permissions\n- [#MODX-2389] Fixed issue where setup options, license and readme displays were not cleared after installation of package\n- Fixed issue where loading mask shows up and never disappears on extended Resource types\n- [#MODX-2388] Fixed issue with save button and user settings\n- [#MODX-2387] Fixed issue with user settings not able to be added via mgr ui\n- Fixed bug that would reset provider for updated packages\n- Fixed issue with paging toolbar pageSize being interpreted as string rather than int\n- Fixed issue where parent id constraint was ignored for default template on new Resources\n- Added sanitization to REQUEST_URI for login controller\n- Updated version to 2.0.4-pl", "MODX Revolution 2.0.3-pl (September 30, 2010)\n====================================\n- Fixed error in modResource::cleanAlias when context var is not available\n- [#MODX-2376] Fixed issues with updating settings on the context page\n- Fixed security issue with login screen and resource TV controller that allowed html injection\n- Fixed issue where clear cache checkbox isn't checked on Element pages\n- [#MODX-2370] Fixed various bugs with plugin event association on plugin page\n- [#MODX-1823] Improved the System Info panel by extracting data from phpinfo()\n- [#MODX-2362] Added missing OnResourceTVFormPrerender event\n- [#MODX-2374] Fixed issue where children nodes were not being moved with parent into new context\n- [#MODX-2373] Fixed imageTV issue where thumbnail was not cleared on data clearing\n- [#MODX-364] Fixed regClient* methods in cacheable Snippets on cacheable Resources\n- [#MODX-2370] Fixed issue with saving property sets on plugin events\n- [#MODX-2369] Fixed issue with modLinkTag and output filters where the filter commands were included in the URL\n- [#MODX-2350] Ensure that new Contexts always have Admin and Resource policy for Admin user group assigned to them\n- [#MODX-2352] Ensure that Context Settings appropriately override System Settings in core-level parsing where a Context is existent (example: site_unavailable_page)\n- [#MODX-2356] Ensure that OnResourceDelete and OnResourceUndelete events in update processors fire at correct times, after save()\n- [#MODX-2361] Ensure that a user in the Administrator group *always* has access to a Context when it is restricted in another user group\n- [#MODX-2357] Fixed bug that occurs when hiding a tab with FC rule that is the default active tab\n- [#MODX-2358] Fixed rare bug occurring with treestate in Chrome due to undefined variables in path\n- Fixed various issues with package management and the add new package button\n- Fixed bug where ?v=203pl is being added to content with .js in it, due to earlier commit to prevent js caching\n- Fixed issues with ellipsis/limit filters and special chars\n- [#MODX-2353] Fixed bugs with checkbox/radio TVs and complex values with HTML/quotes in them\n- Fixed some bugs with deleting a file in MODx.Browser in the actual view pane\n- [#MODX-2354] Fixed issue with imageTV and incorrect preview url reference\n- Fixed ellipsis output filter to use &#8230; instead of ...\n- [#MODX-2327] Fixed bugs with Form Customization not being respected\n- [#MODX-2349] Fixed bug with Form Customization and fieldDefault rule with template field\n- Added code to prevent caching of JS after upgrades by postfixing version to JS URLs\n- [#MODX-2342] Fixed issue where xhtml_urls setting wasnt included in build\n- [#MODX-2345] Fixed issue with templates and categories in mgr not persisting\n- [#MODX-2341] Fixed issue with redirect statement on login page in certain environments\n- [#MODX-2343] File upload now respects upload_* extension restrictions\n- [#MODX-2344] Respect context-specific filemanager_path in upload/remove actions on directory tree in mgr", "MODX Revolution 2.0.2-pl (September 17, 2010)\n====================================\n- Fixed issue where Add New Package would not work when selecting a provider manually\n- [#MODX-2339] Fixed issue with caching menus in mgr and multiple languages\n- [#MODX-2340] Fixed issue with initial resource values reverting after a save\n- [#XPDO-72] Fix invalid call to $this->manager->getPhpType()", "MODX Revolution 2.0.1-pl (September 16, 2010)\n====================================\n- [#MODX-2317] Add responseCode parameter to modX::sendRedirect() method\n- Fixed issue with @DIRECTORY binding not postfixing base path with / before value\n- Many styling enhancements, fixes for [#MODX-2264], [#MODX-2193], [#MODX-1885], [#MODX-1847]\n- Fixed issue with lexicon translations for permissions dropdown in mgr\n- Enhanced system settings grid to autosave without refresh, which allows for tabbing between settings via keyboard to set values\n- [#MODX-2325] Updated placeholders in setup lexicons for french/german languages\n- Added an editable dropdown for Permissions tab when editing an Access Policy for easier addition of Permissions\n- Fixed issue where default template was overriding empty template resources\n- [#MODX-2325] Updated Czech translation\n- [#MODX-2329] Login page now auto-focuses on username textfield\n- Add missing modCategoryClosure to create_tables script in setup\n- [#MODX-2280] Fixed bugs with IE and package management\n- Prevent issue where a User Group can select itself as a parent\n- Allow typeahead on user field when adding a User to a User Group\n- Optimized Resource Group tree in mgr UI\n- Fixed issue where > 20 records were not showing in ACL lists in User Group edit panel\n- [#MODX-2206] Prevent issue where renaming a menu's lexicon key orphans child menus\n- Fixed rendering bugs in file edit panel, as well as optimized its loading and streamlined RTE integration on the panel\n- [#MODX-2202] Removed deprecated modAction objects to prevent confusion\n- [#MODX-2325] Updated Swedish translation\n- Prevent bug that causes modal to overlap welcome screen\n- Allow non-empty responses to OnBeforeTVFormSave to prevent save\n- [#MODX-2201] Ensure MODX_PROCESSORS_PATH is upgraded correctly on upgrades where the core is moved\n- [#MODX-2323] Allow non-empty responses to OnBeforeDocFormSave to prevent save\n- [#MODX-2309] Ensure upload files button always uses the active node as the path, or if it is a file, its parent directory\n- [#MODX-2295] Ensure menuindex can be overridden in resource creation if auto_menuindex is set to true\n- Fixes to resource panels to adjust widths, loading of values properly\n- [#MODX-2318] Fixes to TVs in Resource pages to make order sorting work correctly\n- Abstracted setup database methods to driver-specific structures to accomodate for various future db drivers\n- [#MODX-2241] Added archive_with setting so users with improper ZipArchive compiles can switch back to PCLZip\n- Updated xPDO to include sqlite drivers\n- [#MODX-2308] Added UUID to all modx installs for usage in extras, custom providers, stats tracking, etc\n- [#MODX-2303] Fixed issue where resource editing pages were not respecting context settings\n- [#MODX-2302] Fixed issue with loading of input option values in TV related to optimizations in 2.0.1\n- [#MODX-2297] Fixed output filters limit/ellipsis when dealing with special character cases\n- [#MODX-2290] Added image preview when hovering over images in file tree\n- Added extra sanity checks in Package Management in case transport zips are not extracted\n- Make package grid update available Yes clickable to update\n- Cleaned up and better abstracted modRestClient and modRestCurlClient code\n- Fixed bug in setup during upgrade-advanced where DB information was not being checked correctly\n- Lots of improvements to handling and caching of thumbnails in manager\n- Fixed bug where reset filter on settings grid was not resetting to core namespace\n- [#MODX-2178] Added missing settings and lexicon values for those settings to build/lexicons\n- [#MODX-2179] Lexicons in Setup now use placeholders rather than sprintf for better i18n support\n- Added phpthumb_imagemagick_path for users that need to change the imagemagick path for different environments\n- [#MODX-2288] Dont duplicate TV Resource values when duplicating a TV unless explicitly told to\n- [#MODX-2217] Persist sort order of Resource tree\n- [#MODX-2291] Prevent editing of binary files to prevent zeroing out of file when saving\n- [#MODX-2185] Resource tree expand all toolbar button now expands all levels deep\n- [#MODX-2260] Added ability to rename ORM container nodes on extended fields\n- [#MODX-2285] Added ability to dynamically set number of results for any grid in manager, as well as a default number via default_per_page system setting\n- [#MODX-2284] Fixed bug in modX::getChildIds\n- Adjusted the way resources/elements load data in mgr edit/create pages to vastly speed up load times\n- [#MODX-2282] Fixed deprecated help menu URLs\n- Trees now properly handle state, allowing multiple state paths to be set\n- [#MODX-2163] Give area combobox in System Settings a bit more breathing room\n- [#MODX-2259] Fixed issue with empty value fields in extended/remote fields via ORM widget\n- [#MODX-2249] Fixed issue with misleading comment in modTemplateVar::getValue\n- [#MODX-2270] Added option to sort by pulishedon in the resource tree\n- [#MODX-2278] Removed non-used files and added space to empty files\n- [#MODX-2250] Fixed bug where Checkbox TVs with default value dont allow all checkboxes unchecked\n- [#MODX-2274] Introduced filemanager_url setting to handle URLs when filemanager_path is outside the webroot\n- [#MODX-2251] Fixed issue where @bindings in TVs were running during input, preventing setting values\n- Fixed bug with modContext::getOption and default values\n- [#MODX-2184] Fixed issues with MODx.rte.Browser and context-specifics\n- Fixed issue with filemanager_path in Windows\n- Fixed a possible issue in base file perms in modFileHandler\n- Fixed some random typos in system settings data and lexicon translations\n- Fixed bug where userinfo filter was outputting wrong content when user was empty\n- [#MODX-2263] Fixed IE issue with dropdowns as TVs\n- [#MODX-2183] Autotag values are now alphabetically sorted\n- [#MODX-2240] Site - Preview now dynamically previews current editing context\n- Fixed invalid login issue that prevented OnUserNotFound from firing on mgr login screen\n- [#MODX-2238] Fixed bugs regarding parent constraint and default template\n- [#MODX-2234] Fixed issue when drag/dropping a Resource into the parent field\n- [#MODX-2226] Fixed bugs with date output filter not behaving as expected\n- [#MODX-2184] Fixed issue where context was not respected in MODx.Browser instances, fixed bugs when specifying paths outside MODX_BASE_PATH\n- [#MODX-2236] Added sanity check to modTemplateVar::getRenderDirectories with custom dirs\n- Added modResource::joinGroup\n- Added helper JS function MODx.hideTV to modext\n- [#MODX-2233] Fixed issue where qtip was not showing on Elements in a Category\n- [#MODX-2203] Fixed issue where root of file tree was not accessible after navigating away\n- [#MODX-2192], [#MODX-2232] Fixed issues with settings and their translations, names in the Settings grids\n- Adjustments and optimizations to menus/actions processors and js\n- [#MODX-2231] Fixed issue where saving translated properties would overwrite key with translation\n- [#MODX-2220] Fixed bug where save_user was needed to change profile\n- [#MODX-2213] Always include english lexicon when loading a lexicon to act as a backup translation\n- [#MODX-2210] Added strip for xss in manager a variable\n- [#MODX-2205] Fixed issue with saving resources with resource fields having html and unescaped content\n- [#MODX-2198] Fixed directory checks on context web path for advanced distribution\n- [#MODX-2194] Fixed issue with modLexicon::fetch not working if a prefix is set\n- Removed SVN commit log from top header now that we're in Git\n- Adjusted version to 2.0.1-rc1", "MODX Revolution 2.0.0-pl (LastChangedRevision: 7216, LastChangedDate: 2010-07-21 09:10:12 -0500 (Thu, 21 Jul 2010))\n====================================\n- [#MODX-2159] Fixed bug where richtext_default was being ignored in Quick Create\n- [#MODX-2174] Fixed bug where manager_language was being ignored in Connectors, check for ctx init\n- [#MODX-1715] Added reference to setting keymap_save to allow for overriding of save shortcut key\n- [#MODX-2008] Updated Russian and Japanese translations\n- [#MODX-2008] Added in Thai translation\n- Fixed typo in filters english lexicon\n- [#MODX-2008] Added in French translation, updated German translation\n- [#MODX-2173] Fixed issue with IE and package installation wizard\n- Fixed setup directory checks for advanced builds\n- Fixed incorrect welcome URL in build\n- [#MODX-2008] Added in Czech translation\n- Configured phpdoc.ini file for SDK build\n- Fixed bug in file tree where URL was absolute rather than relative when being drag/dropped\n- Added OnFileEditFormPrerender event to allow plugins to fire on file editing form\n- [#MODX-2172] Fixed bug where tooltips for stay buttons were behind window\n- Sanity checks to tv render directories\n- Removed deprecated CSS icon reference\n- [#MODX-2169] Fixed bug with TV default values, inheriting and non-linear TV inputs\n- [#MODX-2170] Fixed error where element names cannot have less than 3 characters\n- [#MODX-2169] Properly handled @INHERIT binding in TV inputs\n- [#MODX-2165] Changed 'Remove Package Version' context menu item behavior to allow to show on non-installed versions to allow rollbacks from downloaded but not installed updates\n- [#MODX-2164] Fixed issue that might cause random, non-affecting error during package updates\n- [#MODX-2008] Added in Japanese translation\n- [#MODX-2163] Default settings grid to show only core namespace settings to reduce confusion\n- Added autotag TV input widget that grabs tags from a list of the tags so far for all content values for that TV\n- [#MODX-2161] Added sanity check for incorrect or invalid filemanager_path values in file tree\n- Added missing deleted checkbox on resource panels\n- [#MODX-2167] Fixed issue where duplicate button was creating incorrect duplicate name\n- [#MODX-2162] Fixed issues with set to default in TV values, reliance on processedValue\n- [#MODX-2168] Fixed new user panel issue with missing JS reference\n- [#MODX-2160] Fixed bug where config check was running checkPolicy on resources that caused inadvertent missing unavail/error page message\n- Some query optimizations in processors\n- [#MODX-2159] Ensure richtext_default setting is respected\n- Fixed bug where context settings create modal wasnt resetting values\n- Added missing tabpanel IDs for various tabpanels across mgr ui\n- Fixed bug that was strtolower'ing any strings in tabNew FC rule\n- Added grid renderer to FC grid\n- Tweaks to general UX, other slight cosmetic fixes\n- [#MODX-2156] Fixed unitialized variable in modTemplateVar::renderOutput/renderInput\n- [#MODX-2152] Fixed issue where local package dialog wasnt showing after clicking modxcms.com package browser\n- [#MODX-2154] Fixed issue where publish_document access permission was being ignored in resource processors\n- [#MODX-2149] Fixed issue where Package Management's modal would only once if hidden\n- Fixed issues with stay button on resources\n- [#MODX-2008] Added Swedish translation\n- [#MODX-2148] Fixed image TV thumbnail sizing\n- [#MODX-2145] Fixed 'New' context menu text to be easier to translate\n- Slight tweaks to CSS for MODx.Browser file thumbs\n- [#MODX-2147] Added phpThumb settings for controlling thumbnail output in manager, defaulted zoomcrop to off and force aspect ratio to on, center\n- Fixed erroneous change template message\n- [#MODX-2143] Fixed filemanager_path implementation so that thumbnails and relative URLs in browsing work with absolute and relative paths as setting\n- Removed powered-by text in request headers in AJAX calls\n- [#MODX-2143] Fixed issue where if filemanager_path was set differently that URL insertion on TVs or drag/drop was incorrect\n- Added urlencode/urldecode to filters\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings without breaking makeUrl()\n- [#MODX-2142] Fixed issue where translations in settings, properties and permissions were not being translated or falling back to english\n- [#MODX-2132] Reverting commit in r7125 due to side issue caused by fix in it\n- Hardened security on some file download actions in mgr such as console output, phpinfo, properties export\n- Adjusted setup expiry to 15 minutes\n- [#MODX-2139] Added message to display if setup has to restart due to timeout\n- [#MODX-2140] Fixed welcome page to point to static page rather than atlassian stack\n- Update Help URLs to new base url for docs\n- Some UI tweaks to lexicon grid, added reset() JS method to MODx.Window for shorter code\n- Added in create entry to lexicon management\n- Ensure $modx is available in custom TV renders\n- [#MODX-2137] Fixed bug in image TV output render\n- [#MODX-2138] Fixed textarea bug in system settings\n- Allow MODx tags in TV descriptions in input renders, but prevent HTML tags\n- Fixed bug where output render type was being ignored\n- Ensure tv data isnt sent back in resource update processor, to prevent escaping problems with richtext tvs\n- [#MODX-2109] Fixed setup to have upgrade mode not go to editing database/contexts, only advanced upgrade goes there\n- Fix object caching bug in modAccessibleObject::_loadCollectionInstance()\n- Update xPDO 2.0 to revision 429\n- Ensure extended fields can be added to users with none pre-existing\n- [#MODX-2131] Fixed other issues with TV values and rendering\n- Added ctrl+alt+p key shortcut when updating a Resource to preview it\n- Prevent illegal drops of actions to menus, menus to actions, in trees on Actions page\n- Slight fixes, tweaks to plugin events grid\n- [#MODX-2130] Fixed typos and missing references in mb-based output filters\n- [#MODX-2131] Fixed various issues with TV rendering, values, and in multiple contexts\n- [#MODX-1404] Make MySQL client version check a warning only for older versions\n- [#MODX-1404] Remove MySQL client version check for 5.0.51\n- [#MODX-2024] Fix use of %s strftime modifier in modSessionHandler::write()\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings\n- [#MODX-2107] Fix errors with friendly alias slug generation with certain multi-byte characters\n- [#MODX-2114] Fix Error Caching Resource log message when site unavailable or other transient Resources are constructed\n- [#MODX-2129] Added missing Resource events\n- Fixes to Messages page/grid\n- Added optimize database button on database tables grid\n- Fixed reference bug in resource/update processor\n- Improvements to Users grid to dim inactive users\n- Fixed a few bugs with MODx.Browser and file tree\n- [#MODX-2127] Added message to Package Management if cURL or Sockets is not installed that prompts user to do so\n- Added ability to send warning/error messages to all MODx.* grids/trees\n- [#MODX-2128] Fixed MODx.Browser in RTE mode\n- Added modManagerRequest::addLangTopic,setLangTopics,getLangTopics assistance methods\n- [#MODX-2125] Various fixes for manager log page\n- [#MODX-2023] Added sanity checks for settings caches in setup, ensure settings caches are removed post-setup\n- [#MODX-2064] Ensure Action combos in System Actions page are reloaded when an action is updated/created/removed\n- Fixed invalid validation rule on element classes\n- [#MODX-2091] Ensure duplicate maintains published status\n- [#MODX-2123] Added workaround for IE with Quick Update Resource window\n- Modified validation on modChunk, modPlugin, modSnippet, and modTemplateVar to allow spaces within a name\n- [#MODX-2052] Fixed bug with loading multiple MODx.Browser instances in non-file management circumstances\n- Updated duplicate processors to check validation, return more informative messages, sanity checks\n- Removed duplicate days keys in lexicon\n- Fixed issues when TV render directories are overridden\n- [#MODX-2115] Fixed issue with phpthumb reference and capitalization, and when base_url is /\n- [#MODX-2113] Fixed CTRL+SHIFT+H shortcut for hiding left nav\n- Fixed bug in ORM tree relating to adding root nodes when subnode was selected\n- Added ability to add/remove attributes and containers to UI ORM trees, specifically in User extended and remote data\n- Added UI for editing extended User Profile data\n- [#MODX-2116] Fixed bug in depth search in modX::sanitize\n- [#MODX-1150] Changing class_key for a Resource now reloads the page to change editing area\n- [#MODX-2077] Config check screen in welcome panel now is same width as other panels\n- [#MODX-1648] Lexicon Management now loads by default the current manager_language\n- [#MODX-1743] Package update now shows status alert when package is already up to date, rather than an error\n- [#MODX-2119] Fixed bug in IE where onunload was firing regardless, preventing moving off page seamlessly\n- [#MODX-2112] Fixed bug where admin password reset was not working\n- [#MODX-2111] Fixed bug where language settings were not set after running setup in another language\n- [#MODX-2110] Fixed bug where resource fields were not being updated on update, causing publishedon errors\n- Adjusted version for pl development", "MODX Revolution 2.0.0-rc-3 (LastChangedRevision: 7083, LastChangedDate: 2010-07-07 12:20:55 -0500 (Wed, 07 Jul 2010))\n====================================\n- Updated German translation\n- Fixed bug with new installs and base template name\n- Fixed UI issue with Namespace path being unwantingly translated\n- Upped timeout on setup settings cache to 10 minutes; was far too short\n- [#MODX-2040] Fixed bug with setProperties and merge argument\n- Slight tweaks to phpthumb default config\n- Added sanity check when using multiple TV render directories\n- [#MODX-2100] Fixed content type creation for binary type bug, bug in build with regards to content types\n- Added flag to setup to fix proceeding error after install\n- Fixed setup to return setup process to very beginning when settings timeout, avoiding various errors about classes not being found\n- Added modx-tv-checkbox class to resource TV checkboxes for easier DOM manip\n- Added showCheckbox setting for resource TVs display to allow for extensibility and TV targeting\n- Added phpThumb specific settings\n- Added OnResourceTVFormRender event for affecting TV displays on resources\n- [#MODX-2104] Auto-detect correct value and set use_multibyte on new installs\n- [#MODX-2104] Added 'use_multibyte' setting that allows for use of mb_* functions for multibyte characters; fixes bug with MB chars in output filters\n- [#MODX-2019] Added default Element policy\n- Fixed issue with Ext.form.BasicForm and prior commit, adjust else/if condition\n- Added headers check to all Ajax requests to connectors to require unique site ID header to harden security\n- Added modx-content-above and modx-content-below divs for RTE usage\n- [#MODX-2008] Updated Russian translation\n- Enabled RTEs to be used on TV default value field\n- Added which_element_editor setting, which allows for usage of multiple RTEs for Elements vs Resources\n- Fixed bug with custom_resource_classes setting implementation on blank values\n- [#MODX-2094] Enabled Packages to be able to have their Provider changed\n- [#MODX-1809] Added manager_time_format to allow changing of time formats in mgr widgets\n- Added extra var to pass revo version in transport provider requests; helps with download metrics and version checking\n- Optimized package grid by moving menus to JS\n- Fixed issue where manager_language setting was being ignored in mgr connectors\n- Enhance security on language string loader\n- [#MODX-1834] Adjusted color on Yes/No on packages grid to more reflect intent\n- Readjust JS firing timing for Elements to prevent RTE timing errors in faster browsers\n- [#MODX-2090] Added auto_check_pkg_updates_cache_expire setting, which caches package update checks in Package Management to speed up grid load times\n- Ensure Resource pages using RTEs always have save btn enabled\n- Fixes to RTE loading in Element panes, other issues regarding timing of plugin firing\n- Fixed bug with area listings in combo in system settings\n- [#MODX-1961] Fixed bug with octal perms when creating directories in the admin\n- [#MODX-1527] Fixed bugs in admin confirm password field on install\n- Fixed Package Management in IE8\n- Styling improvements\n- Fixed IE issue on navbar, few other tweaks to package management for IE\n- [#MODX-2032] Fixed topic varchar length issue with UTF-8 installs\n- [#MODX-1612] Added Create Menu context menu on root node for menus tree\n- [#MODX-2020] Ensure error when creating duplicate context ACLs shows\n- Tweaks to Package Management browser JS to allow for more consistent rendering\n- [#MODX-2051] Stripped tags from TV description field on input rendering\n- Added 'custom_resource_classes' setting, which allows you to specify custom resource types for the resource tree\n- Tweaked FC tvMove rule to be more consistent with values of other TV FC rules\n- Allow blank names (not keys) in Settings create/update windows; tweaks to query in package management grid\n- [#MODX-1737] Container resources can now have names specified on duplicate\n- [#MODX-2074] Fixed bug where property descriptions were not i18n-able\n- [#MODX-2062] Date TV type now can store time; updated datetime ExtJS xtype to latest version\n- [#MODX-2046] Added 'collapse' toggle to left trees, shortened username on top right to allow for small resolutions\n- [#MODX-2067] Fixed bug with cleanAlias and a non-existent lexicon string\n- [#MODX-2086] Fixed a few bugs in package management styling\n- Tweaks to context menu styling\n- [#MODX-2078] Context menus now show under cursor\n- [#MODX-2083] Fixed bug where setting editedon was returning invalid date\n- [#MODX-2061] Fixed erroneous lexicon entry for cache_handler setting description\n- [#MODX-2085] Fixed issue with namespace path not being translated on get\n- Added ability to activate/deactivate FC rules from context menu\n- fieldVisible, fieldLabel, tvVisible, tvMove Form Customization rules now support multiple fields via comma-sep list\n- Added functionality to Form Customization to add new Tabs and move TVs to other tabs\n- Applied CSS gradient styling to grids, tabs\n- [#MODX-2056] Fixed CSS for topmenu, restyled to add contrast and enhanced\n- Cleaned up TV display panel, removed TV reload button, extended fields all the way across\n- [#MODX-1832] moved \"Set to Default\" to a fade-in icon\n- Prepared code for oncoming feature to move TVs into other tabs\n- Removed credits from about pane, consolidated tabs\n- Fixed permissions checks on resource tree context menu when policies are limited\n- Added prefix filtering to modLexicon::fetch\n- Added modTemplateVar::getDisplayParams for easier fetching of display_params for a TV\n- Fixed bug with custom TV render paths\n- Added phpThumb to core, added connector for secure access, integrated into MODx.Browser\n- Ensure categories in TV panel are sorted alphanumerically\n- Added stripString, cdata, replace, fuzzydate and ago output filters\n- [#MODX-2045] Added ExtJS, Smarty, PHPMailer, MagpieRSS version into System info\n- [#MODX-2057] Fixed bugs with action/menu trees\n- Fixed bug with is_writable check in setup; was checking core/config rather than just core/config/config.inc.php\n- [#MODX-2042] Fixed extra beginning slash for image/file TVs\n- Add validation to processors for Chunks, Plugins, Snippets, and Template Variables\n- [#MODX-1998] Disallow reserved Template Variable names (i.e. Resource field names)\n- [#MODX-2033] Fix bug with unchecking Template Variable access when editing a Template\n- Have modX::switchContext() update placeholders from config on successful switch\n- [#MODX-1774] Remove redundant setting of placeholders from modX::$config in modRequest::handleRequest()\n- [#MODX-2031] Fix modX::stripTags() and modX::sanitize() to properly strip nested element tags\n- [#MODX-2027] Added icon to file tree to show MODx Browser, for a different view on file management\n- [#MODX-1924] Made more precise the cursor pointer change on buttons in mgr\n- [#MODX-1904] Fixed bug with phx placeholders in modTranslate095 class\n- [#MODX-1535] Fixed bug with transparent background for grid-based comboboxes\n- [#MODX-1904] Fixed bug with phx placeholders in modParser095 class\n- [#MODX-1936] Lexicons now fallback to English if no translation is found for specified language\n- [#MODX-1781] Fixed z-index issue with top nav and window masks\n- [#MODX-217] Added create element type icons for Element tree\n- [#MODX-217] Added directory create icon to file tree toolbar, changed upload files button to icon\n- [#MODX-2022] Fixed bug regarding php file permissions and writable checks\n- Fixed bugs related to loading of RTEs for TVs in derivative resource classes\n- Enhanced image TV to show preview of image, adjusted to display below\n- [#MODX-2015] Added sanity check to prevent users from dragging Resources to a non-existent context\n- [#MODX-2013] Fixed bug where hiding fields with Form Customization would disable them from being sent\n- Fixed bugs with System Settings grid due to erroneous merge in UI styling\n- [#MODX-2012] Made Form Customization grid sortable\n- [#MODX-2011] Fixed MODx.grid.Grid::getSelectedAsList to work in Fx,IE\n- Added more sophisticated check for writable directories in setup to ensure compatibility across environments\n- Fixed bug where manager_language setting was ignored\n- [#MODX-2007] Redirect to requested mgr page when logging in\n- Adjusted version for RC-3 development", "MODX Revolution 2.0.0-rc-2 (LastChangedRevision: 6924, LastChangedDate: 2010-05-27 15:56:51 -0500 (Thu, 27 May 2010))\n====================================\n- Fixed copy-prepared-css command in build.xml to prepare for rc-2 release\n- Adjusted welcome screen URL to go to a non-release specific confluence page\n- [#MODX-2000] Fixed FC rule to apply to template fields by overriding in controller\n- [#MODX-2000] Add ability to specify a template in REQUEST or alter via plugin in resource/create controller\n- [#MODX-2004] Allow settings to be duplicated when duplicating a context\n- Added missing OnUserBeforeRemove event\n- [#MODX-1797] Fix bug with publishedby field getting updated unintentionally\n- [#MODX-1919], [#XPDO-52] Update xPDO to revision 425 for fix to xPDOManager::createObjectContainer()\n- [#MODX-1918], [#MODX-1919] Improve error reporting in database setup steps\n- Made default click behavior for Files in file tree be to edit\n- [#MODX-1995] Fixed issues regarding sending password via email with new users\n- [#MODX-1549] Preserve file tree state\n- [#MODX-1810] Gender now saves correctly in user panel\n- [#MODX-1635] Redirect to Users grid after creating a new user\n- Fixed bug with import properties\n- [#MODX-1971] Allow ./- in Context key names, but not as first character\n- [#MODX-1997] Added ability to duplicate and set inactive/active Form Customization Rules, batch actions to Rule grid\n- Cleaned up profile editing page\n- Cleaned up style for headers on welcome page\n- Reworked System Info page, cleaned up styling, display, info\n- Added batch actions to Users grid\n- Fixed bugs with removing directories in file tree\n- [#MODX-1996] Fixed missing create/update settings windows\n- Allow for separate paths on derivative resource types based on a [classkey]_delegate_path setting that points to their controllers, added checks to prevent path mapping\n- Prevent deferred render on left nav trees, to prevent loading errors for js hooks\n- Fixed bugs with MODx.grid.encodeModified/encode, plugin event saving\n- Added loadCreateMenus JS event to modx-resource-tree modext widget\n- Refactored js lang loading to allow for dynamic modification of strings\n- [#MODX-1993] Moved config.inc.tpl to core/docs to prevent confusion\n- Added description below TV rows in Resource edit\n- [#MODX-1853] Fixed issue where reload button was above MODx.Browser in TV pane\n- Switched Quick Create/Update Resource description field to more-used introtext field\n- [#MODX-1992] Fixed error in modSnippet preventing multiple executions per request\n- [#MODX-1983] Clarified package uninstall option message\n- [#MODX-1982] Fixed broken cancel button on Package View page\n- [#MODX-1989] Fixed incorrect var reference in getfiles processor\n- Added extra pagination to dropdowns in mgr that might have large #s of records to add usability for large sites\n- Fixed all Elements including Template Variables to properly respect modAccessCategory ACLs.\n- Allow base-level Element Category ACL assignments\n- Fixed some issues with Settings grid and lexicons, key not being displayed, etc\n- [#MODX-1940] Resized lexicon grid toolbar to fit better in smaller resolutions;\n- [#MODX-1950] Adjusted permissions to allow proper listing of Elements; checks 'list' policy on Element now rather than view_[element]\n- [#MODX-1975] Added warning messages for PHP 5.2.0 and 5.1.6 versions in setup asking that users upgrade to 5.3.0+; will still allow installs, however, if the user has those versions\n- [#MODX-1967] Added warning to setup for people who are using PHP 5.3.0+ and dont have date.timezone set\n- Added proper permission checks to Elements/Categories across processors/controllers\n- Added UX for managing Element Category access for User Groups\n- Add modAccessCategory to allow context-specific security policies on modCategory as well as any modElement via the related modCategory; includes policy inheritance to sub-categories\n- Add modCategoryClosure table class to allow for easy recursive queries on modCategory\n- Fixed bug caused by JS/CSS optimizations that would break left nav when too many resources were loaded\n- Fixed bug where access contexts for admin user were being duplicated on upgrades\n- Added extra options to attaching with modPhpMailer; fixed bug in phpmailer that caused E_DEPRECATED errors\n- [#MODX-1912] Added manager logging to file/directory actions\n- [#MODX-1912] Added file/directory specific permissions to allow more fine-grained security on using the file manager\n- [#MODX-1972] Added OnTVInputRenderList, OnTVOutputRenderList, and OnTVOutputRenderPropertiesList System Events to allow you to return a path to specify where to look for custom TV files\n- Allow separate caching directories for smarty when using different manager themes\n- [#MODX-1951] Ensure smarty cache is cleared on site cache clearing and settings\n- Ensure admin ACLs are set on new installs\n- Added check to modResource::stripAlias to make sure modX object is a modX instance\n- Added basic template and default home resource to new installs\n- Added load-only and load,list and view policies to build, adjusted setup to handle admin/resource policies with different IDs\n- Moved setup's global new/upgrade install scripts to separate files\n- MODExt adjustments; main layout now in central viewport so can handle browser resizing, refactored settings grid editing code, IE/FF/Chrome fixes\n- [#MODX-1970] Add scheme property to Link Tags to allow canonical, https, or any URL generation scheme from modX::makeUrl()\n- Fixed bug where core namespace was not in build\n- Update xPDO to revision 424 for fixes related to PDOException reporting\n- Ensure packages are unpacked after downloading\n- Fixed bug with removing a plugin\n- Added System Setting, 'cache_noncore_lexicon_topics', which can be used to disable caching on noncore lexicon topics, which is useful for 3PC development.\n- Deprecated modPackageBuilder::buildLexicon\n- Completely refactored the Lexicon system to now do file-based Lexicon Entries only. DB entries are only for overrides. This allows for proper overriding of\ncore lexicon entries, caches faster, and allows for much easier 3PC development.\n- [#MODX-1783] Fixed unnecessary scrollbar bug by removing unnecessary margin on body/html tags\n- Slight spacing tweaks to main layout to make layout feel more open\n- [#MODX-1806] Improvements to messages section\n- [#MODX-1913] Fixed incorrect wording on setup complete page\n- Tweaked launching of layout panel to add consistency across browsers\n- [#MODX-1835] Fixed error on Windows platforms when an extension_packages path contains a colon (:)\n- Added ORM editing formpanel object for editing v/p editing pairs, used now on modUser remote data form\n- Added panel for viewing remote data on a user\n- Added 'lexicon' field to modAccessPolicy to enable translations of descriptions of Permissions\n- Added extended field to modUserProfile to handle a majority of basic extended user profile storage/retrieval needs\n- Added 'lexicon' field to Element properties to enable automatic translating of property descriptions and option names\n- Fixed parent/context_key reference issue when creating resource from context tree node\n- Tweaks to index.css for default mgr theme to correct styling issues in webkit browsers due to ExtJS upgrade\n- Fixed deprecated references to removed images in default mgr template css that was causing 404s\n- [#MODX-1911] Allow for drag/drop reorganizing of categories in the Element tree\n- [#MODX-1892] Various fixes to TV-Template relationship grids\n- [#MODX-1895] Added sanity check for windows systems with file names in file browser\n- [#MODX-1908] Corrected logic flaw in modManagerResponse that prevented smarty templatePath from being set for CMPs\n- Optimized loading for System Settings grid\n- Updated ExtJS to 3.2.1\n- Add remote_key and remote_data to modUser\n- [#MODX-1898] Fix static calls to modX::fromJSON() and modX::toJSON() instance methods (xPDO updated to revision 421)\n- Pushed File tree nodes' context menus to JS layer, added Upload Files button to tree toolbar\n- Pushed Element tree nodes' context menus to JS layer, similar to Resource Tree optimizations\n- [#MODX-1897] Fix Date TemplateVar web output render error in PHP 5.3 due to use of ereg()\n- Fixed bug with Quick Update caused by new resource tree js changes\n- [#MODX-1848] Allowed parent selector to select contexts as the parent in Resource page\n- Pushed Resource tree nodes' context menus to the JS layer, massively decreasing the size of the JSON tree sent in the getNodes processor, vast speeding up tree functionality\n- Made publish/unpublish/delete/undelete actions on the tree only change the class of the node, rather than refreshing the node, speeding up workflow\n- Pushed modX::getService to xPDO layer\n- [#MODX-1873] Ensure setup redirects use full URL in header\n- [#MODX-1887] Adjust default widths for main layout to render panels more consistently\n- Optimized modX::getChunk() and modX::runSnippet() by caching instances within a request to modX::$sourceCache\n- Modified modX::setDebug(true) to set error_reporting(-1)\n- Optimized modLexicon::loadCache\n- [#MODX-1824] Fixed bug where duplicate wasnt fully duping resources\n- Moved Resource's duplicate method into the model, via modResource::duplicate\n- [#MODX-1868] tree_root_id now accepts a comma-delimited list of Resource IDs to restrict by. Works across contexts as well.\n- [#MODX-1871] Fixed bug with delimiter TV output render\n- Dropped unnecessary ID field on modEvent table and made `name` column PK\n- Refactored modX::invokeEvent and modX::getEventMap to take advantage of new plugin event changes\n- Adjusted the modPluginEvent model to reference the event name rather than id\n- Added new model-based System Events to work more effectively in any context\n- Removed deprecated system events\n- Added tree_root_id setting that allows you to specify the start parent ID of the left Resource tree\n- Fixed bug where User Settings could not be removed\n- Enabled ability to set absolute path and placeholders for filemanager_path and rb_base_dir\n- [#MODX-1791] modPackageBuilder::createPackage now forces lowercase package name to be more compatible across environments\n- Sanity checks to prevent user from accidentally removing admin/resource access policies\n- [#MODX-1860] Fixed bug where new password was being hidden too fast when changing user password\n- Added proxy support to modRestCurlClient for Package Management\n- Added a couple refactorings to modRestSockClient to prevent possible errors\n- Consolidated user group create system events into one event, OnUserGroupCreate\n- Fixed some various plugin event calls\n- Fixed Plugin Event code to restrict groupname to a UI filter only, not in event caching; adjusted UI grid to support groupname in display\n- Refactored file handling processors to use modFileHandler class with modFile and modDirectory derivative classes to abstract file system processing to abstract for multiple environments\n- [#MODX-1789] Added extra checks in Package Management to make sure that the correct directories are created before using it. Will now prevent usage of PM if those directories do not exist or are not writable.\n- [#MODX-1789] Added code to attempt to create core/components and assets/components after install. If fails, displays a notice to user to manually create them themselves to allow Package Management to work properly.\n- [#MODX-1839] Fixed grammatical error in forgot login link on login page\n- [#MODX-1846] Fixed invalid markup for username in top right\n- [#MODX-1854] Fixed invalid references to cultureKey that broke cultureKey setting effectiveness\n- [#MODX-1785] Fixed invalid password variable reference in invoke notfound event in login processor\n- [#MODX-1784] Fixed invalid event call on user update, as well as added event invoking into updatefromgrid processor\n- [#MODX-1836] Set default context_key in modResource objects to 'web'\n- Fixed bug with system info page and active users that would cause error in error log\n- [#MODX-1788] File tree now respects filemanager_path setting. Also cleaned up file browsing processors.\n- Upgraded ExtJS to version 3.2\n- Updated version to 2.0.0-rc-2 for svn development and issue tracking\n- [#MODX-1778] Fixed error that shows up if E_NOTICE set to true in setup/ index due to servers not posting a HTTPS server global", "MODX Revolution 2.0.0-rc-1 (LastChangedRevision: 6614, LastChangedDate: 2010-03-22 16:41:04 -0500 (Mon, 22 Mar 2010))\n====================================\n- Prepared for rc1 release\n- Fixed CSS compression copying in build.xml\n- Fixed regClient*() functions to work again on cacheable scripts\n- Move element source and include cache files outside of context cache directories since they should be cleared only when elements are updated\n- Remove eval() from modScript and re-enable remote debugging of modScript instances by caching function as include in addition to source cache\n- [#MODX-1759] Ensure manager log fires on top menu deletion\n- [#MODX-1772] Ensure array of IDs is passed to OnBeforeEmptyTrash and OnEmptyTrash plugin events\n- Added a welcome screen to show on first login to manager\n- [#MODX-1738] Fixed issue with default value on radio TVs\n- [#MODX-1741] Fixing inconsistent widths for radio options by making them list vertically rather than horizontally\n- [#MODX-1769] Lexicon grid search now searches name and value\n- [#MODX-877] Updated confusing text on TV access permissions tab\n- [#MODX-1766] Fixed PHP_SAPI issue to properly work by setting a default value on setup to provide a default http_host value to properly populate the site_url\n- Fixed bug in setup that didn't catch processors_path in prior configs\n- [#MODX-1759] Fixed bugs with manager log not storing correct PK values, or displaying missing keys in grid\n- [#MODX-1766] Fixed config.inc.tpl to work with non-httpd SAPI's\n- Added title/info for the Reports->System Info->Database page. This is return fixed the CSS styling issue as well.\n- Fixed CSS Styling on Recent Documents. 5px padding was removed.\n- Fixed bugs with modMail class and default attributes that prevented attributes from persisting after a reset()\n- Removing deprecated RTE handler code\n- [#MODX-1762] Increased file uploader window size for translations\n- Dont render unnecessary tabs in Resource TV panel if no TVs assigned to Template for that Resource\n- Sort Template Variables on the Template editing page by name\n- Ensure Element Properties that have HTML in them show markup instead of rendering the html in editing mode in mgr ui\n- [#MODX-1669] Redid File Uploader in Directory tree to be more cross-browser compatible\n- Cleaned up and enhanced login CSS\n- Standardizing and adding class constants to modRest* classes\n- Updated copyright data in lexicon entries\n- Fixes to build.xml, css compression command\n- Updated copyright dates\n- [#MODX-1750] Lots of procedural and reference fixes to Lexicon grid UI\n- Cleaned up presentation of modAction records in mgr\n- Added a fix to tree refreshParentNode; enhanced modUserGroup::getUsersIn()\n- Added saving mask to Element Property grid to fire when saving the property set\n- Removed deprecated file reference in login template\n- Added System Settings to toggle news/security feeds in welcome panel\n- Added System Setting to toggle on automatic checking of package updates in Package Management\n- [#MODX-1751] Fixed erroneous reference in friendly alias setting description\n- [#MODX-1752] Fixed bug where topmenu items without children didnt show even if they had an action\n- Some css tweaks to login page\n- Updated to xPDO 2.0.0 r419 to fix xPDOVehicle bug\n- Fixed bug with Download Output button in MODx.Console\n- Ensure forgot login activation email is HTML\n- Added Forgot Login link and form to manager, sends an activation email to specified email if user forgot login/password\n- Fixed SQL sorting algorithm for package versions, added helper methods for comparing package versions\n- Added $resource to properties passed to OnDocFormDelete in resource/delete processor\n- Updated to xPDO 2.0.0 r417 ([#XPDO-40] Fixed getCount to work when passing a criteria with a class alias set)\n- Enhanced striptags output filter to take a parameter of allowed tags\n- Make sure $paths and $options are passed to OnCacheUpdate\n- Added compression/concat references to login and browser tpls\n- Fixed build.local.xml and build.xml scripts\n- Added compress_css system setting for compressed CSS for releases, moved over modx-theme.css to templates css/ dir. Don't use compress_css without first running _build/build.local.xml Ant task.\n- Cleaned up leftover PHP4 function definitions, unescaped SQL code, added proper accessor methods for private vars, other old code\n- Fixed bug with modLexiconLanguage::clearCache\n- [#MODX-1738] Fixed issue with FC TV rules not working as expected on Resource Update\n- Fixed bug where plugin event properties were getting merged if more than one plugin was associated with the event\n- Added loading mask to editing panels to prevent accidental editing before data is loaded\n- Added sanity check for OnRichTextBrowserInit event processing\n- Added fix for RTE loading in Resource panel, should fix most RTE saving bugs\n- Added collapsibility to Document panel\n- Added 'concat_js' system setting that will concat all the common JS files into one single file\n- Adjusted lang.js.php to properly use ETag header to cache lang js\n- Added css rule to prevent hidden iframes from being shown\n- Fixed bug where Resource Groups were not editable on Create Resource\n- Added sanity check for packages with missing provider\n- Added \"Updates Available\" column to packages grid, auto-checks provider for updates\n- [#MODX-1732] Added duplicate language ability to language grid\n- [#MODX-1741] Fixed possible bug with radio/cb tv labels\n- [#MODX-1593] Fixed bug where User could not be added with no role in User Groups tree\n- [#MODX-1735] Properly URL encode link tags while still preserving = and &amp; in query string\n- [#MODX-1736] Fixed bug with assigning TVs to Resource Groups\n- [#MODX-1740] Added workaround for SQL code to properly hide TVs with FC rules\n- [#MODX-1738] Fixed bug with radiogroups and set TV default FC rule\n- Fixed some header issues, _FILES content type handling\n- [#MODX-1733] Fixed bug that was stripping tags from connector processing\n- Ensured that Static Resource filename change fires dirty status\n- Made sure Set to Default fires dirty status for Resource panel\n- Fixed possible width stretching bug in TV panel in Resource edit view\n- [#MODX-1543] Added \"Rename Category\" to category nodes in element subnodes in Element Tree\n- [#MODX-933] Can now drag/drop Elements into Categories in the Element Tree to assign them to Categories\n- [#MODX-1729] Fixed incorrect filter name to be more appropriate to function\n- [#MODX-1727] Added missing Empty Cache checkbox to derivative resource panels\n- [#MODX-1724] Fixed bug with output renders in TV panel not triggering panel dirty status\n- [#MODX-1730] Fixed bug with $scriptProperties and login processor\n- Some cleanups to MODExt flow and ID referencing\n- Changed all GPC references in processors to $scriptProperties, which is loaded at entrance points to processors with GPC vars, pushing input handling to the connector\n- [#MODX-1711] Fixed bug with strip output filter\n- Added ellipsis output filter\n- Fixed various event callings across JS implementation to properly modularize modext components\n- Added events to user's groups grid to ensure dirty firing\n- Added MODx.FormPanel::markDirty\n- Added in CSS tweaks to accommodate Opera 10.5\n- Fixed bug with users grid if access permissions tab is removed\n- Fixed deprecated method definitions in modConnector classes\n- Fixed text in language settings to more accurately reflect function\n- Added area filter to Settings grid\n- [#MODX-1721] Disabled unnecessary paging on System Events table\n- [#MODX-1726] Added sanity check to ensure TV input type is properly set\n- Fixed bug with action buttons and continue stay method\n- Added UI for managing website field in modUserProfile\n- Added website field to modUserProfile\n- Removed unnecessary and problematic editor dropdown in chunk editing screen\n- Sped up drag/drop of reordering in tree by now only framing moved nodes instead of refreshing\n- Added modRequest::getParameters() method for retrieving various GPC variables or arrays of variables; automatically strips MODx GET parameters as necessary\n- modRequest::__construct() now creates references to all GPC variables in modRequest::$parameters\n- Modified modX::makeUrl()/modContext::makeUrl() to accept query string parameters as an array or string\n- Added modX::toQueryString() static method to turn associative array into a valid query string\n- [#MODX-1709] Fixed issue with encoding of action button parameter\n- [#MODX-1554] Prevented uploading of files to files themselves in directory tree\n- [#MODX-1700] Fixed issue with text referencing setting in lexicon entry\n- Ensure tags in a Static Resource content are parsed before trying to load the source path\n- Fixed static/weblink update js\n- Removed unnecessary and redundant table prefix check later on in setup\n- Fixed css/js properties in TV tab to let RTEs auto-determine the height of their TD fields\n- Fixed missing permissions reference on resource controllers\n- Added OnHandleRequest to modManagerRequest::handleRequest\n- Properly hides UI elements for Resource buttons/pages if user doesnt have permissions\n- Refactored modResource::cleanAlias() to allow various options, including built-in and custom transliteration capabilities\n- [#MODX-717] Foreign characters (UTF8 data) needlessly removed from alias\n- Hide top menu items if there are no submenus and if the topmenu is not clickable\n- [#MODX-1690] Fixed text for confirmation dialog when removing an Element to include name and type of Element\n- [#MODX-1707] Added mail_charset and mail_encoding system settings to control charset and encoding in emails\n- [#MODX-1706] Ensure that text and qtip fields in Resource/Element trees have any tags stripped\n- [#MODX-1699] Fixed bug in Quick Edit TV where it would erase the caption and replace it with the name\n- [#MODX-1704] Fixed erroneous if statement in clear button hiding in error log panel\n- [#MODX-1675] Added fix for windows paths on Edit File panel\n- [#MODX-1681] Added checks for issue with importing lexicon in Webkit-based browsers\n- Cleanups to TV input widths\n- Removing core RTE; too much work, may take back up in a later version\n- [#MODX-1697] Added ability to edit images and links in RTE\n- Added more robust MODx.rte.Selection API\n- Added missing changes to modActions needed to load lexicon entries for RTE\n- [#MODX-1662] Fixed mismatch in menus widget field label\n- [#MODX-1687] Fixed bugs in template package browser due to changes in modx.view.js\n- Made resource panel be a fileUpload-able panel for plugins\n- [#MODX-1357] Added richtext_default system setting\n- [#MODX-1685] Added MODxEditor, a core Ext-based RTE to be the default RTE for Revolution\n- [#MODX-1674] Stabilized MODx.Browser to work with core RTE\n- - Added missing registry.db.modDbRegister* classes to setup\n- [#MODX-1642] Logging out doesn't unlock resources: added modUser::removeLocks() and modified modUser::endSession() to call this method\n- Added OnInitCulture event to core transport data.\n- [#MODX-1672] Refactor collation/connection processors in setup to be more stable\n- Updated xPDO to r414 for improvements in xPDOManager\n- modInstall::writeConfig() uses new_file_permissions if specified or umask() settings by default\n- Removed superfluous calls to xPDO/modX::setDebug() and xPDO/modX::setLogLevel() in modInstall\n- modInstall::getConnection() now uses utf8_general_ci for charset/collation by default\n- [#MODX-1691] Set Quick Create/Update windows to use anchor property rather than width to adjust for resizing\n- Added 'cultureKey' setting to enable easier language translation in contexts/fe/components\n- Fixes to styling for MODx.Browser window\n- Added 'relativeUrl' parameter to MODx.Browser file data\n- [#MODX-1674] Fixes and stabilization to MODx.Browser, specifically when used by RTEs\n- Changing default editor from TinyMCE to blank value\n- Fixed bug in setup where inplace setting was being forced to 1\n- Cleaned up most processors, fixed wrong permission references, standardized code\n- Fixed welcome panel to only show panels with permission to see\n- Fixed error log view page to restrict viewing and clearing by permission\n- Added descriptive information to Roles grid\n- Lots of permissions fixes, other bugfixes and sanity checks to Element processors/controllers\n- Added propertyset permissions\n- Cleanups to Resource controllers, processors, optimizing of security permission checks\n- Fixed various bugs with search page\n- Fixed bug with adding policies that prevented partial regexp matches in name\n- Fixed bugs when adding new policies or permissions that showed prior added perm/policy in form\n- Properly secured and refactored recently edited resources grid\n- [#MODX-1670] Adjusted permissions to allow restricted user to edit profile\n- [#MODX-1667] Removed unnecessary opacity CSS rule in menus\n- Fixed bug where page wasnt reloading on login in certain situations\n- Make rightlogin div longer to support longer translations\n- [#MODX-1653] Fixed issues with related objects, removal of aggregates, and other packaging bugs. Introduced xPDOTransport::UNINSTALL_OBJECT, which defaults to true. When off, it will prevent an object from being uninstalled.\n- Updated xPDO to r413\n- [#MODX-761] Fixed language issue in setup, now sets it correctly and loads proper lexicon for login screen\n- Ensure console window appears above other windows\n- [#MODX-1663] Added MODx.msg.status, which shows a fading status message on a successful save. This also solves the issue of user feedback.\n- Removed unnecessary field from recently-edited-resource grid on welcome screen\n- [#MODX-1660], [#MODX-1037] Revamped login screen to HTML/CSS, basic form processing to allow browsers to save password in their password management systems\n- Revamped UI in new setup options, cleared up text, simplified presented options\n- [#MODX-18] Allow editing of MODX_CONFIG_KEY in setup welcome view\n- [#MODX-18] Prompt user for MODX_CORE_PATH if not found at beginning of setup\n- [#MODX-760], [#MODX-1080], [#MODX-1528] Added setup option to set new_file_permissions and new_folder_permissions in welcome view\n- [#MODX-760], [#MODX-1528] Removed new_file_permissions and new_folder_permissions system settings from setup\n- [#MODX-760], [#MODX-1528] Updated xPDO 2.0 to revision 407: new file and folder permissions determined from umask()\n- [#MODX-878] Stay buttons now action-specific, done through Ext state rather than PHP\n- Redo logic order of modPackageBuilder::buildLexicon to ensure languages are packaged in before topics\n- [#MODX-1647] Added width specification to force width of screen to prevent scrolling off of RTE TVs\n- Cleaned up tvTitle Form Customization rule by moving code from JS to PHP\n- Fixed z-index issue for windows due to IE fix\n- [#MODX-732] Added z-index force to topmenu for IE, fixed rightlogin div on topbar for IE\n- [#MODX-1641] Optimized and cleaned code dealing with Form Customization TV visibility and default values\n- [#MODX-1658] Fixed bug where placing a menu item in a submenu would place it in top level\n- [#MODX-1624] Enabled changing of text field in menu items\n- [#MODX-1656], [#MODX-1654] Fixed CSS gap in install summary in setup\n- [#MODX-1655] Fixed hardcoded lexicon strings in setup\n- [#MODX-1621] Remove unnecessary context menu items from items in Resource Group Resources tree\n- [#MODX-1627] Fixed incorrect menu in resource group tree resources when newly dragged\n- [#MODX-1599] Added manager_date_format system setting for customizing date formats for the manager\n- [#MODX-1651] Increasing width of setup navbar buttons to accommodate translations\n- [#MODX-1649] Fixed bug where Quick Create didn't respect default_template setting\n- [#MODX-1650] Fixed bug with language specification in setup to properly set cookie for Windows machines, and set initial language properly\n- [#MODX-1626] Fixed bug where top menus could not have actions\n- [#MODX-1494] Fixed issue where some settings dont have descriptions, and cleaned up deprecated settings\n- [#MODX-1645] Fixed incorrect lexicon key for setting_site_start_err\n- [#MODX-1646] Fixed issue where download buttons were staying grayed out if there was an error message\n- [#MODX-1644] Added SMTP mail settings to default system settings to allow global SMTP usage for all modMail functions\n- [#MODX-1606] Fixed bug in modRestCurlClient class due to encoded ampersand\n- [#MODX-197] Refactored Action Buttons JS, added 'actionNew', 'actionContinue', and 'actionClose' events to MODx.FormPanel objects, ensured parent/context_key is persisted through add another resources\n- Added a couple sanity checks to modRestCurlClient\n- Added JS to disable install button when clicked in setup to prevent double-clicks\n- controllers/resources/create: Refactored template inheritance to occur before any delegate controller is called.\n- processors/resources/create: Moved OnBeforeDocFormSave event invocation until after POST vars are applied to $resource object.\n- processors/resources/create: Refactored common code to be executed before any delegate processor is called.\n- processors/resources/create: Refactored to respect add_children and new_document_in_root permissions.\n- Added various access_denied lexicons to the resource topic.\n- Added new_document_in_root permission to control access to creating Resources at the root level.\n- Updated to xPDO 2.0 revision 406.\n- [#MODX-1606] Added sanity checks and ID standardization to DOM nodes for Package Browser\n- Fixed possible bug with ta-toggle div in resource panel\n- [#MODX-1628] Fixed FC tvDefault rule by doing setting php-side\n- [#MODX-1636] Added ability to assign Role to User when adding them to a User Group from the User Groups tree\n- [#MODX-1634] Fixed bug with resource/resourcegroup/getlist processor that prevented showing of resource groups in new resource panels\n- [#MODX-1639] Fixed bug where resource panel JS didnt check for existence of possibly hidden access permissions grid\n- Fixed modUser::removeSessionContext() to call modUser::endSession() if no contexts are left\n- Fixed modUser::endSession() to destroy all SESSION data and the session cookie\n- Fixed bug in Plugin -> System Events tab caused by invalid function call in getlist processor\n- Fixed problems with various deprecated functions to increase compatibility with Evo and avoid performance issues:\n * modX::getDocuments() and modX::getDocument()\n * modX::getAllChildren()\n * modX::getActiveChildren()\n * modX::getDocumentChildren()\n * modX::getDocumentChildrenTVars()\n * modX::getParent()\n * modX::getPageInfo()\n * modX::getUserInfo()\n- Fixed modX::__construct() declaration to indicate it properly as a public method; added phpdoc comments.\n- Fixed modX::sanitize() declaration to indicate it properly as a static method.\n- Updated to xPDO 2.0 revision 405\n- [#MODX-1614] Fixed issue with cached pages going to unauthorized_page instead of error_page when user does not have load permission\n- [#MODX-411] Set system setting: emailsender to the admin email address during install\n- [#MODX-1556] Show class and id for deleted resources or elements in Manager Action Log\n- [#MODX-1552] Create New element Here shows for root elements but not those in categories\n- [#MODX-1625] Fixed bugs with menu tree preventing creating child nodes of new items, restyled menu and action icons\n- Added preventative to make sure packages are only downloaded once when in Package Browser\n- [#MODX-1623] Fixed package installation error: attempting to preserve files fails with error message\n- Updated to xPDO 2.0 revision 404\n- Setup upgrades no longer preserve existing data/files on install\n- Fixed issue with setup trying to write connector files regardless if files are already in place\n- Updated to xPDO 2.0 revision 403\n- Fixed bug where plugin properties were not being injected into the plugin event call\n- [#MODX-1617] Fixed bug with tvDefaultValue Form Customization Rule\n- [#MODX-1619] Added sanity check for modActionDom constraint check\n- [#MODX-1620] Fixed missing or incorrect lexicon entries across ui\n- [#MODX-1612] Fixed bug where Create Menu button was not working\n- [#MODX-1616] Renamed \"field\" to \"name\" in Form Customization rule windows\n- Removed any non-essential JS from the top menu items\n- Added additional check and error logging for processor_path option in modX::executeProcessor().\n- Added missing view_sysinfo permission to default Administrator policy\n- [#MODX-1595] Fixed bug regarding hiding top menu items with permissions\n- [#MODX-1596] Fixed bug related to creating a new top menu item\n- Fixed issues related to usergroup panels and anonymous usergroup editing\n- Fixed bug in template viewer for package browser that wasnt paginating right\n- Added modRestServer for generic REST request handling\n- Enable remote sorting and sorting by ID on Users grid\n- Fixed and enhanced search field on Users grid\n- Fixed bug with duplicating a context where only the first level would duplicate\n- Updated to xPDO 2.0 revision 396\n- Fixed bug where package version info wasnt being computed on download/scanlocal\n- Added check for locked status on resources, now shows locked status in tree, as well as who is editing\n- [#MODX-1592] Fixed bug with usergroup create by moving it to a window\n- [#MODX-1590] Fixed missing processors for ACL grids\n- [#MODX-1526] Added permissions resource_tree, element_tree, file_tree that restrict rendering/viewing of the left-side trees. Must be applied to access policies.\n- [#MODX-625] Adjusted text in config.inc.php writable warning message\n- [#MODX-1586] Fixed toolbar rendering bug in user settings due to hidden div, now using hideMode: offsets\n- Added search for user box in usergroup users grid\n- Changed User Group users grid to a non-local grid, now supports pagination and proper validation\n- Enhanced UI for editing User Group Context/ResourceGroup ACLs\n- [#MODX-1525] Added permissions field to modMenu to define policy permissions required to see Top Menu items\n- Fixed bug in Packages grid to properly show provider name\n- Added modRestResponse class, improved error handling for REST-based package management\n- Added verification for Providers, now check to make sure they can connect before being added or updated\n- Added Package View page to Package Management, allowing you to view more info about a package, view prior installed versions, and remove older package versions\n- Fixed typo in setup script for PM changes\n- Added version_major, version_minor, version_patch, release, and release_index fields to modTransportPackage tables to assist sorting and organization\n- Fixed bug in transport schema\n- [#MODX-1571] Fixed xtype in automatic_alias setting\n- [#MODX-1572] Fixed deprecated error in PHPMailer service\n- [#MODX-1512] Fixed bug with MODx.tree.Tree::refreshNode that caused a strange duplicate node error\n- Updated xPDO to revision 392 to get new nested condition features\n- [#MODX-1515] Fixed date picker CSS\n- [#MODX-923] Added file path to config.inc.php configcheck message on welcome page\n- [#MODX-1579] Added code to prevent invalid characters from being used in admin username/password in setup\n- [#MODX-1575] Fixed bug with Resource Group getList processor\n- Updated to xPDO 2.0 revision 389\n- Added validation to modContext.key field; must be a valid PHP identifier without underscore characters\n- Modified modError::checkValidation() to call modError::addField() for each validation message\n- [#MODX-1562] Cleaned up Site Schedule grid to properly load baseParams during refresh and adjust pagination\n- Cleaned up processor code, plugin invoking, access permission checks in processors\n- [#MODX-1562] Fixed bug in Site Schedule data\n- Fixed OnDocUnpublished and OnDocPublished calls in processors to pass modResource reference\n- [#MODX-1564] Fixed bug causing combo values to get overridden if they were set before the combo store loaded\n- Move element and resource prerender plugin events to after js registering to allow for proper event execution order\n- [#MODX-986] Added \"Duplicate Context\" to Resource tree, as well as \"Remove Context\"\n- Fixed bug with default provider on package management UI\n- [#MODX-1540] Fixed last login display in Welcome page\n- [#MODX-1567] Enabled sorting in Reports -> System Info -> Recently Edited Documents\n- [#MODX-1522] Restricted user editing to just the save_user permission\n- Added a \"reload\" button to the error log\n- Fixed Active Resources on Reports - System Info\n- Fixed database version query in Reports - System Info\n- [#MODX-1560] Added a button to truncate manager log\n- Added new browsing view for Templates in Package Management; thumbnail-based browsing.\n- [#MODX-1534] Revamped file edit page to match other page structures\n- [#MODX-1542] Added missing undelete permission to basic Resource policy\n- [#MODX-1539] Added view_user permission to solve dropdown combo users bug that needed \"edit_user\"; view is more applicable there\n- [#MODX-1553] Show current permissions in chmod window\n- [#MODX-1539] Fixed a few bugs with the manager log page\n- [#MODX-1530] Fixed permission reference in resource create/data\n- [#MODX-1532] Fixed bug in permissions reference when trying to remove element from property set\n- Fixed bug with login page and new controllers location\n- Enhanced provider home page to allow links for newest/most downloaded packages\n- Added sorting to Access Policy grid, cleaned up getList processors across site\n- Fixed Manager Log page to properly display content, log the right class key, and now display the name of the object edited\n- Enhanced Property Sets page to now allow you to edit specific implementations of Property Sets per element, as well as the default set\n- Added \"disabled\" checkbox to Quick Update Plugin\n- Fixed bug in modManagerResponse dealing with CMPs and templating paths\n- Moved controllers/* files to controllers/default/ to allow for custom manager templating\n- Fixed bugs with Property Sets not showing correctly in dropdowns\n- Updated xPDO to revision 385 to fix cache_db functionality broken by PHP 5 only changes\n- [#MODX-1514] Added css for pointer cursor to top menus\n- [#MODX-1513] Added check for SimpleXML to installer\n- Add sanity check to make sure languages arent erased on package uninstall\n- Removed confirm dialog for remove action on Access Permissions grid\n- Fixed panel layout for Access Policies, User Group editing\n- Fixed E_STRICT warning on modX::getCacheManager() [method signature did not match xPDO::getCacheManager()]", "MODX Revolution 2.0.0-beta-5 (LastChangedRevision: 6224, LastChangedDate: 2009-12-15 10:03:36 -0700 (Tue, 15 Dec 2009))\n====================================\n- Fixed bug where Set to Default on Resource TV panel was hidden unless you clicked Reload\n- Fixed some bugs with Property Sets editing\n- Fixed bug where download wasnt working for package management due to missing provider\n- Fixed bug where quick create Static Resource wasnt loading MODx.Browser\n- [#MODX-1496] Fixed issue with scrolling context menus not working on local grids\n- Fixed styling in welcome panel\n- Shrinking top menu a bit to fit in smaller window resolutions\n- Fixed invalid method reference in modInstallTest derivative classes\n- Fixed styling and JS in TV pane\n- Fixed error with charset reference in setup/\n- Clear Search in Package Browser when clicking on a Tag\n- Added Search bar to Package Browser, now can search entire repository\n- Fixed height of Package Browser to not go too far down screen\n- Fixed modRestSockClient to properly strip HTTP headers and return only XML\n- Added modStaticResource methods: getSourceFile() and getSourceFileSize()\n- Fixed bug in setup/ script with new transport package fields\n- Fixed modCacheManager to not cache reg* calls that will cause breakage on similar calls to reg* method\n- Added 'package_name' and 'metadata' fields to modTransportPackage for future development\n- Fixed styling commits; also fixed bug on Package Management when not selecting default provider\n- Added help buttons to Resource pages\n- Moved TV categories in Resource edit page to tabpanel, also cleaned up button styling\n- Fixed table styling. This is temporary until all tables are ported to ext grids. This affects welcome pane, system info, and online users.\n- Fixed bug where package browser would close on ESC key\n- [#MODX-1489] Allow spaces in Category names\n- [#MODX-1497] Fixed username not being sent in new user email\n- Fixed NOT NULL error in modManagerLog\n- Revamped Package Management UI, changed Provider hooks to REST-based, massively improved downloading UI\n- Fixed styling on the search page.\n- Fixed styling on the actions page.\n- Fixed styling on the manager logs page.\n- Fixed triggerfields in windows in Safari\n- Changed the text-size and and top margin of the Main Navbar Submenu span for more readability.\n- [#MODX-1426] Added connect check to assist with mysql_get_server_info in setup\n- Few style changes: Changed Button style text color to black - Previously it appeared that buttons were disabled. Changed Text color inside of combo boxes to black - As before it looked like the element was disabled.\n- Modified the date fields to show a drop-down box rather than the date image. Changed the text-size and spacing of the Main Navbar to 12px.\n- Fixed styling of the welcome panels.\n- Fixed some issues with OnDocFormSave, plus standardized how to render fields/html to update forms\n- Fixed bug with default values, @ bindings and other things on checkbox/radio TVs\n- Prevent tree from expanding too much on quick create, cleaned up js\n- Assigned user id/username to [[+modx.user.id]] and [[+modx.user.username]] for easier access\n- Cleaned up last PHP4 remnants to PHP5-only\n- [#MODX-1483] Fixed bug with TV saving in resource create processors\n- Recompiled MODx.Console to use Ext.Direct, now should be a bit more stable. To end a MODx.Console session, pass 'COMPLETED' to the registry.\n- Resizing the left tree now properly resizes content in the right panel and is stateful\n- Added resizability to leftbar tree\n- Removed no-longer-necessary js file references in resource controllers\n- Consolidated filetree css/js into main css/js files\n- Fixed logic error that caused removing setup directory to fail\n- Combined some common JS files, cleaned up login page css, other optimizations\n- Consolidated filetree extension CSS, removed unnecessary filetree files\n- Consolidated CSS files in templates/default/css to one single file to reduce load times from @imports\n- Added rowactions to package grid\n- Improved code in @DIRECTORY binding to be more efficient and take advantage of DirectoryIterator\n- [#MODX-1478] Fixed @SELECT binding\n- [#MODX-1474] Fixed bug with multiple list-boxes\n- [#MODX-1476] Fixed bug with TV default values with non-inherit tvs, also bug with radios/checkboxes and set to default\n- [#MODX-1479] Fixed bug with duplicate DOM ids in User Group tree\n- [#MODX-1480] Fixed bug with wrong permission reference in property set remove processor\n- Added emptyText to local and property grids\n- [#MODX-1477] Added emptyText config param with default 'No data to display' message to empty MODx grids\n- documentObject was not getting set from cached Resources.\n- Added inline help that loads official MODx documentation in a window\n- [#MODX-900] Fixed erroneous text on site_status setting description\n- Added (Inherited Value) flag to TVs that are inheriting their value\n- Added category titles to TV editing panel\n- [#MODX-1354], [#MODX-1475] Fixed @INHERIT and other bindings in TV inputs\n- Fixed bugs with dirty status not firing for certain TV input types\n- Fixed CSS for login page\n- Fixed issue where default connection charset was not persisting in setup for upgrades\n- CSS tweak to get windows working properly\n- Major styling updates (thanks lossendae!)\n- [#MODX-1473] Fixed bug with modUser and modUserProfile PK's getting mixed, causing errors if PKs for each object were different\n- Added city field to user UI\n- Optimizations to Resource panel\n- [#MODX-1466] Made \"back\" from Access Policy edit redirect to Access Controls page, made Access Controls tabs stateful\n- [#MODX-1471] Added scrollOffset: 0 to grids to hide empty space on right side\n- [#MODX-1469] Fixed dir handling in setup\n- [#MODX-1388] Updated documentation for modX.getTree and modX.getChildIds\n- [#MODX-1318] Prevent ordering of elements in dragdrop since order defaults to alphanumeric\n- Made charset in setup/ a dropdown of available charsets\n- Fixed collation grabbing for setup/\n- [#MODX-1090] Added 'Rename File' window to directory tree\n- Vast improvements to setup, including removing of mootools, using ExtCore now, simplified UI workflow to remove unnecessary AJAX calls, added in database creation checking, collation specification, etc\n- Fixed bug with modPackageBuilder that would ignore the specified path for a Namespace\n- [#MODX-1207] Changed modSession.id column to varchar(40) to support session.hash_function=1 with session.hash_bytes_per_char=4.\n- Simplified and optimized session handling, removing older PHP workarounds and adjusting preset system settings.\n- Make sure non-static Resources with binary content types get processed and output.\n- [#MODX-1450] Added paging to Template combobox to allow for large numbers of templates\n- [#MODX-1443] Tree sorting now works for modMenus\n- Removed deprecated system settings from build\n- [#MODX-1448] Fixed issue with container checkbox not persisting\n- [#MODX-1426] Fixed issue with MySQL checks on non-standard\n- [#MODX-1437] Fixed duplicate policy\n- Fixed some issues with Form Customization\n- Added 'address' field to modUserProfile\n- Added ability to edit the (anonymous) user group from the user group editing panels\n- Fixed typo in usergroup get processor\n- [#MODX-1018] Fixed bug with having to click the Clear Filter button in a settings grid twice\n- [#MODX-1380] Fixed bug with expanding node when quick creating a resource in it\n- [#MODX-1326] Fixed the access denied logout form, added styling\n- [#MODX-1423] Fixed error with duplicating a template\n- [#MODX-1409], [#MODX-919] Fixed issue where tag symbols were being stripped in Elements and breaking filtering and nested tag functionality\n- [#MODX-1347] Fixed user validation for username missing error\n- Extrapolated RTE logic to make it generic\n- Added OnRichTextBrowserInit to allow for 3rd Party RTEs to hook into MODx.Browser\n- Added system setting \"allow_multiple_users_per_email\" to allow users to have a single email shared across users. Defaults to true.\n- [#MODX-972] Fixed bug when property description was changed, grid wasnt updating\n- [#MODX-1390] Fixed docs for $modx->sendUnauthorizedPage();\n- [#MODX-895] Fixed possible rendering issue with error log scroll bar\n- Optimized setup pre-install checks, now checks both mysql client and server versions\n- [#MODX-1404] Fixed mysql version checks to only show a warning if the client/server is incorrectly setup to where PHP cannot determine the versions.\n- Package Management now restricts downloading/updating Extras to their supported MODx versions (ie, you can't download packages that support only beta-3 if you have beta-4 or beta-2)\n- [#MODX-1310] Fixed expand/collapse toolbar items in trees\n- [#MODX-1361] Make sure cache (including Smarty files) is cleared after install\n- [#MODX-1372],[#MODX-1376] Marked deprecated functions as so in phpdoc comments\n- [#MODX-1378] Fixed bug with adding a None role to a user group in the User -> Access Permissions tab\n- [#MODX-1375] Fixed documentation for modX.getRequest\n- [#MODX-1374] Fixed documentation for modX.getRegisteredClientScripts\n- [#MODX-1370] Fixed quick create to set modResource type to modDocument properly\n- [#MODX-1373] getLoginUserName and getLoginUserId now return boolean false if no user is logged in\n- [#MODX-1369] Fixed validation errors and possible loophole in error processing for user processor flow\n- Fixed column alignment with radio/checkbox TV inputs\n- [#MODX-1350] Fixed issue where reset to default wasnt working with radio TV inputs\n- [#MODX-1360] Fixed issue where publishedon was being reset in quick update\n- Sanity fixes to misc processors\n- Added access modifiers to methods in modElement\n- Moved name character sanity checks for Elements to element class.\n- Cleaned up element processors, added missing permission checks, filled out plugin event calls\n- [#MODX-1355] Fixed erroneous label for quick create resource on Contexts\n- [#MODX-1352] Remove stay-buttons from user update screen\n- [#MODX-1349] onDirty now fires on triggerfield-based TVs\n- Cleanups to getList processors, bugfixes for grids\n- [#MODX-1317] Fixed erroneous label for quick create resource; should be Document\n- [#MODX-1316] Added menu title to quick create/update resource\n- Fixed issues with User grid\n- [#MODX-1325] Fixed console's download to file functionality\n- [#MODX-1327], [#MODX-1340] Fixed issue with generation of new password\n- Fixed locking\n- Lots of PHP5-only optimizations", "MODX Revolution 2.0.0-beta-4 (LastChangedRevision: 5880, LastChangedDate: 2009-10-19 09:04:47 -0500 (Mon, 19 Oct 2009))\n====================================\n- If memory limit is lower than 24M, force to 128M if possible\n- Fixing setup text for memory limit checks.\n- [#MODX-1080] Make sure traditional distribution doesnt need base directory writability\n- Added modInstallTestSvn class for handling SVN-specific setup tests\n- Fix to setup contexts controller to read existing paths on upgrade.\n- setup/ memory_limit checks now only need to be 24M for setup/ to run.\n- Updated to xPDO 1.0 revision 363 to fix \"Error saving changes to parent object fk field action\" messages being logged during install.\n- Fixed issues with category remove dialog and lexicon topic grid\n- [#MODX-1294] Fixed possible obscure problem when using Preview after changing the alias in a Resource\n- [#MODX-1278] Fixed issues with checkbox TVs and default values, fixed the 'set to default' button for complex inputs\n- [#MODX-1280] Fixed issues with the user create processor\n- Added OnBeforeUserActivate, OnUserActivate events\n- Added 'active' boolean field to modUser. Defaults to 1.\n- Added OnCreateUser, OnDeleteUser, OnUpdateUser events\n- [#MODX-1170] Fixed issues with Export Topic\n- [#MODX-912] Fixed isinrole/ismember output filter\n- [#MODX-677] Made capitalization consistent on Resource edit/create screen\n- [#MODX-1251] Fixed issue with server offset displaying incorrectly\n- [#MODX-896] Fixed issue with server_offset setting description\n- [#MODX-928] Fixed issue where parent resource wasnt refreshing properly\n- [#MODX-777] Made consistent the checkDirty behaviour of save buttons across manager\n- [#MODX-938] Added check to build to check if core+core.transport.zip were removed before build starts.\n- [#MODX-629] Added missing automatic_alias setting to build\n- [#MODX-790] Fixed issue where couldnt browse back to root directory with MODx.Browser\n- [#MODX-902] Fixed empty warning message for removing category\n- Fixed bug with removing categories\n- Fixed issue where couldn't drag a resource onto a resource with no children\n- [#MODX-1130] Fixed issue with parent triggerfield; also redid how tree hrefs load so that clicking on a node in the tree to load url can be disabled\n- [#MODX-1133] Fixed issues with hotkey behavior\n- [#MODX-1230] Fixed issue where drag Resource to symlink/weblink content field would add tags as well\n- [#MODX-1273] Added OnLoadWebPageCache event invocation to modRequest->getResource().\n- [#MODX-1273] Fixed events in User update/create form\n- Enabled compression of manager JS scripts by changing the Setting \"compress_js\" to true.\n- Upgraded ExtJS to ExtJS 3.0.2\n- [#MODX-1270] OnManagerCreateGroup and OnWebCreateGroup events now fire\n- [#MODX-1237] Fixed warning in modParser with regards to uninitialized variable\n- [#MODX-979] Added password_generated_length (the length of the auto-generated password) and password_min_length (the minimum length for a password)\n- Cleaned up usergroup processors\n- Added sanity checks to usergroup processors\n- Prevent possible issue on usergroup update that would wipe related objects\n- Prevent possible issue that would allow user to remove Administrator group\n- Removed some legacy todo statements\n- Moved Element category reset on modCategory object remove to modCategory class\n- Cleaned up modResourceGroup, modTemplate helper methods\n- Added modUser::joinGroup(group,(optional)role) and modUser::leaveGroup(group) for easier development\n- Optimized getrecentlyeditedresources processor\n- Make sure config.js.php outputs proper headers\n- Commented out Content-Length headers on lang.js.php, for some reason was slowing down servers\n- [#MODX-1256] Fixed issue with Resource tree not being visible in Resource Groups page\n- Fixed issues with Import HTML/Resources pages; properly convert to MODExt\n- [#MODX-1202] Fixed issue where Element name was missing in Duplicate window\n- [#MODX-1233] Fixed bug where categories could only be renamed once before needing to reload page\n- [#MODX-1248] Fix bug that could wipe TV values if tab wasnt loaded\n- [#MODX-1241] Fixed Preview button on update panels\n- Prettying up of TV fields\n- Now display SVN revision number with version in top left of mgr header\n- Fixed issues with TVs setting values incorrectly\n- Added \"Set to Default\" button on TVs that will reset the TV's value to it's default value. TV Resource values can now be set to blank as a valid value.\n- [#MODX-924] Fixed errors in various system setting descriptions\n- [#MODX-935] Tooltips in Resource tree now do not show if no description or longtitle is set\n- [#MODX-1120] Now shows TV names in tag form below the caption in the TV editing panel in Resource editing\n- Fixes to plugin event calls in controllers\n- Fixes to filetree to enable in Ext3\n- [#MODX-1112] Fixed issue where checkboxes in grids werent firing dirty statuses\n- [#MODX-1229] Fixed issue where default hidemenu setting in Create Static Resource was setting incorrectly to true\n- Added some extra variables for RTE firing; also made sure MODx.loadRTE fires on new resource creation. Fixes [#TINYMCE-9], [#TINYMCE-8]\n- [#MODX-523] Fixed copy issue in console by providing \"Download to File\" link\n- [#MODX-649] Fixed issue where comboboxes were not loading proper displayValue when first rendered\n- Added category combobox to quick update/create windows\n- [#MODX-1019] Added missing site_unavailable_page System Setting.\n- [#MODX-1226] Removed modResource->checkChildren() method; isfolder should not be set based on presence/absence of children.\n- [#MODX-1213] Fixed issues with WebLink creation and loading\n- [#MODX-1178] Fixed issue where checkbox TVs were unable to be set to false; properly rendered values into a hidden field\n- [#MODX-1204] Implemented $matchAll for modUser::isMember, that allows exclusive and inclusive group membership checks\n- [#MODX-1203] Now preserves state of open tabs in left bar\n- Added \"Form Customization\" page, which emulates Evolution ManagerManager functionality and integrates it into the core\n- Revamped modMenu DB structure to allow for more proper dynamic menus; 3PCs will need to now refer to the Components menu as 'components', as the \"id\" field has been dropped and \"text\" is now the PK\n- Fixed DOM issue with Profile page\n- Improved core transport build script, lowered build times\n- Fixed issue where hiding the alias field would cause it to be erased\n- [#MODX-1169] Fixed issue where unchecking Container on a Resource that had children would hide them from the tree\n- [#MODX-1125] Fixed issue where Properties were being lost on new Elements\n- Fixed some dirty field problems in Element/Resource forms\n- [#MODX-1167] Improved isFolder checkbox tooltip\n- [#MODX-929] Changed default click functionality in Tree menu to edit Resources, unless does not have permission to, will then go to View\n- Fixed navbar structure on main menu to properly handle infinitely deep nested menus. Needs help from a CSS guru on the CSS end.\n- [#MODX-1161] Fixed bug with height argument on modX::getParentIds\n- Documentation updates to modResource class\n- [#MODX-1189] Fixed issue with TV values not setting properly with modTemplateVar->setValue\n- Added modResource->getTVValue, which gets the value of a specified TV for the Resource\n- [#MODX-1177] Adjusted Lexicon Management text to properly represent functionality\n- Added more metadata to Lexicon Topic exports\n- [#MODX-1191] Fixed issue where Namespace combo was conflicting with other DOM IDs in Lexicon Management\n- Changed Accordion to Tabs in left menu\n- In all Resource panels, Moved Page Settings back to right side, moved Template to top, moved Published to top right\n- [#MODX-1173] Added modResource->hasChildren() function. Returns # of children for the Resource.\n- [#MODX-689] Fixed error when using @SELECT binding with Template Variable Input Option values.\n- Fixed issues with modMenu creation/editing\n- [#MODX-1132] Various fixes to the user editing page\n- [#MODX-1123] Fixed bug where properties were not saving on new elements\n- [#MODX-683] Changed title for 1st tab on Resource edit screen\n- [#MODX-1118] Tweaked MODx.combo.ComboBox and other store references to possibly fix local store bug\n- Fixed issue with Sort By dropdown in the Resource Tree\n- Fixed issues with User Group update page\n- Added modAccessPermission class to properly handle access policy permissions\n- Adjusted UI to handle model change\n- Added logic in setup install to clear sessions table after install to prevent access permission changing problems (and is a good general practice anyway); users will have to re-login after setup/ is run.\n- Cleaned up access policy grid\n- Default sort roles by authority\n- Removed no-longer needed Security pages; now done in Access Control and User Group edit screens\n- Started cleanup of Security system; changed 'Authority' listing on User Group page to a more correct \"Minimum Role\".\n- Added some IDs to resource edit page\n- [#MODX-1124] Took Templates off the list of attachable elements in Tools | Property Sets", "MODX Revolution 2.0.0-beta-3 (LastChangedRevision: 5593, LastChangedDate: 2009-07-30 11:14:17 -0500 (Thu, 30 Jul 2009))\n====================================\n- Fixed issue with scrollbars and height in tree context menus\n- [#MODX-963] Fixed issue with scrollbars and height in grid context menus\n- Fixed possible error in lang.js.php\n- [#MODX-982] Added param stringLiterals to directory/getList processor\n- [#MODX-978] Updated PHPMailer to 2.0.4\n- [#MODX-960] Fixed DOM issue with User Group creation/editing screen\n- Added ability to drag/drop files in file tree into fields\n- Fixed issue with file tree hiding files\n- [#MODX-960] Fixed erroneous header in Manage User Groups and Roles\n- [#MODX-965] Removed Disabled field from Package grid since it currently is unapplicable\n- [#MODX-964] Fixed issue with toolbar buttons in package download tree by removing unneeded buttons, fixing refresh button\n- [#MODX-966] Changed Package Management grid to be easier to read, removed unnecessary information\n- [#MODX-962] Fixed issues with User panel screen\n- Replace deprecated split() call in magpierss class with explode().", "MODX Revolution 2.0.0-beta-2 (LastChangedRevision: 5416, LastChangedDate: 2009-07-16 13:15:41 -0600 (Thu, 16 Jul 2009))\n====================================\n- [#MODX-1029] Fixed incorrect URL references in browser controller template\n- Updated version info for beta2 release\n- [#MODX-942] Made sure all get-based processors use REQUEST, not POST\n- [#MODX-937] Added 'Download Extras' button to package grid which loads modxcms.com provider\n- login processor does not return site_url in response by default.\n- modResponse->outputContent() allows programmatic options to configure max_parser_iterations.\n- Updated xPDO to revision 341: package uninstall preserves and restores file resolver data\n- Changed key shortcuts to always require ctrl+shift to prevent browser collisions\n- Added in field for description key in modMenu windows\n- [#MODX-931] Added isequal, isequalto, and notequalto as modifier aliases to default Output Filter\n- Fixed issues with pagination on settings grids\n- Fixed ENTER key issues on quick create/update windows\n- Added &language option to lexicon tags.\n- Added ability to load lexicon topics via tag: [[%key? &namespace=`mynamespace` &topic=`mytopic`]]\n- [#MODX-910] Fixed issues with gte/lte/gt/lt output filters\n- [#MODX-921] Added \"isempty\" as an alias of \"ifempty\" in output filters\n- [#MODX-920] Fixed wordwrap output filter\n- [#MODX-914] Added isnotempty and hide output filters\n- [#MODX-913] Added isloggedin and isnotloggedin to output filters\n- Upgraded ExtJS from 2.2 to 3.0\n- [#MODX-925] Fixed issue where name couldnt be changed on duplicate resource window with resources with children\n- [#MODX-911] Fixed dragability issue when assigning resources to resource groups\n- [#MODX-901] System Settings grid search now searches descriptions\n- Added 'afterLayout', 'loadKeyMap', and 'loadAccordion' events to MODx.Layout\n- Fixed bugs with File TV input renders\n- [#MODX-887] Properly standardized POST/REQUEST access methods for element processors\n- Fixed issues with user emails being sent in plaintext with no linebreaks; now HTML-based for the time being\n- Package Download tree now disables already downloaded packages.\n- [#MODX-885] Fixed missing break statement in cat output filter\n- [#MODX-844] Fixed ucfirst output filter, added ucwords output filter\n- [#MODX-869] Added missing descriptions for certain menu items\n- [#MODX-868] Fixed bug on settings grid where filter box was not firing on enter key\n- Fixed bug where hidemenu was not persisting in Quick Update Resource\n- Fixed bug with tree mask rendering before panel is rendered\n- [#MODX-747] Fixed issues with access grids update windows\n- [#MODX-803] Fixed DOM issues with TV mgr input property renders\n- [#MODX-805] Fixed attribute issues with TV web output renders\n- [#MODX-859] Changed login page loader box to say 'Loading...' instead of 'Saving...'\n- [#MODX-860] Fixed z-index issues across manager\n- Added a custom loadMask to MODx.tree.Tree objects to display when they're loading but not affect page focus\n- Added a custom loadMask to the Package Management download tree to display while loading the remote provider payload\n- Added in icon for package files\n- Added fsockopen as a fallback for transport package if allow_url_fopen or cURL is not enabled\n- [#MODX-856] Added cURL method of grabbing transport packages when allow_url_fopen is set to false\n- Fixed bug in property update where list grid was not hiding if list xtype was previously selected but not now\n- Fixed import properties where it was not properly handling descriptions\n- Fixed bug where ExtJS couldnt handle text/json header responses with fileUpload set to true in form panels\n- Fixed some DOM issues with Package Management\n- [#MODX-833] Temporary fix for modManagerLog message showing up in console\n- [#MODX-853] Changed source caption of view resource data\n- [#MODX-809] Adjusted formatting of View Resource data fields\n- Fixed bugs with Resource data page not loading fully, glitching tree\n- [#MODX-772] Fixed bug where plugin events were not showing enabled if filtered by name\n- Fixed user system event calls to pass proper arguments\n- Fixed bug where you could only load 1 Quick window at a time\n- Fixed bug with duplicate resource\n- [#MODX-845] If no setup options are specified, package installation will automatically proceed\n- Added parameter to the getNodes processor for resources/elements called 'stringLiterals' which, when true, does not encode the JS literals\n- Layout can now be toggled between tabs (default) and portal panels via the setting 'manager_use_tabs'\n- Nuked the Loading Box in MODExt\n- Changed clearCache key shortcut to CTRL+U (CTRL+SHIFT+U for PC users)\n- Fixed issue where folder resources couldnt be drag/dropped\n- Added some key-events: CTRL+H for hiding accordion, CTRL+U for clearing cache, CTRL+N for Quick Create Resource (PC users will need to add SHIFT to all those calls)\n- Fixed portal issues with Safari\n- Added a few events to MODx. JS object, cleaned up code\n- Added sanity checks to context/category create/update processors\n- [#MODX-766] Added check to prevent settings starting with numbers\n- Added ability to update plugin events and dynamically manage plugins associated with them by right-clicking on them in the Plugin Event grid\n- Added 'beforeSubmit' listener to MODx.Window\n- Adjusted TreeDrop code to allow for RTEs to utilize drag/drop features\n- [#MODX-827] Fixed typo in resource container help string\n- Added prevention fix to prevent dragging of non-elements/resources into content panes\n- [#MODX-770] Fixed bug with creating Symlink\n- Fixed issues with creating and editing a static resource\n- Fixed bug with treedrop that set boolean values to string representations; changed to 1/0\n- Fixed missing context menu item to remove new properties in a property set\n- Added functionality for Element Tag Builder to use descriptions of properties\n- [#MODX-817] Redid Clear Cache window to use MODx.Console\n- Lexiconized missing \"Copy to Clipboard\" string\n- Slight tweaks to MODx.Console to get messages to display final ending messages properly\n- Changed invokeEvent missing event warning to debug msg to prevent it from logging in every console output\n- [#MODX-818] Fixed issues with Quick Create where it didnt work in FF, missing lexicon strings\n- Added Visual Element tag builder when you drag/drop an element into a field\n- Resources/Elements can now be dragged from tree straight to Resource Content pane.\n- Removed Spotlight effect on dialogs; was unnecessary.\n- Fixed bug in Namespace creation window that was preventing namespace from creating\n- Added refreshes to comboboxes in Lexicon Management to refresh combos on Namespace/Topic creation to keep panels up-to-date\n- Fixed Safari issue with Element tree displaying funky on certain pages\n- Fixed issue in Safari where combobox trigger was on left side\n- Only set lexicon entries for context/user settings if they dont exist as system settings\n- Fixed issue with Actions panel causing accordion DOM to bug\n- Fixed issue with Quick Update not persisting class_key\n- Fixed some issues with persistent settings for Quick Update Resource\n- Fixed issue with Quick Update Resource content field being too long\n- Fixed invalid lexicon entry reference for quick create resource\n- Added Quick Create/Update Resource\n- Preview context menu option now is \"smart\" and builds FURLs and separate context references\n- Fixed invalid topic reference issue with modLexiconEntry::clearCache()\n- Fixed headers for connector responses\n- Added Quick Create/Update for all Element types\n- Fixed bugs with category setting in Element processors\n- Added Clear Cache checkbox option to all Element type forms\n- Fixed bug with Category dropdown\n- Fixed tv input properties forms from double-rendering\n- [#MODX-804] TV fields now fire resource change event\n- Fixed bug in Safari with TV fields being uneditable if panel is dragged\n- [#MODX-745] Added 'cancel' button to go back to policy page when updating a policy\n- [#MODX-573] Removed no-longer-applicable 'role' column from users grid, fixed capitalization issues in processors\n- [#MODX-762] Added in missing lexicon entries to hardcoded strings\n- Added modx.localization.js for i18n translations\n- Added indexes on modLexiconEntry table\n- Properly formatted lexicon strings still using sprintf\n- Fixed bug where created was not set on transport package creation\n- Made sure package grid paginates correctly if number of packages installed exceeds 20\n- Fixed Last Modified On on Lexicon grid\n- Optimized action, menu, language, content-type, lexicon, namespace processors\n- [#MODX-765] Added fix to prevent creation of blank system settings\n- Fixed bug in Safari with TV widget properties rendering\n- Consolidated resource getNodes processor, added access policy checks\n- Added sanity check to toJSON function in modConnectorResponse\n- Properly refactor element tree to point to correct processor\n- Added delegate processors for different modes in element tree\n- Updated Context policy attributes for missing attributes\n- Fixed invalid category reference on chunk update processor\n- Added log error messages if save()/remove() fails on modElement derivatives\n- [#MODX-771] Fixed invalid lexicon string reference in element tree\n- Added WARN log message when executing a system event that doesn't exist\n- Filled out missing access policy checks in element processors\n- Fixed incorrect and missing permission check in snippet get/getList processors\n- Fixed invalid lexicon reference in template processors\n- Optimized templateTV getList processor to use only one query\n- Optimized plugin event getList processor to use only one query\n- [#MODX-194] Added sanity checks to element names\n- [#MODX-792] Added check to prevent user from creating blank context, other sanity checks\n- [#MODX-475] Prevented adding contexts with _ in name; will auto-strip\n- [#MODX-796] Fixed check for valid passwords in setup\n- Fixed problematic reference to $_lang\n- Fixed improper log message reference in lexicon's reloadFromBase processor\n- Additional access control defects and warning messages resolved for anonymous users.\n- Fixed access control defect which prevented multiple policies from being respected per principal.\n- Fixed issue with Policy Attributes not adding b/c id was not passed in\n- Added 'save' event fire to Element/Resource formpanels\n- Properly setup on*FormRender events for Element classes\n- Added MODx.onSaveEditor check, which will fire on form save, that allows 3rd Party Components to execute JS code on Element/Resource saves\n- Major refactoring to modx.actionbuttons, to render faster, as well as properly register events and button configs\n- Allowed OnRichTextEditorRegister to return a string as well as an array\n- Added MODx.releaseLock(id), which releases the lock on a Resource for a given ID\n- Added MODx.sleep(ms), which sleeps the UI for a given number of milliseconds (useful in async calls)", "MODX Revolution 2.0.0-beta-1 (LastChangedRevision: 5070 , LastChangedDate: 2009-05-28 16:20:08 -0500 (Thu, 28 May 2009))\n====================================\n- Fixed issue with cacheable toggle on derivative Resource pages\n- Fix error message when reading expired messages in modDBRegister.\n- Fixed issue with login page JS\n- Fixed issue with derivative Resource classes JS not loading Page Settings data into submit\n- Fixed issue with utilities JS not loading at right time\n- Updated build.xml to produce beta releases.\n- Quick fix to prevent blank attribute referencing\n- Fixed issue with package attributes and skipping blank options\n- [#MODX-723] Fixed issue where preview pane was picking up CSS from preview\n- Updated xPDO to revision 333.\n- Fix issues with Page settings defaulting to 1 on resource creation\n- Adjusted order of JS utils loading to make for easier min-concat loading\n- Cleanups to JS to prepare for beta-1\n- Lexicon updates\n- Updating outdated copyright notices in source code headers.\n- Fixed hardcoded version number in setup.\n- Added request_controller system setting to indicate the front-controller file (default=index.php).\n- Fixed array_merge warnings in modLexicon.\n- Added back support for anonymous user access control.\n- Added support for returnUrl parameter to be sent to login processor to allow unauthorized responses to return to the original requested page directly (NOTE: this overrides manager_login_startup and login_startup parameters, but does not work with POST requests: these will simply return to the URL with only GET parameters).\n- Export lexicon now prompts for download of exported file\n- Enhanced User Group update/create screen to now have grids that allow you to assign Resource Group / Context permissions to that user group. This will help clear up confusion with the access relationships.\n- Fixed scope issue in accordion.css that was causing odd behaviours with panels in the main content\n- Adjusted setup procedures to allow for more lexicon support for pre-load checks\n- Adjusted setup lexicon to allow for multiple topics; conformed upgrade scripts and other references to match\n- Consolidated similar code in setup, esp. with regards to fatal errors\n- Added smarter checks for xPDO failures in connectors\n- [#MODX-744] Fixed issue with invalid display of num cleared on cache claering\n- Fixed bugs with updating packages from a remote provider\n- Made sure package attr returns '' if false\n- Fixed manager log to show username, not user ID\n- Standardized derivative resource form panels to move page settings to left\n- Tweaked tree menu headers\n- Minor IE overrides for top navigation and accordion panel.\n- Added support for modLinkTag properties as url parameters, with context reserved to indicate a context to send to makeUrl().\n- Fixed error in modLinkTag when passed invalid data.\n- Added '@RESOURCE' binding alias so as to deprecate @DOCUMENT binding\n- Fixed default language setting for modLexicon\n- Fixed a couple issues with the page settings checkboxes for resources\n- Removed deprecated _tx_.gif\n- Removed home icon and replaced with tab\n- Adjusted CSS to align main content page vertically\n- Trees now have fun new icons representing their types (this includes the resource, element and file trees)\n- Cleaned up the default.inc.php lexicon topic to remove any no-longer-used entries\n- Fixing typo in subtract output modifier\n- Fixed improper reference in TV property renders for mgr context\n- Updated xPDO to revision 329.\n- Improvements to sendError() behavior.\n- Added lock stealing processor and updated remove_locks processor.\n- Added steal_lock:true policy attribute to default Resource policy to allow lock stealing permissions by ResourceGroup.\n- modTemplateVar: Fix getValue() on `value` field by storing and verifying the value requested is cached by the same resource.\n- modResource: Add resourceId value to getMany() on modTemplateVar to identify the resource caching a value on the modTemplateVar instance.\n- modX: Set logTarget based on XPDO_CLI_MODE; ECHO for CLI and HTML for non-CLI requests.\n- modX: Add sendError() function to provide customizable, named error pages on FATAL or other critical error situations.\n- modX: Refactored sendForward(), sendErrorPage(), sendUnauthorizedPage() functions to allow an array of options and better handle FATAL errors.\n- modCacheManager now Caches related modContentType data to prevent unnecessary database connection/query on fully cached pages.\n- Fixed problem with modStaticResource truncating the content to the size of the static file by setting the content length header on non-binary content types.\n- Fixed problem with modStaticResource non-binary content types rendering the path to the static file rather than the actual content of the file.\n- Calling modX->log(MODX_LOG_LEVEL_FATAL) or modX->messageQuit() now logs the error to file and then renders {MODX_CORE_PATH}errors/fatal.include.php.\n- Updated to r325 in xPDO: xPDO method changes to getOption() and _log().\n- Update 'setup-options' ability in transport packages to allow for script-based setup options that will properly handle upgrades to setup options default values\n- Updated to r323 in xPDO: Revise xPDOTransport::writeManifest to make 'setup-options' be able to be an executable script to allow for dynamic form ability\n- Updated snoopy class to version 1.2.4 (used by magpierss).\n- [#MODX-535] Removed automatic setting of isfolder based on presence or absence of children.\n- [#MODX-499] Site start Resources now return base_url from modContext->makeUrl() if no scheme is specified (i.e. when expecting relative links).\n- Improved error reporting on modX->makeUrl() to show original $id value being passed in on failures.\n- modLinkTag no longer returns empty values on first pass of parser, allowing delays until the value returns a valid value.\n- Implemented modResource editor locking (added modResource methods: getLock(), addLock($user), removeLock($user)).\n- Implemented modResource locking features in all appropriate processors.\n- modResource->checkChildren() now uses modX->getCount() to determine if children exist.\n- Added steal_locks attribute to Context access policy.\n- [#MODX-728] Made sure config check dialog is hidden if no warnings are present\n- Package Installations will now skip license agreements / readme panels if none are specified\n- Made sure More Info in download panel can scroll\n- Fixed issue with spacing in setup options panel of package install\n- modCacheManager->generateScript(): Fixed PHP notice in log message on error.\n- modInstall: Modify _modx() function to call setDebug with E_ALL & ~E_NOTICE instead of E_ALL & ~E_STRICT.\n- Optimized queries in element tree to eliminate subqueries or queries in loop, reducing to O(n) instead of O(n^2n)\n- Made clear cache results a bit smaller\n- Refresh trees after clear cache\n- [#MODX-609] Clear cache menu item now loads results in an alert dialog. No longer loads a separate page.\n- Fixed to template getlist processor\n- [#MODX-671] Fixed bug with resource group access permissions being checked when not assigned\n- [#MODX-699] Fixed to allow usage of login processor without lexicons\n- Added Import/Export to element properties grids, which allows for file-based transporting of properties.\n- Fixed issues with comboboxes dropping down a blue screen\n- [#XPDO-28] Fixed problem with multiple file resolvers on vehicles with similar basenames cause directory contents to merge unexpectedly.\n- fixed PHP notice for missing elementType variable\n- fixed subcategory elements missing from display (was counting elements in parent category rather then subcategory to determine if the subcategory should be displayed)\n- Fixed issue with default properties in TVs being locked\n- Fixed no onTVFormPrerender\n- Made sure clearDirty is fired on TV panels\n- Tweaked the css and updated copyright year.\n- Refactored all index.php gateways to support constructor options set as $options in the various config.core.php files.\n- modCacheManager/modCache: Introduced cache partitioning allowing various cache provider implementations to target specific MODx cache partitions and provide custom (system/context/user) settings for configuration options to each: cache_system_settings, cache_context_settings, cache_resource, cache_scripts, cache_lexicon_topics, cache_action_map\n- modAccessibleObject: Refactored object and collection loader logic to improve cache hit rates.\n- modRequest: Fixed warning for undefined variable $fromCache.\n- modSessionHandler: Refactored write() method to only update access time when the session data has changed or at specified intervals before the data is made available for GC.\n- modSessionHandler: Added support for cache_db_session, a new configuration setting to allow session data to be cached when cache_db is enabled.\n- modTemplateVar: Allow getValue() to use a `value` field for data if already populated for a specific resource.\n- Commented out missing image in welcome.tpl (temporary)\n- Added couple of bugfixes to modDBRegister to prevent duplicate payloads and update existing messages.\n- Fixed bug where QuickUpdateChunk was persisting values\n- Added fix to prevent DOM id problems\n- Added clearCache checkbox to chunk editing to allow toggleable cache clearing\n- Optimized chunk processors\n- Added 'Quick Update Chunk' and 'Quick Create Chunk' options to Elements tree, which allows you to quickly edit or create chunks via a window straight from the Element tree on any page\n- [#MODX-718] Fixed bug where elements without a category wouldn't show\n- [#MODX-697] Fixed problem with deprecated role topic still in action build scripts\n- [#MODX-705] Removed random numbers causing Radio TVs to render improperly\n- Fixed bug that caused policy data to be erased when creating/saving/removing policy data\n- [#MODX-711] Fixed Update Context screen to properly pass correct PK\n- modDbRegister: fixed bug with expired messages not being removed if remove_read => false\n- modDbRegister: allowed messages to be updated/overwritten\n- Fixed modCacheManager::prepare() - was returning false on already-prepared contexts\n- Added support for nested categories for elements; categories can now have subcategories\n- Fixed to treestate to properly set treestate ID so restore can work properly\n- Fixed call to onDocFormRender to make sure ID is passed on Resource update\n- Fixed to getFiles processor for MODx.Browser to properly store URL parameter with the base_url prefixed\n- [#MODX-712] Fixed errors creating context settings\n- modX: Fixed potential error when invokeEvent() is called and executes a plugin with property sets and pluginCache does not contain the object\n- modCacheManager: Fixed error when building the pluginCache with property sets\n- modCacheManager: Fixed typo in parentSql that was breaking use alias paths option.\n- modCacheManager->generateContext(): Added support for Resources to be generated in multiple contexts via modContextResource.\n- modParser: Removed errant log() statement in parseProperties().\n- modParser: Fixed problem in parsePropertyString() when passing `escaped` property values containing semi-colons (;).\n- Added in necessary reloading functions to ColumnTree\n- Fixed issue with column tree's context menu overriding the ID\n- modManagerResponse: Detect if controller responses are error arrays and render using error.tpl appropriately.\n- [#MODX-693] redirect bug - modResponse logic error\n- Moved core/config/version.inc.php to core/docs/version.inc.php\n- layout/tree/resource/getnodes.php: Additional optimization to reduce memory usage and improve performance when opening Resources containing a large number of children.\n- modConnectorResponse->toJSON() optimized to greatly reduce memory usage and improve performance with large result sets.\n- [#MODX-691] allow User Settings to be saved from prop. grid\n- Fixed bug with documentMap\n- Fixed issue with default tv render panel for resource page\n- [#MODX-690] Fixed a few events names registered in the system_eventsnames table during build/install\n- Added id's to element and category nodes for informational purposes (missed one spot).\n- Added id's to element and category nodes for informational purposes.\n- Updated drag and drop behavior to update context_key of all child Resources when dropping a container on a different context node.\n- Modified modTransportPackage.manifest field from MEDIUMTEXT to TEXT in order to handle large manifests.\n- Fixed aliasMap broken in recent cacheManager refactoring.\n- Added helper functions to MODx.tree.ColumnTree\n- Added DD events to ColumnTree\n- Added missing column tree CSS\n- Added UI for adding property sets to PluginEvents\n- Added cacheManager object checks to verify for PHP4 installs\n- modCacheManager->generateResource(): added validation of the modResource primary key before attempting to cache a record.\n- modUser: modified storage of session data to use the modUser primary key value to isolate values associated with a specific user; this will allow users to login as multiple users on the back-end and/or front-end without affecting the session data associated with a specific user.\n- modX->_initSession(): Enable session_gc_lifetime configuration setting to set session.gc_liftime ini setting regardless of what session handler is configured.\n- modPluginEvent: Added the ability of plugins to utilize Property Sets by allowing a plugin registered to a particular event to attach a Property Set and make it available during processing.\n- Fixed warning with loading of RTEs in resource page\n- [#MODX-674] Fixed content-dispo combobox bug\n- Removed allowBlank: false check on menuindex to allow for dynamic creation\n- Added in missing lexicon entries for prior menuindex commit\n- [#MODX-678] Added back in 'menuindex' field to resource panels\n- Added missing modX::__construct() options parameter.\n- Allow for extending of MODx.panel.ResourceTV by making reference to modx-resource-template field dynamic\n- Fixes for RTE loading\n- Fixed issue where smarty template path was not being reset if 3PC set path to something else\n- modX constructor now accepts a second parameter containing an array of options to be set in the config\n- Major refactoring of modCacheManager to provide more granular caching options\n- modCacheManager now accepts options, based on changes to xPDOCacheManager, and provides access via getOption()\n- generate*() methods now all return data as well as cache it to a specified cache_handler unless otherwise configured\n- modX->getCacheManager() no longer supports MODX_CACHE_DISABLED or config['cache_disabled']; the cacheManager is required, though you will still be able to effectively turn off all caching in the future via this setting (this will be worked back in)\n- manager/controllers/system/refresh_site.php changes to better target things to remove from the cache\n- Introducing modDbRegister and the modx.registry.db package, providing a database modRegister implementation.\n- Added new system settings for individual cache areas, i.e. cache_system_settings, cache_context_settings, cache_lexicon_topics, cache_scripts, etc.\n- modCacheManager: Various fixes and adjustments to latest refactoring, including clearCache improvements.\n- manager/controllers/system/refresh_site.php: Improvements to default clearCache call.\n- modCacheManager: converted generateActionMap() to support configurable cache implementations\n- Updated modAction->rebuildCache() and modManagerRequest->loadActionMap()\n- Additional tweaks to manager/controllers/system/refresh_site.php\n- Updated xPDO externals to revision 308\n- Removed unnecessary comments from the reg* functions\n- Moved all manager pages JS/CSS to inside HEAD tag using the reg* functions; this improves speed and validation of the manager\n- Fixed the way 3PCs handle their controller files. NOTE!!! This means that you no longer need a \"core/controllers\" file in your 3PC; just set the namespace path correctly, then set the controller in your modAction.\n- Added an ability for mgr pages to utilize regClientStartupScript and other reg* functions to make pages load faster and move JS/CSS to HEAD tag\n- modX->getEventMap() - Made sure prepare() creates a valid statement before calling execute()\n- Updated modStaticResource to set headers in getFileContent() for now, though this needs to be refactored for flexibility.\n- Fixed issue with saving TVs from create resource processor\n- [#MODX-637] Fixed issue with TVs not reloading on changing template in new resources\n- [#MODX-663] Fixed various issues with modAction creation\n- Fixed issue with MODx.Browser uploads not refreshing the main view\n- Fixed publishedon default date setting\n- Fixed date TV default value\n- Fixed default setting for symlinks\n- Fixed issue with Symlink/WebLink class_key storing\n- Fixed issue with textfield editing in Safari on Property Set grid\n- [#MODX-662] Fixed duplicate issue with elements\n- Fixed issue with property sets page and property lock\n- Fixed name issue on duplicating elements\n- Fixed symlink page setTimeout issue\n- Fixed missing file inclusions\n- Fixed element tree where categorized templates weren't showing\n- Added editing ability to resource's publishedon date\n- Fixes to package downloader panel due to ID conflicts\n- Adjusted modTransportPackage::transferPackage to rename incoming file to [signature].transport.zip rather than basename($source)\n- Fixed xml/json response classes to properly work\n- Added permission \"unlock_element_properties\", which gives ability to unlock editing of default element properties.\n- Added implementation of above permission into element properties grid\n- Fixed some logic issues with the lockMask\n- [#MODX-561] Added \"Locked\" ability to default properties for elements\n- [#MODX-633] Fixed issue with add another not respecting parent\n- Fixed TV access panel not working on new TVs\n- Fixed state management with tree nodes\n- [#MODX-661] Fixed URL TV input, where it was not setting prefix value\n- [#MODX-659] Fixed bug where root-level docs couldnt be updated b/c of parent issue\n- Fixed bug with parent being assigned to 0 always in derivative Resource classes\n- Made sure bad resources (where parent = id) are ignored when building the context cache files.\n- Fixed parent bug in controllers\n- Fixed transport.data.php with 'namespace' key on modActions\n- [#MODX-622] Updated top menu structure to be more consistent.\n- Fixed error if properties are null\n- [#MODX-651] Fixed bug when deleting a propset, would not empty grid\n- Fixed to resource page combos not setting display value correctly\n- [#MODX-658] Fixed issue where in TV -> Create, templates were not showing\n- Fixed template nodes to properly sort by templatename\n- Adjusted resource menus and such to refer to a 'Resource' without a specific class_key as 'Document' when applicable, with the exception of talking about Resources in the generic sense\n- Added Duplicate option to Property Sets\n- Fixed bug where template inheritance for resources wasn't happening\n- Fixed symlink page\n- [#MODX-632] Updating xmlrpc to 2.2.1\n- Corrected logic in setup to allow forced PDO emulation mode (XPDO_MODE == 2).\n- Added `category` field to modPropertySets; they can now be categorized\n- Enhanced UI to support new modPropertySet category ability\n- Modified MODx.Window so that the ENTER key submits the form\n- Added more IDs to element forms\n- Added ability to \"remove\" overridden properties, but only ones that are not in the default propset (ones that are should \"revert\")\n- Fixed OnWebPagePrerender event not firing as expected.\n- modOutputFilter: Refactored date modifier to return '' if the timestamp encountered == 0 or -1.\n- modOutputFilter: Added strtotime modifier.- Refactored connectors to execute in the context from which they are called, rather than their own context.\n- Updated xPDO to revision 304 for new xPDOFileVehicle feature to respect XPDO_TRANSPORT_RESOLVE_FILES options.\n- [#MODX-562], [#XPDO-24], [#XPDO-25], and [#XPDO-26] Updated xPDO to revision 302 to resolve various issues regarding transport packages and model generation.\n- [#XPDO-23] and [#MODX-604] Updated xPDO to revision 298 to resolve nesting error when logging messages during installation with improper cache directory permissions.\n- Added modPropertySet->getElements() method as shortcut to get all proper modElement instances available to the set.\n- Added overridden modElementPropertySet->getOne() to get related Element using the proper element_class value.\n- [#XPDO-21] Updated xPDO to revision 290 for updates to xPDOObject::addOne() and addMany().\n- [#MODX-553] Unpublished and deleted Resources now ignored properly in modRequest::getResource().\n- [#MODX-553] Core setup now automatically adds an ACL to the web context for members of the Administrator group.\n- Core setup now updates the Administrator group ACLs for accessing the mgr and connector contexts with an Authority of 0 (highest authority).\n- Modified OnUserNotFound event handling not to rely on references which no longer work properly with recent changes to property handling.\n- Added overridden modElement->get() to handle converting legacy property strings stored in the database.\n- Added modPropertySet class to represent persistent sets of properties that can be applied to modElement instances.\n- Added support for modElements to relate modPropertySet objects via modElementPropertySet (many-to-many).", "MODX Revolution 2.0.0-alpha-6 (LastChangedRevision: 4485 , LastChangedDate: 2008-11-25 11:58:49 -0600 (Tue, 25 Nov 2008))\n====================================\n- [#MODX-395] i18n'ed the modMail classes, added lexicon topic 'mail' for handling mail strings\n- Added check to make sure user cannot browse to subdirs with ../ in connector processor fetching\n- [#MODX-482] Implemented code to remove setup/ directory when box is checked.\n- [#MODX-408] Fix atrocious grammar in mail reception message\n- Fixed labels for static resource page\n- [#MODX-518] Make sure clearing cache clears registry output from package\n- Fixed in_array() checks against $_currentTimestamps in xPDOObject::save() that prevented timestamp/datetime fields from saving 0 values.\n- [#MODX-512] Fixing check in setup to make sure core/packages is writable\n- Fixed bug with RTE loading and saving\n- Changed 'Provisioner' references to 'Provider' in UI for nomenclature consistency purposes\n- Added lexicon load to resource processors\n- Fix error on resource view when template is empty.\n- Added namespace filter to settings grid\n- Fixed import trees\n- Hide the resource ID field if a new resource\n- [#MODX-514] Fixed issue with pub_date/unpub_date not being reset properly\n- [#MODX-484] Added missing ht.access sample to web context files in included in transport package.\n- Modified modWorkspace vehicle attributes to XPDO_TRANSPORT_UPDATE_OBJECT => false\n- Updated xPDO to revision 284 for new xPDO package-aware vehicle features when loading classes.\n- Slight styling improvement to grid to make alt-rows more apparent\n- Added clearCache() functions to modLexiconTopic, modLexiconLanguage\n- Added 'collapsible' options to the options tabs of resources. Can now collapse them to show only the content editor.\n- Prevent blank property value names\n- Adding css classes to modext components for easier styling\n- Fixed some issues related to installation of packages, namely dealing with the setup-options attribute and resolver handling\n- Added _build/build.local.xml to prepare an svn development copy for execution; builds core transport, minifies and concats the javascript and puts it in place, etc.\n- Slight fix to login box and css styles to get checkbox checked css to render properly\n- Updated xPDO to revision 281 to get fix to xPDOObject::save() when updating fields with NULL values.\n- Styling updates; make form fields bigger, tabs bigger, menus bigger...basically pretty up the UI\n- Fix to typo in createTable in modInstallVersion\n- Implemented version-specific upgrades to setup/\n- Updated xPDO to revision 275 (xPDOObject datetime/timestamp handling improvements, xPDOTransport pre-existing object restoration features, and more).\n- Changed System Events action to Error Log Viewer, which now allows you to view (and clear) the error log from the manager\n- [#MODX-509] Fixed issue with refreshing of incorrect node in dragdrops on trees\n- Fixes to CSS in setup, moved error box to fixed bottom right, i18n'ed more stuff, cleaned up HTML and simplified outputs\n- Fixed issue where the path for processors could not be overridden by changing the parameters for handleRequest in modConnectorRequest to an array of options\n- [#MODX-501] Fixed issue where trees didn't refresh when package was installed. All trees now refresh.\n- Fixed bug with duplicating resources\n- [#MODX-505] Fixed issue with creating weblink redirecting improperly\n- Fixed issue with emptying recycle bin and root-level resources\n- [#MODX-508] Weblinks are now not hidden by default\n- Fix missing published checkboxes in resource derivative classes\n- Applied patch to fix issue with label click of checkboxes not changing value\n- [#MODX-507] Fixed bug where Published checkbox wasnt showing in resource panel\n- Fixed bug in filetree that would scroll up topmenu\n- [#MODX-507] Adding in textbox for parent ID for now, will come up with better solution later\n- [#MODX-506] Fixed bug where cache wasn't cleared on drag/drop in tree\n- Fixed bug in modPackageBuilder that was preventing deletion of existing package directories and files.\n- Added constants MODX_INSTALL_MODE_NEW, MODX_INSTALL_MODE_UPGRADE_EVO, MODX_INSTALL_MODE_UPGRADE_REVO\n- Extracted install->test() to a separate class, then i18n'ed the test strings\n- LOTS of phpdoc additions to all processors, including parameter lists for each processor\n- Removed any last trace of modules from Revolution\n- Added phpdoc information to processors\n- Properly clear cache on install/uninstall/remove of packages\n- Removed \"require_once MODX_PROCESSORS_PATH.'index.php';\" from all processors\n- Only show 'Update Package' if the package comes from a provider\n- Fixes to get browser working with TinyMCE\n- Fixed issue with forced removing of packages not properly removing the resolvers\n- Standardized modRequest/modResponse methods across all derivatives (i.e. modRequest::handleRequest() always calls modRequest::prepareResponse(), which calls modResponse::outputContent()).\n- [#MODX-478] Fixed typo in lexicon import/export that prevented window hiding\n- Fixed issues with Symlinks\n- Fix to TV output/input renders when loading in a context other than web/mgr\n- Fix to invokeEvent to prevent unwanted caching of event name if plugin executes more than one event per runtime\n- [#MODX-424] Added readme viewing to package grid\n- Added ability to delete multiple element properties at once via a multiple row handler\n- [#MODX-488] Removing double click from properties grid for 'name' field to prevent unwanted breaking\n- Added back in setDirectory to modConnectorRequest\n- [#MODX-292] Properly format system settings editedon value\n- [#MODX-293] Properly format editedon for lexicon entries\n- [#MODX-481] Fixed rendering issues in element property grid columns\n- [#MODX-479] Fixed issue where first snippet property edited didn't show value\n- [#MODX-480] Fixed issue with lexicon entry update/create not loading proper topic\n- [#MODX-474] Removing package builder menu item from build script\n- [#MODX-456] Fixed issues with element property grids\n- Fixed MODx.grid.LocalGrid store bugs when dealing with grouped data\n- added pageSize and pageStart config items to MODx.grid.Grid\n- Fix to MODx.grid.Grid in case listeners are provided, dont ignore context menu\n- [#MODX-466] Fixes to dropdowns for element categories, field issues\n- [#MODX-115] Some fixes to rendering issues with comboboxes/datefields on Safari\n- Updated xPDO to rev 265 for improvements in xPDOValidator allowing multiple rules to be evaluated per column.\n- Refactored modError completely, removing all derivative classes and introducing modManagerResponse and modConnectorResponse to handle formatting modError responses appropriately.\n- Added modRequest::registerLogging() and relocated logic for detecting and taking action on register logging parameters out of loadErrorHandler().\n- Refactored modArrayError to remove Smarty dependencies, moving them to a new derivative, modSmartyError which the manager UI can utilize explicitly.\n- Added element property panel to all Element panels for managing default properties (except Modules).\n- Added modElement->setPlaceholders() to set placeholders and return any global placeholders that might need to be restored after an element is processed.\n- modChunk and modTemplateVar now restore any placeholders from the global scope after processing any local properties with the same name.\n- Added properties as local placeholders when processing modTemplateVar instances to match behavior of modChunk/modTemplate.\n- Updates to snippet property editor.\n- Added properties to modTemplateVar to make them consistent with all other elements.\n- Modify modX::getChunk() and runSnippet() to process those elements as non-cacheable instances.\n- Added modResource::getContent() and setContent() functions for extensible control of accessing raw source content.\n- Modify modElement::setProperties() and modTag::setProperties() to handle various property data formats.\n- Updated modParser::parsePropertyString() to handle local property xtypes from UI and convert legacy types.\n- Added isCacheable() and setCacheable() to modElement and modTag classes for direct, extensible control of caching.\n- Modified behavior of modTemplate/modChunk not to prefix properties turned into placeholders with the name of the element.\n- Added getContent(), setContent(), getProperties(), and setProperties() to modTag and derivatives.\n- Added modParser::parsePropertyString() to parse element properties from string or array representations.\n- Updated modElement::process() behavior to check cache sooner and avoid unnecessary source content access and other processing.\n- Additional foreign key and sorting indexes added to modElement classes.\n- Added properties to all modElement classes except modTemplateVar.\n- Added setProperties() to modElement for setting a set of default properties that will be used by the element.\n- Added getProperties() to modElement for getting the properties to be used when processing the element.\n- Added getContent() and setContent() function to modElement and provided overrides in the appropriate subclasses.\n- Removed modTransportPackage::loadTransport(); the manifest should always be loaded from the file.\n- Updated xPDO to rev 262 for improvements in the xPDOTransport manifest format.\n- Updated xPDO to rev 258 for bug fix in new xPDOObject::_setRaw() function with array and json phptype fields.\n- Updated xPDO to rev 256 for bug fix in xPDO::getSelectColumns() and new xPDOObject::_setRaw() implementation to resolve issues with native php types when using fromArray().\n- Added modPackageBuilder->setPackageAttributes() function for easily adding transport-level attributes to a package.\n- Updated xPDO to rev 252 to get new features allowing transport packages to carry transport attributes.\n- Added numerous foreign key and sorting indexes to site_content table (modResource) to improve performance of common queries.\n- Changed modX::changePassword() implementation to call modUser::changePassword().\n- Added getResourceGroups() and getUserGroups() to modUser class to retrieve those things and cache in session.\n- Renamed and moved modX::_checkPublishStatus() to modRequest::checkPublishStatus() and renabled this functionality.\n- Deprecated and moved modX::checkPreview() implementation to modResponse.\n- Added view_offline attribute to default Context access policy.\n- Removed deprecated and invalid modX::makeFriendlyURL().\n- Removed deprecated modX::webAlert() function.\n- [#MODX-364] Results of regClient*() functions are now cached into the Resource cache files to solve error on cached pages with cached snippets.\n- Removed deprecated modX::mergeDocumentMETATags() and moved feature to modResource::mergeMetatags() and modResource::mergeKeywords().\n- Removed deprecated modX::makeList() function.", "MODX Revolution 2.0.0-alpha-5 (LastChangedRevision: 4273 , LastChangedDate: 2008-10-09 12:42:42 -0500 (Thu, 09 Oct 2008))\n====================================\n- [#MODX-88] Move version checking to setup script and add notifications.\n- [#MODX-66] Change the way properties work within the scope of a chunk; placeholders set by the chunks properties are now removed after the chunk is processed.\n- Added modX::unsetPlaceholder() and modX::unsetPlaceholders() functions.\n- [#MODX-329] Fixed error with browser \"remembering\" user even when \"remember me\" is not checked. Was always using the system setting regardless of rememberme.\n- [#MODX-380] Created modSymLink resource class which forwards requests to other resources without changing the URL (as opposed to modWebLink which redirects).", "MODX Revolution 2.0.0-alpha-4 (LastChangedRevision: 4213 ,LastChangedDate: 2008-10-01 12:18:41 -0500 (Wed, 01 Oct 2008))\n====================================\n- Updated xPDO to rev 248\n- More log messages for modPackageBuilder\n- Fixed some bugs with MODx.Browser\n- Enabled specific path setting for MODx.Browser\n- Fix to remove redirect to system settings if version info differs.\n- Added MODX_SETUP_KEY to setup to identify the distribution type and allow setup logic to be conditional based on this information.\n- Introduced additional default policy attributes and policy checks throughout the controllers and processors for more robust access control.\n- [#MODX-349] Added processor and menu item to reload your own access policies without logging out and logging back in.\n- [#MODX-349] Added processor and menu item to flush all user sessions from the database.\n- [#MODX-349] Modified user policies to cache policies by Context; previously policies cached for one context were being applied to other contexts when switching or accessing both from the same browser session.\n- Updated xPDO to revision 246 to fix problem with modLexiconEntry rows being duplicated in upgrades after deleting modLexiconFocus records.\n- Modified Ant build to automatically compress and concatenate js files (SVN users cannot use compress_js option without performing the complete-wc task in build.xml).\n- Updating xPDO to revision 234.\n- Added support for logging to registers through any modError instance when loaded by modRequest::loadErrorHandler().\n- Removed modRegisterHandler and added logging helper functions to modRegistry.\n- Updating xPDO to revision 233.\n- Updated modAccessibleObject::loadCollection() based on xPDO::loadCollection() changes.\n- Updating xPDO to revision 231.\n- Various model updates to reduce memory usage [convert foreach with fetchAll() calls to while with fetch()].\n- [#MODX-137] Locked Elements now editable by users with the Admin policy attribute edit_locked (not locked as in being edited by another user, but locked explicitly in the Element attributes).\n- Moved makeUrl logic to modContext class and modX now determines which context to use when building the URL.\n- Introduced modX->getContext() to retrieve, prepare and store context configurations in modX->contexts array for reuse during the single request\n- Added _config, _systemConfig and _userConfig to hold on to various parts of the configuration settings before they are merged for use, allowing other functions to remerge the settings as needed.\n- Fixed modX->switchContext() to clear all contextual/user setting overrides and reload the bootstrap _config, _systemConfig, and make use of the modX->contexts array.\n- Implemented UI ability to choose vehicle-specific attributes when adding vehicles to packages\n- Added dynamic value replacement of {setting_key} in user settings in modX->getUser().\n- Added function to grab the request parameters to MODx.request\n- Added missing permission check on empty_cache attribute on refresh_site controller/processor.\n- Updated xPDO to revision 218.\n- [#MODX-282] Fixed bug where grid would show non-existent page in lexicon/settings grids\n- Removed permission check on logout action; doesn't make much sense.\n- Proper formatting of editedon time in system settings grid\n- Added System Settings \"Update Setting\" window for more detailed editin\n- Rebuilt core data files for the transport.core.php script and made correction to core namespace path to the value {core_path} which is calculated at run-time.\n- [#MODX-263] Access policy update grid moved to separate page\n- Created panel for editing access policies\n- [#MODX-277] Changed 'setting' to 'name' at top of System Settings grid\n- [#MODX-283] Fixed combo-boolean combobox to prevent overwriting of form variables. this was a bizarre bug.\n- Allowed modPackageBuilder to now use dynamic, on-the-fly namespaces. Separated out registerNamespace() from create()\n- Added support for loading extension_packages via configuration settings before the session is initialized.\n- Fixed dynamic value replacement of {setting_key} in system and context setting generators.\n- Updated xPDO to revision 216.\n- Added class_key field to modUser class/table to support modUser derivatives.\n- Fix to new modLexiconEntry table structure (was not installing due to NOT NULL and no default value).\n- Removed modResource::hasAccess() function to make sure and avoid confusion with security.\n- Add default admin user to the Administrator modUserGroup with a modUserGroupRole of 2 (SuperUser) on new installs and upgrades.", "MODX Revolution 2.0.0-alpha-3 (LastChangedRevision: 3867, LastChangedDate: 2008-07-22 08:44:38 -0500 (Tue, 22 Jul 2008))\n====================================\n- [#MODX-210] Changed no-longer-valid help text for resource panel\n- [#MODX-216] Fixed bug with pub_date/unpub_date for the Resource panel\n- [#MODX-213] manually entered passwords not being displayed after saving\n- Added editability to packages grid\n- [#MODX-205] Fixed category saving\n- [#MODX-196] Fixed snippet category error in IE7\n- Created modInstallError for base processing methods\n- Added object support to modInstallJsonError\n- [#MODX-201] Fixed bug with Category combo that prevented adding in a custom category\n- [#MODX-200] Added colored Not Installed text to not installed packages\n- [#MODX-70] Removed top buttons, as they are unnecessary and cause more problems than they are worth.\n- [#MODX-174] Language setting in setup is not loaded.\n- Note: renamed the language file to en.php to match the adopted IANA standard codes (see #MODX-187)\n- [#MODX-26] Manager User creation problems\n- Corrections to new user account email\n- Added MODX_URL_SCHEME define and url_scheme configuration setting\n- Added MODX_HTTP_HOST define and http_host configuration setting\n- Changed \"Modules\" top menu to \"Components\" top menu. Component developers are encouraged to put their 3rd party menus in there.\n- [#MODX-83] Radio Options not working in TV\n- [#MODX-103] Fixed blank template change warning message.\n- [#MODX-173] Language setting in manager pages is not loaded.\n- Removed ucwords on getlist processor for lexicons.\n- Fixed feed_modx_security/news keys in the build file.\n- [#MODX-184] Fixed show in menu checkbox, should have been labeled \"Hide Menu\" since the opposite is true in the database. Changed to match DB column properties.\n- [#MODX-190] Fixed bug with missing duplicate snippet error message\n- Added check for existing name in snippet duplicate processor\n- Updated build.src.url to branches/revolution\n- Fixed import html/resources\n- Fixed action pointer if version is incorrect", "MODX Revolution 2.0.0-alpha-2 (LastChangedRevision: 3841, LastChangedDate: 2008-07-15 09:18:24 -0500 (Tue, 15 Jul 2008))\n====================================\n- Adopting new product name, MODX Revolution, and changed version to 2.0.0\n- Fixed bug with content type grid\n- Replaced 'gender' with Role column in Users grid\n- [#MODX-182] Fixed invalid reference in tv/create.js\n- Fixed TV input type dropdown, added proper processor/connector\n- changed xPDOCriteria calls to more abstract newQuery ability\n- Added attachment capabilities to modMail/modPHPMailer classes\n- Added setHTML method to modPHPMailer\n- Updated documentation for modValidator class\n- Added explicit header call to set text/json; charset=UTF-8 on responses from modJSONError\n- Remote package installation now works.\n- Fixed invalid schema relationships with transport providers/packages\n- Included check for xPDO transport service config to prevent warning\n- [#MODX-108] Added more database info to the site info page - contrib by sottwell\n- Finished UI for modStaticResource\n- Added some inline documentation to widgets for help\n- Set a more appropriate default resolver target\n- Removed unnecessary package parameter from modPackageBuilder::buildSchema\n- Removed unnecessary package setting\n- Added buildSchema function to modPackageBuilder\n- Added tooltips to elements and contexts in the resource/element trees\n- Fixed bug in Module update page\n- Added a qtip to document tree nodes so they display resource longtitle/description in a tooltip\n- Moved styles to gray theme to prepare for css work\n- Weblinks now functional\n- Fixed slight bug with FF3 and panel collapsibility\n- Fixed plugin properties\n- [#MODX-162] Fixes problem where vehicle grid is not refreshed on 2nd build, as well as resets the form\n- Added 'success' event to MODx.FormPanel\n- [#MODX-172] Fix to option values for setup in IE 6. Fix by kmd.\n- [#MODX-166] - Fixed config cache issue - fix provided by kmd\n- [#MODX-165] could not save Template element - fix provided by SA\n- Fixed and cleaned up the actions/menus JS and combos\n- Removed unnecessary tertiary expression (check is already handled by the function)\n- [#MODX-131] Fixed Apache crash and enabled Tools -> Action\n- Added fix to _() JS function to allow for parameter passing:\n String: 'Testing: [[+hello]]';\n JS call: _('testkey',{'hello': 'Success!'});\n Result: 'Testing: Success!';\n- [#MODX-148] Added support for [[+placeholder]] tags in lexicon strings. i.e., with a lexicon string with key 'test' and value: 'Test me: [[+hello]]'\n Programmatically:\n $modx->lexicon('test',array('hello' => 'Success!');", " Tag:\n [[%test?hello=`Success!`]]\n- Fixed to typo on system info JS\n- Added namespacing ability to the addDirectory() and load() methods of modLexicon. Used like so:\n $modx->lexicon->addDirectory('pathhere/','testNS');\n $modx->lexicon->load('testNS:fociname');\n- [#MODX-102] fixed missing lexicon entries in php4\n- Added OnHandleRequest event, invoked before anything occurs in modRequest::handleRequest().\n- Set the modLexicon::_lexicon to an empty array even if nothing was loaded.\n- Added modX::switchContext(string $contextKey) function to make it easy to switch contexts using a plugin and the new OnHandleRequest event.\n- Fix to properly submit the content field for resources (should also handle multiple RTEs now)\n- Fixed typo in lexicon reference in event getlist\n- Fix to MODx.load to return multiple objects if they exist\n- General JS doc updates\n- Added MODx JS class, which allows for xtype loading via MODx.load()\n- Some JS doc updates\n- Fixed modErrorHandler to ignore suppressed errors like a proper error handler is expected to.\n- [#MODX-109] Fix bug with profile page loading of date.\n- Reconfigured context update window to separate into tabs for easier viewing and rendering\n- Changed TV resource group panel to a grid, instated proper remove/update code\n- [#MODX-126] Implemented 2 new modSystemSettings: feed_modx_news and feed_modx_security for dynamic setting of the RSS feeds in the welcome pane of the manager\n- [#MODX-137] Removed locked check until a resolution is made on locked elements.\n- [#MODX-119] Corrected issue with file editor stripping out SCRIPT tags. Was using $_REQUEST instead of $_POST so the values were sanitized by the request handler.\n- Updated Template management to a MODx.FormPanel\n- Altered the way modLexicon loads multiple foci for PHP4 compatibility\n- Added modLexicon::addDirectory, which adds a directory when loading lexicon foci\n- Properly load TV widgets and i18n their strings\n- Fixed bug with modLexicon and $modx reference\n- [#MODX-133] Prevent elements from being dragged into different types\n- [#MODX-125] Fixed saving pub/unpub date on resources\n- [#MODX-106] Removed assets/images check.\n- Configured Object field in Package Builder to be a combobox that loads a dropdown of the selected class_key\n- Added ability to remove vehicles from not yet built package\n- Added MODx.grid.LocalGrid as abstract class of local-data-based grids\n- Added MODx.panel.Wizard as abstract class of wizard panels\n- [#MODX-121] Fixed top menu loading incorrectly when clicking on icons\n- Fixed TV management page, specifically with TV->Template access\n- [#MODX-118] Fixed bug with creating/removing/updating directories from Directory tree\n- Added MODx.combo.ContentDisposition\n- Added ability for MODx.toolbar.Actionbuttons to support formpanel as an alternative for form config parameter\n- Added $modx->config properties to MODx.config JS array sent\n- Fixed update resource TV loading\n- [#MODX-113] Fixed bug in Safari with scrolling in grids, apparently Safari doesn't like Ext's autoHeight\n- Removed legacy tpl's in settings/ dir\n- [#MODX-107] Fixed tree refreshes when resource is saved, both in create and update. Update will now refresh only the parent node of the resource being saved, which speeds up save time\n- Fixed issues with TV Panel loading improperly on new resource\n- [#MODX-114] Prevented JS error from occurring when using page settings checkboxes\n- [#MODX-116] Fixed text for removing a category\n- Fixed Resource pages to allow for Resource Groups to be assigned access prior to Resource creation, as well as making grid not save until 'Save' is clicked\n- Fixed Template pages to allow for TVs to be assigned access prior to Template creation, as well as making grid not save until 'Save' is clicked\n- Fixed TV pages to allow for templates to be assigned access prior to TV creation, as well as making grid not save until 'Save' is clicked\n- Fixed module update, removing legacy code\n- Fixed plugin event grid: now can be used via create or update, also properly handles events, does not save until \"Save\" button is clicked on action bar", "MODx 0.9.7-alpha-1 (LastChangedRevision: 3664, LastChangedDate: 2008-04-28 12:43:15 -0500 (Mon, 28 Apr 2008))\n- Updated ExtJS from version 2.0 to 2.0.1\n- [Trac#20] When creating new document, make the 'Log Visits' checkbox respect the main configuration setting.\n- [Trac#9] Converted Database Tables tab in System Information to use Ext Grid.\n- [Trac#40] Default role settings are now set correctly when saving roles to the database.\n- [Trac#4] Converted Modules section to use Ext interface.\n- Added new resource import routine for creating resources from static content on the file system, as any valid modResource derivative.\n- Introducing context support to the manager resource trees.\n- [Trac#32] Display correct message counts for the Inbox section on the Welcome page.\n- [Trac#31] System Configuration page always showing 'New Install' message. Refactored code to use $modx->version.\n- [Trac#25] Several bugfixes and refactorings to make the Messages section function correctly.\n- [Trac#6] Remove Locks not working from the top menubar.\n- Removed custom_contenttype from system_settings and manager interface.\n- Converted and refactored Import HTML tool for the new APIs.\n- [Trac#29] Resource checkboxes on settings tab not showing accurate values when editing.\n- [Trac#28] Cache not cleared when resources are saved and the clear cache checkbox is checked.\n- [Trac#27] Cached modResources were not loading or rendering since getResource() moved to modRequest from modX. Cache files generated with new reference to the modX object ($this->modx vs $this).\n- Remove logic in modResource::addOne() that was disallowing binary content types.\n- Add conditional to check for $GLOBALS['https_port'] before attempting to use it.\n- Several fixes to modResource processors involving saving of boolean fields via checkboxes; make sure POST is filled with unchecked fields having a value of zero.\n- Upgrades now work for previous 0.9.7 installations\n- Add-on installation has been removed from setup in preparation for adding it to the manager itself.\n- Removed modManager095 and all related legacy support for ManagerAPI extender, moving this functionality to modManagerRequest.\n- Added/updated delegate controllers, templates, and processors for modWebLink and modStaticResource.\n- Added new static resource option to document tree context menus.\n- Fixed bug with chunk update processor deleting the chunk content.\n- [Trac#19] Bugs with password on user creation/update; was saving plain password (not encoded).\n- Introduction of new setup using transport packages (new installs only for now).\n- Modified modRequest::sanitize() to no longer strip old-style tags.\n- Moved MODx classes and maps out of core/xpdo/om/modx095 and into core/model/modx.\n- [xPDO] Add support for package specific include paths for models.\n- Refactored INCLUDE_ORDERING_ERROR to manager/includes/accesscheck.inc.php\n- Begin adding input and output filtering to all MODx elements and tags (modElement and modTag derivatives), including default filter implementations based on phX (not yet working).\n- Begin refactoring modx095 package to utilize xPDOQuery (modResource::getOne()).\n- [xPDO] Fixed error in xPDOObject::remove() that was trying to call the toCache function on xPDOObject rather than xPDO.\n- Added checkForLocks func to modx.class.php\n- Added checkIfIn to modmanager095.class.php, to do the annoying check if in manager in all the pages\n- Added splitter class for tables to get the line effect found in user management\n- Added ul.no_list to get list effect without bullets\n- Added formhandler.js - handles validation in forms by sending form through AJAX call. If response != true, then outputs response to a div with id 'errormsg'. Also evaluates JS scripts in the response.\n- Updated MODx model for modUserSettings and modWebUserSettings with appropriate primary key indexes and field types.\n- Updated installer SQL to remove the previous indexes and add the primary key index.\n- Fix to modX :: insideManager() to make sure there is a context object initialized before trying to get the context key.\n- [xPDO] Introduction of xPDOQuery for building SQL queries using only objects and the API.\n- [xPDO] Fix to timestamp phptype handling when stored as integer dbtype in database.\n- Modified modResource constructor to set createdon and createdby fields appropriately.\n- Fix for mcpuk GetUploadProgress script (see http://modxcms.com/forums/index.php/topic,11712.msg79581.html#msg79581)\n- Separated styles into their function, for easier manipulation and management\n- Ongoing Conversion of manager pages to xPDO, cleaning up XHTML\n- Emulated PDO can now be forced in PHP 5.1+ when PDO class is already available, but the required drivers are not available.\n- Added $modx->getTree() function for easily getting a tree structure of MODx resource ids in the current context.\n- Modified $modx->resourceMap to a simpler structure and optimized getParentIds() and getChildIds() functions. $modx->documentMap still holds the old structure but is deprecated.\n- Refactored entire caching layer, based on changes to xPDO. Files are now spread amongst logical directories, and automatic temp directory detection was also added.\n- Translated all core files and data in the core distribution/installation to the new native tag format.\n- Optimized modParser, removing run-time translation with modParser095 from normal execution and added modTranslate095 utility class, which can translate tags in database and file content, writing a log of the translation and/or making the changes to the database and files. modParser095 is experimental, and not recommended, as there are too many issues with mixed tags being parsed incorrectly.\n- Fix to make sure modX::parseChunk removes replacement placeholders for empty values.\n- Updates to MakeForm class.\n- Added modXMLRPCResource, modXMLRPCResponse classes and supporting code, including modified XML-RPC for PHP code (from version 2.1). You can now create resources that represent XMLRPC servers and clients.\n- Altered session cookie expiration that was getting set automatically on all sessions based on the default session cookie lifetime. Lifetime is now only applied if a session value is set for each context.\n- Added check to verify keys passed to modX::getPlaceholder() are valid strings to avoid PHP errors.\n- Various additional changes to prevent errors from revealing critical database credentials and connection information.\n- Fixed bug with system settings getting overwritten on mutate_settings manager page.\n- Merged from trunk (0.9.5.1-RC1) at revision 2251.\n- Latest updates and bug fixes from xPDO project.\n- Add ability to locate and use original manager/config/config.inc.php to upgrade directly on legacy installations.\n- Applied fixes to modResponse::outputContent(); was not assigning regClient script replacements to the output.\n- Changed parseChunk to parse new style tags to avoid any accidental matches on mixed tag situations.\n- Changed modChunk and modTemplate logic to create placeholders from any properties of the elements prefixed by the name of the element + '.' (added the .).\n- Fixed alias path generation, was reversing the order of parent paths in the resourceListing.\n- Fixed problems with recent changes to modRequest::sanitizeRequest() which was again truncating $_POST vars in the manager when encountering MODx tags.\n- Fixed generation of context cache files; was generating an eventMap for the mgr context at all times.\n- Fix to logic in modDocument::getMany('modTemplateVar').\n- Merge with 0.9.5.1 trunk at revision 2205.\n- Parsing adjustments to better deal with mixed old and new style tags.\n- [xPDO] Significant xPDO core update to prepare for SQLite, PostgreSQL and other ports.\n- Fix bug in install/upgrade SQL when resetting user and system settings for manager_theme.\n- Added some new configuration options for session handling and various caching features; more to come.\n- Minor changes to reduce number of unique db connections used during a request.\n- Various PHP 4 warnings fixed when assigning values by reference directly from functions (only variables can be assigned by reference in PHP 4).\n- Various improvements to MakeTable class based on usage in user_management and other manager interfaces.\n- Begin replacing Datagrid usage in manager with MakeTable (user_management, web_user_management, manage_modules, docmanager module); lots more Datagrids to replace.\n- Various changes to DataGrid and DatasetPager to try and support existing usage.\n- Fix for @EVAL bindings with more than one line of code.\n- Adjustments to modParser::collectElementTags() to better handle invalid tags (i.e. mispelled snippet names) with nested tags.\n- Adjustments to modParser095::translate() to properly handle translation from old to new configuration tags [(email_sender)] to [[++email_sender]].\n- DBAPI::escape() adjustment (again) to avoid certain issues when using native PDO along-side legacy manager code calling the mysql extension.\n- Removed & from getMany call in modCacheManager to prevent PHP warnings in PHP 4.\n- [xPDO] Added additional logic to xPDO::loadClass() which will return an error immediately if no class name is provided.\n- Adjusted modDocument::getMany() signature; added $cacheFlag= false parameter.\n- Remerged mutate_content.dynamic.php to fix several problems saving documents.\n- Adjusted queries in refresh_site.dynamic.php.\n- Added session table to install script due to failure of auto-table creation on some environments.\n- Removed unnecessary if statement around session_set_save_handler() in modX::_initSession(); the actual problem was auto-table creation was failing.\n- Fix DBAPI::escape() function; PDO::quote() adds single-quotes unlike the legacy mysql escape functions and this was causing content truncation.\n- [xPDO] xPDOCacheHandler class updated to allow configuration properties to determine a class for handling xPDO object and result set caching.\n- modX::_initSession() updated to better handle situations where session_set_save_handler() fails when trying to override default PHP session handling.\n- [xPDO] Modified fromArray() so it is not responsible for determining the _new attribute of xPDOObject instances. This is the responsibility of xPDO::getObject(), which uses xPDO::load(), and xPDO::getCollection().\n- Fix datasetpager error with PDO changes so DocManager module can load.\n- Fix WebUser login -- weblogin.processor.inc.php.\n- Fix makeUrl() -- no longer needs to add base_url.\n- Fix upgrade install script to insert new config settings properly.\n- Few tweaks to modX::_initSession function (was setting session_name twice).\n- Changed all line-endings to unix-style \\n on all files.\n- Removed assets/cache/* which is replaced by core/cache/*.\n- Updated version data format to be compatible with PHP's version_compare() function.\n- Resolved problems setting primary keys values and improperly identifying new objects when using xPDOObject::fromArray().\n- Several adjustments to xPDO::load(), xPDO::getCollection() and several xPDOObject methods based on changes to xPDOObject::fromArray().\n- Added stripslashes() to modRequest::_sanitize() when working with magic_quotes_gpc enabled.\n- Fix to MakeTable::prepareOrderByLink() to handle FURLs properly.\n- Reduce exposure of critical database credentials in xPDO::load() when errors are reported/logged.\n- Fixed error in xPDOObject::save(); updates to objects with compound primary keys were failing.\n- Added proper escapes to deprecated modX::getFullTableName() to fix issues when dashes (-) or other reserved (My)SQL characters appear in a database name.\n- Merged with trunk (0.9.5 final) at revision 2106.\n- Removed session_keepalive code.\n- Merged with trunk (0.9.5) at revision 2066.\n- Merged with trunk (0.9.5) at revision 2063.\n- Schema updates based on column size changes in 0.9.5.\n- Added missing modX::getSettings() method.\n- Various bug fixes.\n- Merged with trunk (0.9.5) at revision 1945.\n- [bug fix] Fixed a modParser bug when CDATA wrappers were encountered.\n- Add missing webAlert function to new modX class.\n- Modify categories save process to get the insert id using $modx->lastInsertId().\n- Fix to setup.sql; changed ENGINE= to TYPE= when creating new context table to avoid problems with MySQL versions before 4.1.\n- Fixed invalid reference to mergeDocumentMETATags in modResponse class.\n- [New feature] Allow custom error handler classes.\n- [New feature] Fine-grained configuration options for caching pages, database results, or disabling the cache altogether (see system settings starting with `cache.`). Turn the different caching options on/off or set a default time-to-live for those items being cached.\n- [New feature] Database result-set and xPDO object caching, with support for memcache, native-JSON object caching for high-performance AJAX requests.\n- [New feature] Configurable session management with default implementation configured for modSessionHandler, an xPDO-based implementation that stores sessions in a database, and allows a great deal of configurability, by site and/or context.\n- [New feature] Contexts allows a site to be organized into sub-sites, subdomains, etc, and override any system settings by context. The default contexts are 'web' and 'mgr' to support the legacy ideas of front-end and back-end session contexts.\n- Introducing the new MODx core built on top of xPDO; this will incrementally replace the entire existing codebase, but can co-exist until 1.0 release and provides about 90 to 95% legacy compatibility for existing tags and add-ons." ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [6, 321], "buggy_code_start_loc": [6, 2], "filenames": ["core/docs/changelog.txt", "core/model/phpthumb/modphpthumb.class.php"], "fixing_code_end_loc": [8, 345], "fixing_code_start_loc": [7, 2], "message": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF008510-C712-4018-9E0B-022CFA929190", "versionEndExcluding": null, "versionEndIncluding": "2.6.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68."}, {"lang": "es", "value": "MODX Revolution en versiones iguales o anteriores a la 2.6.4 contiene una vulnerabilidad de control de acceso incorrecto en el filtrado de par\u00e1metros user antes de pasarlos a la clase phpthumb, lo que puede resultar en la creaci\u00f3n de un archivo con un nombre de archivo y un contenido personalizados. Parece ser que este ataque puede ser explotado mediante una petici\u00f3n web. La vulnerabilidad parece haber sido solucionada en el commit con ID 06bc94257408f6a575de20ddb955aca505ef6e68."}], "evaluatorComment": null, "id": "CVE-2018-1000207", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-13T18:29:00.270", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory"], "url": "https://github.com/a2u/CVE-2018-1000207"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/pull/13979"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://rudnkh.me/posts/critical-vulnerability-in-modx-revolution-2-6-4"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-732"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, "type": "CWE-732"}
38
Determine whether the {function_name} code is vulnerable or not.
[ "This file shows the changes in recent releases of MODX. The most current release is usually the\ndevelopment release, and is only shown to give an idea of what's currently in the pipeline.", "MODX Revolution 2.7.0-pl (TBD)\n====================================", "- Filtering user parameters before passing them into phpthumb class #13979", "- Update phpThumb to 1.7.15-201806071234 #13938\n- Require minimal PHP version (in composer.json) #13939\n- Prefer ampersand replacement of the the translit class [#13931]\n- Add iconv_ascii transliteration [#13932]\n- Add set_sudo permission [#13807]\n- Log setlocale errors [#13878]\n- Various improvements regarding password generation and validation [#13923]\n- Make error.log location customizable [#13768]\n- Add system setting for partial resource cache clearing feature [#13588]\n- Prevent line-wrap in error log [#13843]\n- Add template icon for resources in search results in the uberbar [#13882]\n- Remove duplicate code of password generator and fix an issue with the empty value of password_generated_length setting [#13909]\n- Add ID number to manager pages (resources and elements) [#13914]\n- Add option to supply waitMsg on submit in MODX windows [#13915]\n- Show validation errors when setting a new user password [#13585]\n- Add CLI install script for use with composer create-project [#13790]\n- Allow extension packages to have an empty table_prefix [#13716]\n- Add wildcard support to form customization actions [#13775]\n- Make HTTPS server check accept any non-empty value [#13794]\n- Add ability to search by id on all objects in manager search [#13804]\n- Add automatic_template_assignment feature [#13700]\n- Media Browser optimizations [#13805]\n- Add \"Purge Old Versions\" button to the package version listing to clean up old versions [#12818]\n- New resource option \"Use current alias in alias path\" to allow hiding resources from the URI [#11153]\n- Make $modx->setDebug support E_LEVEL constants (e.g. E_NOTICE/E_ERROR) and fix setting debug to 1 not working [#12579]\n- Use stricter check for string type in resource tree to avoid uncaught error in edge cases [#13262]\n- Allow plugins OnDocFormRender to set templates with $resource->set('template', 3) [#13049]\n- Add \"filterPathSegment\" output filter to turn a string into url-safe string [#13699]\n- Make sure requests to containers without the container suffix are redirected to the right url with container suffix [#13142]\n- Ignore spaces in allowedExtensions properties and relevant system settings to ensure the right file types show up [#13702]\n- Add list of recent manager log entries to the Resource Overview page [#13734]\n- Prevent notices for undefined Smarty placeholders [#13748]\n- Remove some unused images [#13788]\n- Fix incorrect hex colors in TV input options description [#13776]\n- Change modResource.description column to text [#13802]", "MODX Revolution 2.6.4-pl (June 7, 2018)\n====================================\n- Fix sorting by access column in Template Access tab of Template Variable edit view [#13893]\n- Make sure category is not null before checking add_children permission when creating chunks [#13906]\n- Address various minor XSS issues in the manager [#13887]\n- Update xPDO to 2.7.0 to solve bug with getIterator and MODX Resource Group ACLs [#13889]\n- Update phpmailer from 5.2.21 to 5.2.26 to fix various security issues [#13886]", "MODX Revolution 2.6.3-pl (April, 19, 2018)\n====================================\n- Fix installation of transport packages with setup options [#13861]", "MODX Revolution 2.6.2-pl (March 30, 2018)\n====================================\n- Display context name and key in Context dropdown [#13839]\n- Only save properties modified from the default for an element in Property Sets [#13799]\n- Replace usages of each() to avoid deprecated warnings in PHP 7.2 [#13829]\n- Prevent adding ./ to filepath when in root of a mediasource [#13778]\n- Fix error with getonline processor on systems with only_full_group_by sql_mode [#13835]\n- Prevent logging errors for comments or empty tags [#13771]\n- Fix typo preventing verbose CURL option from being set in modRest [#13798]\n- Prevent http headers from being overwritten in modRest [#13797]\n- Fix sending messages to wrong recipients in message/create processor [#13796]\n- Stop sending too much data on package install request [#13813]\n- Add events permission to Administrator policy on new installs [#13830]\n- Remove max width from the tree sidebar [#13637]\n- Select the correct media source when editing a static element [#13750]\n- Fix the setup language being reset to English in the last step [#13611]\n- Fix incorrect view url after changing the resource url [#13768]\n- Fix silent fail on login without manager access [#12706]\n- Fix incorrect media source being used on image TVs when creating new resource in different context [#13609]", "MODX Revolution 2.6.1-pl (December 15, 2017)\n====================================\n- Increase efficiency of cache refresh on autopublish events [#13572]\n- Remove concatenated key from name field in Contexts grid [#13372]\n- Prevent infinite loop when a modSymLink refers to itself [#13710]\n- Get only unique template paths for manager controllers [#13717]\n- Ensure dashboard widget exists before calling methods on it [#13604]\n- Fix phpthumb issue in files tree and media browser [#13704]\n- Show correct Resource type icon in search results [#13705]\n- Allow callback if nothing is selected in MODx.browser [#13684]\n- Fix Flush Your Permissions top menu item [#13690]\n- Improve changelog display in package browser [#13677]\n- Revert behavior of image_width and image_height for media source images [#13672]\n- Fix CLI installation to properly detect MySQL server version [#13680]\n- Fix title format in various manager views [#13668]\n- Fix javascript issue on resources containing quotes [#13669]\n- Fix console error when editing resources with tv tab [#13683]\n- Fix invokeEvent call for new OnResourceCacheUpdate event [#13676]", "MODX Revolution 2.6.0-pl (November 1, 2017)\n====================================\n- Add top padding to .modx-alert and .modx-confirm classes [#13652]\n- Improve setUserGroups/addUsers methods [#13653]\n- Enable sorting by 'assigned' column in template variable grid [#13598]\n- Return better error message if group name already exists [#13600]\n- Hide empty template variable tabs in the resource panel [#13649]\n- Add .less, .scss, .sass and .css.map as default allowed upload file types [#13592]\n- Enable context setting overrides in modResource->cleanAlias() [#13622]\n- Add OPTIONS request method to modRestController [#13636]\n- Fix redirect when deleting elements [#13644]\n- Fix format of chunk title [#13643]\n- Prevent connector errors from invalid ctx parameter [#13627]\n- Fix processing of noncacheable elements inside cached [#13530]\n- Fix site_status issue when a session is not available [#13635]\n- Fix endless loop when error log is too big [#13632]\n- Fetch Lexicon lang and topic lists from database [#13599]\n- Add CSS class to TV containers [#13602]\n- Add OnResourceCacheUpdate event [#13590]\n- Add new Who's Online dashboard widget [#13545]\n- Additional SVG preview improvements [#13629]\n- Enable rendering of SVG previews in Media Browser [#13517]\n- Add stream upload support for binary files to modRestService [#13164]\n- Remove null-byte character check [#13581]\n- Add search/filtering to plugin event list [#13552]\n- Search improvements for user management [#13551]\n- Improve description of TemplateVariable Input Option Values [#13550]\n- Replace all hardcoded http versions by $_SERVER['SERVER_PROTOCOL'] [#13518]\n- Make searchbar accessible via assistive tech landmarks [#13437]\n- Make ContextResource optional in query for rebuilding contexts [#13360]\n- Reduce varchar and text index prefixes for utf8mb4 support in mysql [#13559]\n- Change new installs to create tables with InnoDB engine on mysql [#13462]\n- Fix set height of error log [#13566]\n- Reset user session token if it is set but value is empty [#13577]\n- Fix chmod feature on directories [#13580]\n- Fix resource tree ignoring hide_children_in_tree value [#13578]\n- Skip date format check when using resource quick update [#13534]\n- Fix ability to drag files more than once [#13533]\n- Fix permission check for updating user group settings [#13544]\n- Fix collapsing secondary buttons [#13558]\n- Add unique index for modTemplateVarResource values [#13535]\n- Fix media browser active state in tree [#13496]\n- Fix media browser tree refresh after creating a directory [#13501]\n- Prevent \"New User Group\" button being covered with long translations [#13555]\n- Add modx_media_sources_elements when a context is duplicated [#13529]\n- Remove resource template values when context is removed (cherry-pick) [#13525]\n- Fixed issue with incorrect signature during installing two packages with setup options (cherry-pick) [#13557]\n- Added loading error log only via ajax to avoiding blank page in case bad characters in log file [#13560]\n- Added DKIM attributes to PHPMailer [#13303]\n- Hide user group tree panel splitbar if center panel is hidden (cherry-pick) [#13520]\n- Added missing setting for primary user group during creating a new user [#13528]\n- Remove exposing of full path from error message when controller not found in the Manager [#13430]\n- Remove hardcoded modUser references in user processors [#13532]\n- Secondary button height fixes [#13543]\n- Add newNameField to modObjectDuplicateProcessor to correct error messages [#13521]\n- Added ability to duplicate a context from the contexts grid & while editing a context [#13540]\n- Honor the failed_login_attempts setting [#13516]\n- Added option to allow double encoding to htmlentities output modifier [#13325]\n- System events are now listed with their attached plugins [#13324]\n- Added ability to return custom error message via plugin when a user authenticates [#13204]\n- Create a new \"please wait\" windows on any package download instead of hide/show [#13506]\n- News & security feeds in the manager welcome page are now loaded using AJAX [#13507]\n- Added resource pagetitle & ID when deleting a resource [#13497]\n- Remove unused path_search and url_search processors in setup [#13433]\n- Fix logging an empty value in modUser->joinGroup() [#13445]\n- Fix featured flag in package listing not interpreting the string value [#13470]\n- Re-style the templated package provider thumbnail grid [#13274]\n- No addition on a JS string! [#13401]\n- Sessions are marked as staled after creating/updating/removing a user group/policy [#13311]\n- Clearing cache from the manager is now logged in manager actions [#13350]\n- Context sorting in trees is now enabled by default [#13356]\n- Add events for package install, uninstall, and remove [#12936]\n- Add setting to log when snippets are called that don't exist [#12984]\n- Added option to disable EVAL binding in TVs [#13224]\n- Allowing using keyboard modifiers to open some links in new tabs [#13103]\n- Pass properties to the OnRichTextBrowserInit event [#13110]\n- Add tag [^m^] to show used memory [#12981]\n- Add Delete button to chunk/snippet/plugins-window [#13245]\n- Add after(append) and before(prepend) output filters [#13021]\n- Add class_key and item filter to the Manager Log [#13005]\n- Change view_ permissions to edit_ permissions for elements in uberbar search [#13095]\n- Allow manually editing rank of contexts [#13097]\n- Pass the namespace to OnManagerPageInit event [#13104]\n- Add new line and spaces regex to input filter [#13115]\n- Add \"UserProfile events\" [#13153]\n- List empty as default template in system settings [#12975]\n- Add .x-form-display-field style [#12955]\n- Add the ability to generate custom manager \"top menus\" [#12554]\n- Replace dirname(dirname(__FILE__)) with dirname(__DIR__) [#13147]\n- Add User Group description to UserGroups grid (with row toggle) [#13130]\n- Add ExtJS Manager headers and descriptions components [#13118]\n- Made modX::addEventListener & modX::removeEventListener actually work\n- Correct email subscription form on help page [#13463]\n- Add ability to see changelog of extras before downloading the update [#13410]\n- Fix session_start error \"Session callback expects true/false\" on PHP 7 [#13041, #13073]\n- Prevent \"Call to member function get() on array\" error, caused by TinyMCE [#13085]\n- Prevent drag/dropping contexts when context_tree_sort is disabled [#13363]\n- Improve user messaging with an outbox and improved message listing [#13390]\n- Prevent dashboard breaking if a widget is missing a file [#13367]\n- Fix positioning of TVs on the first resource tab [#13318]\n- Prevent error on PHP 7 when using invalid output conditions [#13167]\n- Allow use of date/strftime output filter on date strings without strtotime output filter [#8161]\n- Make the save button available immediately when removing locks from the resource update page [#12028]\n- Add option to skip duplicating resources when duplicating a context [#13277]\n- Expand relative base paths in the file media source [#13295]\n- Added pagetitle of the resource that has been duplicating into the title of duplication window [#13475]\n- Fix incorrect pending changes warning when a resource was set to the empty template [#13483]\n- Add optional $byName attribute to modResource->joinGroup to force joining a numeric group [#4014]\n- Allow default TV values to use @BINDINGs [#3454]\n- Make sure log_target being empty defaults to FILE instead of ECHO [#7659]\n- Allow javascript handlers to be executed in the user-nav [#13094]\n- Make sure the scripts cache uses the right file permissions [#12677]\n- Add support for new_folder_permissions_cache and new_file_permissions_cache settings to change permissions on cache folders [#12677]\n- Add new modDirectory->getFiles() method to list files/folders in a directory [#13096]\n- Some modRest refactoring to clean up code style and doctypes [#13133]\n- Fix output filter handling of non-existent TV tags to be consistent with placeholders [#13203]\n- Automatically change to the resource tab that holds an error when encountering a validation error saving a resource [#13202]\n- Move OnFileManagerBeforeUpload event so it can also be used to prevent uploads or change file info [#13067]\n- Lower memory usage of duplicating contexts with lots of children [#13217]", "MODX Revolution 2.5.8-pl (TBD)\n====================================\n- Use pageSize from system settings for system settings grid [#13493]\n- Fix date format for created field of package in the package provider [#13509]\n- Add a mouseout listener to the 'Clear Filter' buttons across the manager [#13510]\n- Add view_template:true for the \"Content Editor\" access policy [#13508]\n- Refresh the parent (resource) node when creating the first children [#13499]\n- Refresh element in tree after changing name in element's panel [#13502]\n- Remove unused path_search and url_search processors\n- Fix logging an empty value\n- Update xPDO to fix issue with validation rules", "MODX Revolution 2.5.7-pl (April 20, 2017)\n====================================\n- Try all available methods when attempting to download transport packages [#13419]\n- Prevent stored XSS in UserGroup names and various other fields [#13418]\n- Prevent user/email enumeration in forgot password feature [#13408]\n- Prevent XSS cache poisoning via Host header [#13426]\n- Proper use of json_encode and error handling for outputArray() in processors [#13389]\n- Prevent reflected XSS in setup [#13424]\n- Fix local file inclusion vulnerability in setup action parameter [#13422]\n- Fix various local file inclusion preventions to also protect on windows [#13428]\n- Remove htaccess from allowed file types on new installations [#13423]\n- Prevent stored XSS in resource pagetitle [#13415]\n- Make search bar work as expected on Chrome & Firefox [#13405]", "MODX Revolution 2.5.6-pl (March 28, 2017)\n====================================\n- Enable Resource Group access column to be sorted [#12426]\n- Prevent warning from array_key_exists when aliasMap not available [#13297]\n- Fix broken images in File tree when media source above doc root [#13292]\n- Encode HTML in the template description to prevent potential XSS [#13290]\n- Use (but limit) setting for results per page in package management grid [#12518]\n- Added validation for min and max length of text TV configuration [#9039]\n- Allow value '0' for multi select TV items [#9492]\n- Fix \"undefined\" on package management breadcrumb when updating [#12567]\n- Reduce log level to INFO for links not found by modContext->makeUrl() [#13268]\n- Fix error in Firefox preventing using enter in the uberbar [#12714]\n- Fix error when deleting a file from a TV [#12417]\n- On new installs set base_help_url setting to the new docs subdomain [#13309]\n- Refresh resource tree and context grid on create and delete [#12495]\n- Only call generateContext once when saving a resource [#13347]\n- In get/setTVValue, consider numeric strings as ID instead of name [#12542]\n- Validate chmod input [#13352]\n- Prevent drag/drop of directories messing up directory structures [#13165]\n- Get rid of duplicate scrollbars in the help window [#12914]\n- Show proper error page when viewing an inaccessible symlink [#12380]\n- Avoid duplication of modLexiconEntry objects when updating context settings [#12823]\n- Fix system info's database tables tab on sqlsrv [#9854]\n- Add comment to config.core.php files that its contents are overwritten on update [#10299]\n- Fix double dots in the filename of downloaded static resources [#10267]\n- Fix duplicating resource children which are hidden from the tree [#13298]\n- Show proper error message when trying to rename a file/folder that already exists [#13256]\n- Fix missing caption when duplicating a TV via the Edit TV page [#13317]\n- Fix empty error popup when adding a usergroup to a media source without a policy [#12701]\n- Fix close button on resource overview page [#12822]\n- Hide database username, password and database name from advanced setup [#13090]\n- Fix \"Cannot read property 'style' of undefined\" error when resizing viewport after closing a modal [#13294]\n- Fix \"o.field is undefined\" error when checking a resource group [#13296]\n- Fix phpdoc for modAccessibleObject->checkPolicy [#13301]", "MODX Revolution 2.5.5-pl (February 8, 2017)\n====================================\n- Respect new_file_permissions setting when create/upload files in manager [#13246]\n- Escape regular expression special characters in last query string of a superboxselect [#13236]\n- Improve logging of bad links [#13268]\n- Fix a few Smarty variables not being defined [#13117]\n- Only load manager layout when the controller is not \"browser\" [#13135]\n- Add autoHeight in the Create/UpdateSetting window [#13220]\n- Address various potential security issues in setup [#13261]\n- Validate file extension when renaming/creating files in file browser [#13240]\n- Examples to rewrite all domains of one installation with/without www [#13249]\n- Update MODX Transport Provider to use SSL URL [#13260]\n- Add site name to the login title [#13254]\n- Fix File Unzip feature [#13223]\n- Fix truncating filename at space by downloading via filemanager [#13171]", "MODX Revolution 2.5.4-pl (January 3, 2017)\n====================================\n- Update xPDO to 2.5.3 release to avoid xPDOQuery class not found error", "MODX Revolution 2.5.3-pl (January 3, 2017)\n====================================\n- Fix listing packages on systems with non-utf8 locales [#13182]\n- Update PHPMailer to 5.2.21 for CVE-2016-10045 patch [#13229]\n- Access chunk array instead of chunk object instance [#13210]\n- Update PhpMailer to 5.2.19 to protect against RCE vulnerability [#13227]\n- Add various missing permission checks to processors [#13174]\n- Update xPDO to 2.5.2 release\n- Improve phpThumb InitializeTempDirSetting [#13151]\n- Validate Resources when dropped onto weblinks and symlinks [#13212]\n- Fix Resources not loading in the tree in sqlsrv [#12845]\n- More specific removal of critical settings in MODX.config [#13180]\n- Fix broken list of previously installed package versions [#13179]\n- Fix incorrect media source name on Files tab [#12596]\n- Update Font Awesome to 4.7.0\n- Remove placeholders from login screen to fix accessibility bug/confusing screenreading [#13186]", "MODX Revolution 2.5.2-pl (November 14, 2016)\n====================================\n- [SECURITY] Hide critical settings in MODx.config [#13170]\n- [SECURITY] Prevent local file inclusion/traversal/manipulation [#13177]\n- [SECURITY] Prevent path traversal in $modx->runProcessor [#13176]\n- [SECURITY] Prevent unauthenticated access to processors [#13175]\n- [SECURITY] Prevent path traversal in modConnectorResponse action param [#13173]\n- [SECURITY] Update xPDO to 2.5.1 release\n- Add security/login support for action based connector [#13158]\n- Make one single connector file possible [#13157]\n- Don't create a DirectoryIterator on non existing folders [#13127]\n- Fixing tvLabel output filter empty needle warning [#13138]\n- Fix session extension call using action based connector [#13146]\n- Select modTemplateVarTemplate.rank for MySQL 5.7 ONLY_FULL_GROUP_BY SQL Mode [#13098]\n- Fix new category option duplicating view of elements [#13137]\n- Consistency in error messages, based on error type [#13126]\n- Make sure things do not break when no valid json/empty string is returned OnMediaSourceGetProperties event [#13119]\n- Removed superfluous code in the manager \"gateway\" [#13120]\n- Set temporary directory for files processing in phpThumb [#13128]\n- Upgraded phpThumb to 1.7.14-201608101311 [#13125]\n- Force display errors during setup [#13107]\n- Added duplicating caption field for TVs [#13100]\n- Fix PHP warning if the response message is empty [#13111]\n- Removed duplicate element ID [#13105]", "MODX Revolution 2.5.1-pl (July 21, 2016)\n====================================\n- Preserve original behavior for 3PC RTE TVs [#13071]\n- Fix with of install button after text change [#13078]\n- Fix server port check in setup start script [#13037]\n- Update phpThumb to version 1.7.14 [#13039]\n- Show image preview in file tree for S3 media source [#13059]\n- Fix problem with S3 bucket names containing dots [#13031]\n- Add missing properties in modX class [#13035]\n- Fix pagination in the \"New event create\" dialog [#13062]\n- Fixing padding-top issue in MODx.Window [#13038]\n- Use sans-serif font for TV textareas [#13045]\n- Prevent reflected XSS in connector's JSONP support [#13051]\n- Fix a SQL injection [#13052]\n- Fix uberbar user search return invalid User ID [#13056]\n- Fix width of the install button [#13057]\n- Extended grunt build tasks [#13026]\n- Remove deprecated curl option [#13032]\n- Show resources marked as container with a folder icon in the tree, even if it has no children. [#13027]\n- Restore missing Duplicate buttons on weblinks and symlinks [#12910]\n- Fix changing labels via manager customisations on checkboxes [#12890]\n- Fix extracting the title if it contains newlines when importing HTML [#12937]\n- Fix code smell issues in modPhpThumb [#13022]\n- Prevent using double quotes in extended user fields and containers to prevent breaking the context menu [#13012]\n- Fix saving a resource if the pagetitle of the parent contains tags [#13017]\n- Fix JavaScript error when editing an extended user field that contains markup [#12841]\n- Increase the delay for opening top nav menu items to 0.5s to prevent misclicks [#12931]\n- Allow email addresses validated by the extjs email vtype to have longer TLDs [#12940]\n- Fix updating user settings [#12988]\n- Fixed permissions for new files [#13000]\n- Fix for 500 error after install using STRICT_TRANS_TABLES mode in mySQL [#13001]\n- Fixed typo in scss [#12993]\n- Remove all traces of manager HTML5 cache manifest [#12985]\n- Fix rare database connection setup error (new installs/advanced upgrades) [#12997]\n- Remove :first-of-type, reduce padding on container [#12973]\n- Fix problem with multiple placeholders in a system setting [#12692]\n- Set correct title to edit fc set [#12974]\n- Corrected $_lang array index and $_lang string typo [#12979]\n- Error 500 + installer fails when MYSQL Strict SQL Mode is ON [#12838]\n- Use rawurlencode in modparser [#12675]\n- Reference to values passed by reference got lost [#12951]\n- Add uri to mysql/modcontext.class.php [#12971]\n- Add missing viewport meta tag needed to enable the responsive manager [#12977]\n- Avoid empty manager theme [#12989]\n- Fix: expression is always true [#12956]\n- Make sure uberbar resource search respects ACLs [#12960]", "MODX Revolution 2.5.0-pl (April 21, 2016)\n====================================\n- Fix issue where site_start and default_template settings get the wrong ID on certain environments [#12959]\n- Replace hard-coded charset in Default template with MODX setting [#12916]", "MODX Revolution 2.5.0-rc2 (April 6, 2016)\n====================================\n- Set the leaf property to true instead of 1 [#12734]\n- Increase the space between the content and the logo areas in the base template [#12898]\n- Add missing preserve_menuindex setting [#12905]\n- Fix displaying categories in Package Manager\n- Update FileAPI to 2.0.20\n- Fixing partial import of content with UTF-8 chars inside [#12896]\n- Fix Media Browser when compress_js is enabled [#12899]\n- Restore backwards compatibility in updated Smarty [#12897]", "MODX Revolution 2.5.0-rc1 (February 3, 2016)\n====================================\n- Implement X-Powered-By header to send \"MODX Revolution\" on all requests [#12885]\n- Add cleanup script to remove legacy files during upgrades\n- Fix installed package list in package detail page when the package's name has spaces [#12870]\n- Add filter and search to the templates grind in TV panel [#12873]\n- Add typeahead for templates in resource panel [#12872]\n- Fix session warning on HHVM [#12868]\n- Add new stripmodxtags output filter [#12860]\n- Add new base template and resource content [#12855]\n- Fix re-definition of function mkdirs\n- Add `createdon` date field to modUser [#12581]\n- Ensure $restarted in templates/language.tpl always exists [#12847]\n- Update LinkedIn link description on Help page [#12851]\n- Fix undefined index in modOutputFilter->filter [#12856]\n- Add new output filter 'htmlspecial' [#12861]\n- compress_js no longer dynamically minifies javascript, instead it uses a prebuilt min.js for better performance [#12611]\n- Autoload third party packages when viewing manager actions [#11866]\n- Fix example core/ht.access file to properly lock down access to the core when used [#12503]\n- Fix selecting values on the tag TV input type [#12627]\n- Fix the insert element by drag & drop feature remembering properties it shouldn't [#12729]\n- Potential improved speed on certain pages thanks to processElementTags optimisation [#12717]\n- Fix checking for duplicate URIs when resources are unpublished [#12844]\n- Add border for grids\n- Change modResource Children to Composite relation [#12279]\n- Allow searching by Resource ID in Uberbar [#12783]\n- Add modParsedManagerController which can be used for developing CMPs with snippets and chunks [#12555]\n- Allow custom redirect method for each action button in action bar\n- Fire emptyTrash event after emptying recycle bin [#12673]\n- Add anonymous_sessions to allow session-less access for anonymous users [#12616]\n- Make the manager a lot more mobile friendly [#12776]\n- Fix .icon-coffee class to show a coffee cup, use .icon-coffeescript for the code icon [#12784]\n- Update Font Awesome to 4.5 (includes `icon-modx`!) [#12774]\n- Make use of the maximum available height when viewing the error log [#12746]\n- Improve usability of the tree by limiting click target for editing containers to the name [#12773]\n- Add published_resources and unpublished_resources to result of OnResourceAutoPublish event [#12747]\n- Improve keyboard navigation and screen reader support on the login screen [#12784]\n- Update PHPMailer to 5.2.14: https://github.com/PHPMailer/PHPMailer/releases/tag/v5.2.14 [#12808]\n- Update Smarty to 3.1.27: https://github.com/smarty-php/smarty/blob/v3.1.27/change_log.txt [#12807]\n- Allow uberbar labels and icons to be set server-side in extended search processors [#12749]\n- Add ability to unpack zip files in the file tree / media manager [#12775]\n- Ensure setup can continue if date.timezone is not set [#12738]\n- Make modPhpThumb class compatible with PHP7 [#12809]", "MODX Revolution 2.4.4-pl (April 5, 2016)\n====================================\n- Make sure only recipient can mark user messages read/unread [#12944]\n- Do not attempt to clean cache_db_handler if cache_db not enabled [#12942]\n- Fix broken output filters on undefined placeholders introduced by #12835 [#12906]", "MODX Revolution 2.4.3-pl (February 11, 2016)\n====================================\n- Various config_check improvements [#12628]\n- Fix error embedding images in modPhpMailer [#12645]\n- Prevent uncacheable elements from being cached in cacheable elements [#12835]\n- Fix the DocBlock comment for leaveGroup() [#12877]\n- Fix modX->getUser to force load settings when parameter is passed [#12840]\n- Fix issue with parent name not showing when creating a new resource under a parent [#12849]\n- Fix system settings pagination issue if default_per_page is > 30 [#12862]\n- Remove the 'Installed on' part of the language string.\n- Fix getOption call in modUser->getProfilePhoto\n- Sets correct responseType in the rest service for multiple packages via a single request [#12669]\n- Fix loading rich text editors on non-document resource types [#12632]\n- Fix dashboard and dashboard widget save button [#12711]\n- Fix failure message in Export processor [#12709]\n- Fix tree style for deactivated plugin [#12712]\n- Fix fatal error if user not found [#12772]\n- Fix warning generated by configcheck dashboard widget if safe_mode or open_basedir is enabled [#12745]\n- Include a random hash for core assets being loaded to refresh browser caches [#12700]\n- Fix fatal errors in the manager on PHP7 [#12741]\n- Fix \"Remember Me\" on the manager login [#12802]\n- Show message after triggering a URI refresh [#12800]", "MODX Revolution 2.4.2-pl (October 6, 2015)\n====================================\n- Fix emptying property sets on element save [#12580]\n- Different tree styles for unpublished + hidemenu [#12699]\n- Add patch for ExtJS Drag & Drop issue [#12617]\n- Fix initialization of modUserGroupSettingUpdateProcessor processor [#12678]\n- Add resource title in Manager Log for edited resources [#12589]\n- Update Font-Awesome to 4.4 [#12598]\n- Update setup to check the minimum supported PHP version [#12637]\n- Add hover effect to tree expand/collapse icon [#12664]\n- Fix not rendering output properties of custom TVs [#12635]\n- Fix image width and add transparency pattern [#12670]\n- Disable trash icon and set proper tooltip after removing resources [#12672]\n- Pass 0 as id of default property set instead of \"Default\" [#12674]", "MODX Revolution 2.4.1-pl (September 23, 2015)\n====================================\n- Update PHPMailer to v5.2.13\n- Make user grid in ACL view consistent with user group view\n- Update xPDO to 2.4.1-pl\n- Fix dropping elements in template [#12572]\n- On policy template update sync policies with policy template [#12654]\n- Restore backwards compatibility for addons interacting with modTransportProvider [#12633]", "MODX Revolution 2.4.0-pl (August 18, 2015)\n====================================\n- Preselect core namespace if it is available in namespace combo box [#12562]\n- Fix namespace and policy filter in namespace access grid [#12560]\n- Escape Site name in header\n- Fix double nocompress option in advanced install", "MODX Revolution 2.4.0-rc1 (August 12, 2015)\n====================================\n- Fix installing package dependencies when there are setup options [#12556]\n- Fix potential E_RECOVERABLE (and other) errors in package download [#12543]\n- Add missing return statement in the package download processor [#12539]\n- Allow comma-separated list of constraints in Form Customization [#11239]\n- Prevent firing OnDoc*Form* Events on the Resource Overview page [#11865]\n- Automatically select the setup language based on Accept Language headers [#12011]\n- Change the modUserProfile.country field to use ISO codes rather than localised country names [#12534]\n- Add ability to prefill certain resource values in OnDocFormRender [#12535]\n- Allow setup options in packages to execute javascript [#12298]\n- Allow pressing enter in text areas [#12524]\n- Make sure registered CSS/JS are loaded on deprecated manager controllers [#12529]\n- New setting manager_use_fullname will show the fullname of the logged in user, instead of the username [#12527]\n- Parse the forgot_login_email message using the parser, to allow lexicons or other tags in the email [#12266]\n- Show error message when grid autosave fails\n- Disable setup options button when dependencies are not met [#12531]\n- Add config check to make sure the core folder is not web accessible [#12504]\n- Add ability to search for resources by template in resource/search processor [#12268]\n- Add download() method to modFileHandler [#11371]\n- Remove unnecessary caching headers from the manager request [#12254]\n- Fix logout from manager in case of broken javascript [#12344]\n- Fix limited width of TV descriptions [#12494]\n- Convert usergroup tree to usergroup tree & grid in ACL page\n- Prevent dashboard widgets with no output to be displayed\n- Add a reference of executed modPlugin object in modSystemEvent\n- Add JSONP support to the modConnectorResponse\n- Travis-CI automated test suite\n- Enhance config check style & add check for min PHP version\n- Log login action\n- Log empty trash action\n- Prevent displaying packages without a name from package provider\n- Fix adding anonymous use group to ACL groups\n- Clean \"onAjaxException\" to remove full HTML document tag to avoid breaking manager\n- Target user menu wrapper to change \"sub menu direction\" instead of targeted IDs\n- Implement new use_frozen_parent_uris option to respect frozen parent URIs in generating child URIs\n- System Events Manager page\n- Anonymous username as System Setting\n- Prevent JS error when Media Source is not in the first combo store page\n- Add regexp validation into text TV\n- Various MySQL performance optimizations via new database indexes\n- Fix TV's output properties column name in get properties processor\n- Auto suggest setting key in contexts and users settings\n- Add namespace permissions\n- Added Property Set file and color input field\n- Added option to not submit the emptyText of a form field\n- Links in description for extras opens in new tabs\n- Added ability send to provider information about language\n- Fixing cancel button not actually closing the popup window\n- a11y enhancements\n- Added qtip for tree root nodes & media sources to display their description\n- Updated setting groupingConfig options to grid\n- Media browser improvements\n- Fixed import HTML unicode error\n- Added tvLabel output modified\n- Added user photo profile field to user panel\n- Added system settings to enable customization of the top bar navigation\n- Added modMenu.description as tooltip in menu tree\n- Added ability to customize media source icons\n- Added ability to edit a media source from the files tree\n- Added ability to customize context icons\n- Added rank parameter to modUser->joinGroup method\n- Added rank to categories\n- Fixed package browser tree\n- Added package dependencies\n- Added contentType=string option to modRestCurlClient service [#11279]\n- Added realtime resource alias generation [#11799]\n- Added saveObject and removeObject methods to create and update processors [#12345]\n- Improved error message styling in the manager [#12349]\n- Added new option to date TV to hide the time from the users [#12348]", "MODX Revolution 2.3.6-dev\n====================================\n- Unset modx.user.userGroups in leaveGroup [#12410]\n- Fix fatal error when the database password contains a quote [#12528]\n- Fix several \"language string not found\" errors [#12546, #12545]\n- Add ability to disable on the fly compression to traditional installs [#12486]\n- Fix output of [^p^] tag on certain locales [#12514]\n- Fix counting rank of dashboard widgets [#12437]\n- Prevent XSS in file create/update processors [#12513]\n- Fix checking modMenu permissions with the same action value [#12361, #12255]\n- Fix missing pagination on category dropdowns [#12469]\n- Setup Options window is now bigger and grows as needed [#12297]\n- Set request-specific cultureKey option dynamically [#12227]\n- Make sure object processors pass a generic $object alongside the $objectType-based variable [#12243]\n- Fix issue editing users when extended fields contain multibyte characters [#12484]\n- Limit the size of images in Image TVs to 400px [#12498]\n- Show MODX version and flavor as tooltip on the MODX logo [#12496]\n- Normalize thumbnail size for image TV\n- Set default background color for thumbs to WHITE instead of BLACK\n- Updated default uploadable file types, including SVG and TIFF [#12526]", "MODX Revolution 2.3.5-pl (June 25, 2015)\n====================================\n- Fix Account dropdown hover on small screens\n- Compile Sass with libsass\n- Update npm packages\n- Update and Relax bower packages\n- Fix D&D resource sort when auto_isfolder setting is enabled", "MODX Revolution 2.3.4-pl (June 23, 2015)\n====================================\n- Allow access via id or alias when request_method_strict is false\n- Fix resource caching in multiple contexts\n- Bypass aliasMap for preview urls in manager\n- Fix custom theme CSS\n- Add Element/Resource name to the Quick update window's title\n- Improve drag & drop resource sorting\n- Fix row edit in site schedule grid\n- Fix float value of input options\n- Correct permission for Contexts menu item to \"view_context\"\n- Show the template icons at the template tree section\n- Fix saving binary field when creating content type\n- Fix edit action for S3 media source\n- Prevent using Ext.getCmp() when not needed in resource tree\n- Improvement to news and security widget DNS check\n- Better modMenu management\n- Set media source config in RTE media browser\n- Don't count Resources hidden from tree as children\n- Hide the \"Forgot your login?\" link if allow_manager_login_forgot_password is set to false\n- Update logo on setup page\n- Remove unnecessary DIV from file TV tpl\n- Remove unnecessary DIV from image TV tpl\n- Remove resource locks correctly based on current user\n- Fix tooltip full viewport width\n- Update Font Awesome to version 4.3.0\n- Update bower to build css correctly", "MODX Revolution 2.3.3-pl (January 29, 2015)\n====================================\n- Add OnCacheUpdate event to refresh() method\n- Check for valid google.com DNS before trying to load feeds\n- Fix case of table_prefix and service_class in modX->_loadExtensionPackages()\n- Fixed showing RTE in all resource types\n- Fixed sorting in MODX browser\n- Fixed updating resources from recent resources in user's profile\n- Fixed duplicating user\n- Unset modx.user.userGroups in joinGroup()\n- Use window.location.search to populate MODx.request\n- Added option to delete property from Property Set using the UI\n- Fixed preserving locked attribute in elements after quick update\n- Allow copy&paste system information page\n- Fixed urlAbsolute path in media sources\n- Fixed column width grid head/content\n- Fixed connector's URL when getting media source list\n- Make syncsite checkbox a system setting\n- Added system setting for automatic/manual switching container property in resources\n- Fixed showing lock tree icon for locked resources\n- Fixed @INHERIT binding in TVs\n- Make FC profiles sortable by template\n- Removed limit to getnodes for menu items\n- Fixed error message and missed lexicon for create chunk\n- Fix timezone problem\n- Fix javascript error while revert to default new property\n- Hide Duplicate buttons from Resource panel when user don't have permissions\n- Fix Password tab visible in edit profile to users without permission\n- Remove C:\\fakepath\\ from filename when importing property sets\n- Fix unnecessary scrollbars in windows\n- Fix wrong error message for creating new namespace\n- Remove limit from modx-combo-category combobox\n- Improved generateContext method to be quicker\n- Fixed loading theme based styles on login screen\n- Fixed selecting the same file to upload again\n- Fixed removing plugin from an event via the Update plugin event window\n- Fixed autoredirect after creating user\n- Fix context settings remove and update from window\n- Fixed showing minLength and maxLength value in error msg for text TVs\n- Prevent $this->resourceArray['resource_groups'] from being undefined\n- Fixed disabling caching of a chunk's output\n- Fixed Duplicate resource button visibility\n- Updated memberof output filter to return integer\n- Fixed setting resource as it's own parent\n- Trim setting's key before saving\n- Sort plugin events by enabled\n- Restore permission for menu help\n- Fixed processor path in user panel\n- Move refreshURIs() call from clear cache to new menu item Refresh URIs\n- Fix uploading packages on Windows", "MODX Revolution 2.3.2-pl (October 21, 2014)\n====================================\n- Fixed issue with S3 buckets containing dots\n- Fixes issue with Form Customizations containing multiple constraints on TVs\n- Single-Select TVs now retain custom values in the dropdown select options\n- Fixed birthdate on 1970/01/01 resulting in false\n- Restores horizontal scrolling to the Resource tree [#11949]\n- Language simplification for context menu items\n- Fixed property set creation which allowed empty 'name'\n- Fix for arrow that pointed wrong way in collapse areas\n- Fixed rendering TVs to modx-resource-content by Manager customizations\n- Fix default category name when creating a new element instead of showing 0\n- Fix store load if init combobox value is 0\n- Display context name in combo box\n- Fixed elements search results icons\n- Removed listeners/actions on Media browser data view double click\n- Added visual indication in elements trees when an element is edited (active class)\n- Removed unused code in Resource Tree Panel\n- Enable path style on AWS driver if the bucket's name contains a dot\n- More use of 'manager_date_format' in the manager\n- Use FontAwesome checkbox icons instead of sprite images\n- Made MODx.combo.Browser Media Source defaulting to the defined default Media source instead of hard coded id \"1\"\n- Replace security/forms/set/export processor with a class based one and fix\n- Fixed issue where batch removing access policies was only allowed for \"core\" policies (instead of preventing deletion for core policies)\n- Updated alias length to 255 in ExtJS\n- Fix superbox selects in toolbars\n- Prevent combobox lists being taller than the screen, mainly from windows\n- Fix MODx.Ajax.request ot handle multiple concurrent requests\n- Fix loading default manager controller without changing the manager theme when the manager theme does not include the requested controller\n- Fix encoded htmlspecialchars in resource overview > cache output tab\n- Fix creation of folders in S3 media source root\n- Disable keyboard shortcut to focus the search bar\n- Updated \"far\" parameter to \"C\" (to provide correct thumbnails aspect ratio) in modfilemediasource\n- When using resource_tree_node_tooltip system setting, make sure the given field is not empty before displaying the quick tip\n- Updated welcome url for 2.3\n- User / User Group Settings update and delete fix\n- Fixed modx_user_group_settings table on SQLServer\n- Make sure modContext config is \"prepared\" before using makeUrl()\n- Have [[++server_port]] report the port number\n- Consider dev version lower than alpha\n- Handles \"site preview\" when default_context is not \"web\" context or when manager is on its own (sub)domain\n- Fixes missing Permissions tabs for anonymous User Group\n- Updated modPHPMailer to use getService instead of creating new instance of modError\n- Refresh context's name in tree after changing it\n- Use modx_browser_default_sort setting for sorting in RTE browser\n- Fix front-end user group comparison bug when assigning new user groups [#11399]\n- Prevent XSS via GET param for manager controller action [#11966]\n- Fix CRC icons in tree\n- Refresh/expand appropriate tree node when creating a resource using \"quick create\"\n- Limit property set name/description length\n- Added ability to update a namespace within a window\n- Use lexicon strings instead of hard coded ones in manager login form\n- Display an error when updating a user from grid with duplicate email address\n- Create new instance of console on every action with package manager\n- Reset addresses list on failure send\n- Fixed superboxselect close button in Safari\n- Fixed typo forcing empty calls to modError::addError() for all sent emails\n- Fixed issue with tree node \"jump\" on expand/collapse\n- Added some client side validation when creating a new user group\n- Fixed mimetype issue on s3 Media Source\n- Do not display setting modification date if no modification has been done [#11762]\n- Moved user groups access tabs within a single permissions tab [#11769]\n- Make use of FontAwesome for files icons [#11851]\n- Fixed issue where required field was not highlighted [#11826]\n- Updated NodeJS dependencies [#11827]\n- Removed limit on Media Sources in the tree panel [#11834]\n- File and directory sorting improvements, more natural and consistent [#10286]\n- Accessibility improvements for new checkbox / radios [#11772]", "MODX Revolution 2.3.1-pl (July 22, 2014)\n====================================\n- Make Gravatar optional (enabled by default)\n- Update logos, login and help view\n- Update base_help_url to be protocol relative\n- Fix login after a session expired [#11763]\n- Fix manager menus for sqlsrv driver [#11677]\n- Refactor validation of a connector being included [#11738]\n- Updated RSS security feed to be Revo specific [#9440]\n- Do not output modScript include result w/o explicit string return [#11705]\n- Move OnInitCulture event to parser service [#10366]\n- Fix password reset feature [#11725]\n- Adjust appearance of saving window for new design\n- Fix labels / TVs in custom FC tabs [#11758]\n- Fix hover-preview thumbnail border width in Files tree\n- Fix long category name overflow in vertical tabs [#11728]\n- Enable usernav menus for mobile devices\n- Update phpthumb release to v1.7.13 [#11742]\n- Fix pagination in Topic combobox [#11713]\n- Simplify Gravatar profile image fallback [#11716]\n- Correct duplicate method declarations in phpthumb class [#11700]", "MODX Revolution 2.3.0-pl (July 15, 2014)\n====================================\n- Respect automatic_alias regardless of friendly_urls\n- Prevent use of GET vars in login controller/processor\n- Restrict returnUrl in login processor to url of login context\n- Added drag/drop reordering of template variables on the templates TV grid [#11560]\n- Added ability to use conditional custom output modifiers [#11610]\n- Updated MagpieRSS Snoopy to 2.0.0\n- Add strftime as alias for date output filter [#11550]\n- Validate and sanitize _ctx placeholder used by ResourceManagerController\n- Fixed incorrect sorting by rank in TV grid on template create/update screen\n- Remove references to deprecated modX::getMicroTime()\n- Fix parent ResourceGroup inheritance on create\n- Preserve order of selected values in multiselect\n- Updated PHPMailer to v5.2.8\n- Updated phpThumb to 1.7.12-pre (current GitHub status)\n- Added resource_tree_node_name_fallback system setting\n- [#11297] Allow passing options to modRestCurlClient\n- Ease reuse of media sources panel\n- [#9245] Fix context menu position on custom resources that define a certain menu\n- Added OnResourceAutoPublish system event\n- Fix incorrect sorting by rank in TV grid on template create/update screen\n- Fixed Categories with a sub-category would always be shown in an Element's tree even if it didn't contain any elements of that type\n- Fix media source directive in TV when accessed from another context\n- List only user related resources in recently edited resources widget\n- Fixed colors/states not changing on subsequent database connection attempts in installer\n- Make ddGroups unique for resource, element and file tree\n- Fixed collapsing tree after quick creating an element\n- Add back Legacy modX.getFullTableName() method\n- Make OnFileManagerBeforeUpload event selectable\n- Added ability to define a default package provider via default_provider setting\n- Return nothing when toPlaceholder output filter is used\n- Added replace closing php tag for inline php dashboard widget\n- Fix to tv,chunk,snippet name validator per scottboryses observation\n- New manager theme\n- Move fax field near other telephone related fields\n- Option to disable CSS/JS compression during setup\n- Changed extension of JSON content type from .js to .json\n- Added modResource.isMember and modResource.getResourceGroupNames methods\n- Replaced uploaddialog with more modern multiuploaddialog\n- Added Other gender\n- Fixed events called in modResourceGroupCreateProcessor\n- Added dedicated page with media manager\n- Add icon/markup to modMenu items, allow new entries for topmenu and usermenu\n- An instance of modError added to modMail\n- Make sure connector responses return application/json content type\n- Removed hard coded \"index.php\" in manager assets\n- Preselect media source in static elements browser\n- Added ability to refresh a media source (tree)\n- Prevent duplication in context root if new_document_in_root != true\n- Sanitize filename when editing a file\n- Adds validateOldPassword flag to optionally skip passwordMatches() call\n- Make preview possible if session_enabled = 0\n- Improved widget of active users\n- Calling modUser->joinGroup sets rank to count(UserGroupMembers) instead of to 0\n- Call getNodesFormatted with parent property in modResourceSortProcessor\n- Hide back button during installation\n- Fixed regex for element names\n- Added system settings to change default action\n- Check for \"theme_path/js/layout.js\" before trying to load it\n- Clean modx->user on context init\n- Added shift modifier to tree click, that will open resource in a new window\n- Removing duplicate windows\n- Updated context setting's update window to appear as a create window\n- Load setting topic to allow 3PC components to use it for system setting translations\n- Allow filtering of namespace by request on lexicon page\n- Add proper validation for modSession id\n- Updated phpmailer class to 5.2.7\n- Fallback http_host to prevent cache issues under HTTP/1.0\n- Added ctx option to isloggedin/isnotloggedin output filters\n- Ensure opcache.revalidate_freq is set to 0 during setup\n- Clear menus cache on actions with menu\n- [#11123] Added \"success\":true to modProcessor response\n- [#11182] Fix issue where grid stores loaded only 20 records by default when pagination were disabled\n- [#828] handlePreview is called only if the deleted value changed\n- Update xPDO for additional SQL injection protection\n- [#11186][#11176][#9880][#2896][#5850] Disabled dirty check on save button in Resource's panel\n- Validate context key provided to modX::initialize()\n- [#11170] Added pdf to content type\n- [#675] Add upload functionality directly to package manager grid\n- [#703] Added OnElementNotFound system event\n- [#11149] Make sure hitting the close button does not trigger double prevent navigation warnings\n- Add refreshURIs call as part of clearing the site cache\n- Update parent field in Resource panel after drag and drop current resource\n- Check if template exissts before using it's icon in getNodes processor\n- Prevent content duplication when using [css|js|html]To[Head|Bottom]\n- [#11099] Removed C:\\fakepath\\ from filename during uploads\n- Fix path issue with phpthumb after 1.7.11-beta update\n- Prevent redirect of base_url when query string exists\n- Enable Template-based icons in Resource tree\n- Increase message_limit for ExtJS HttpStateProvider\n- Fix lexicon getList processor\n- Improve Confirm Navigation feature and make configurable\n- Confirm navigation when unsaved changes exist in resource panel\n- Fix deprecated returnValue to prevent confirm navigation alert\n- Fix xPDO->parseBindings bug triggering modDbRegisterMessage errors\n- Prevent processor property overwriting in modX::runProcessor()\n- Add open in new window action to middle mouse button click in trees\n- Preserve value types in modSystemEvent::output()\n- Prevent removal of user groups after validation fails\n- Remove extra dot in filename for Content Disposition attachment\n- Fix unescaped backslash in file and image TV\n- Remove cache clearing logic from system setting model\n- Update phpthumb to 1.7.11-beta to close security vulnerability\n- Add options and context filtering to modX::getTree()\n- Auto-resize modal window height to fit browser height\n- Add modSoftRemoveProcessor for marking records deleted\n- Ensure property not set when creating new property in Property Set\n- Implement auto-save on Content Types grid\n- Support PHP use statements in Snippets and Plugins\n- Add in/inarray conditional output filter\n- Add preg_quote to friendly_alias_word_delimiters characters\n- Do not prepend base_url when baseUrlRelative in modFileMediaSource\n- Add filterPathSegment() methods to modX and modResource\n- Remove check for children on Categories in Elements Tree\n- Allow Categories to have same name with different parents\n- Add case-insensitive contains/containsnot conditional output filters\n- Add modResource::clearCache() to clear cache for single Resource\n- Remove all dependency on mysql extension (deprecated in PHP >= 5.5)\n- Add extended field support and more to userinfo filter\n- [#9484] Add UserGroup Settings\n- [#10135] Fix output from multiple plugins OnSiteSettingsRender\n- Make path param optional in modFileMediaSource::getBases()\n- Clear register before calling clear cache\n- Add clear flag to modRequest::registerLogging()\n- Add modRegister::clear() method\n- Show custom xPDO class names in Manager Log\n- Fix context setting overrides in modX::_initContext()\n- Fix MODx.Console.onComplete when provider not set\n- Fix notice when resource not set in modX::sendForward()\n- [#9841] Add access to resource OnLoadWebPageCache\n- [#9072] Set upload_maxsize to php upload_max_filesize value on install\n- [#10146] Add embedded image support to modMail\n- [#9133] Fix various issues with Number TV\n- Fix visibility of Quick Edit independent of allowChildrenResources\n- [#8453] Add several File Management system events\n- [#7866] Add columns option to Checkbox TV\n- Add OnMODXInit event in modX::initialize()\n- Add name field to Contexts\n- Add preserve menuindex/alias options to Duplicate Context\n- Allow Namespace-based loading of custom TV files\n- Deprecate usage of modAction objects in favor of modNamespace base controller path", "MODX Revolution 2.2.10-pl (October 7, 2013)\n====================================\n- Increase modTransportPackage version columns range to smallint\n- [#10211] Fix parser state bug triggered by media sources\n- Fix loading modResource derivatives in class_key dropdown\n- [#9973] Prevent extended user classes being set to modUser\n- Upgrade xPDO to 2.2.9-pl\n- [#10182] Improve sanitization of processor_err_nf response", "MODX Revolution 2.2.9-pl (August 28, 2013)\n====================================\n- Avoid critical error when resource tree not initialized\n- Avoid suppressed warnings with ob_get_level()\n- Upgrade xPDO to 2.2.8-pl\n- [#10043] Fix class-loading LFI in registerLogging\n- [#6937] Fix Persistent/Reflected XSS in User Messaging\n- Set default error_handler_types to error_reporting()\n- Upgrade to ExtJS 3.4.1.1 and add ExtJS debug support\n- [#9976] Fix cross-context symlink caching\n- [#10093] Add create/update methods to S3 Media Sources\n- [#9902] Added error window when package download fails\n- [#10070] fix potential SQL injection vulnerability in modImport\n- [#9843] Added lang_topics field to create and update action window\n- [#10094] Defaults overwriting properties in ResourceCreateProcessor\n- [#10007] Fix parser logic when processing elements via API\n- [#10087] Avoid stat warnings with missing static sources\n- [#9809] Remove empty ULs in topmenu\n- [#7569] Add bottom border to collapsed panels\n- [#146] Also fire field change event on change event\n- Fix contextsAffected in resource/sort processor\n- [#9815] Improved manager redraw on browser resize\n- Fix clearcache timing issue with MODx.Console\n- Prevent accumulation of MODx.Console onMessage callbacks\n- Prevent session write errors from phpthumb cache\n- [#9964] Fix Import HTML to use context of parent\n- [#9916] Add TABLE to TRUNCATE command in flushSessions (SQLSRV)\n- [#9527] Fix password reset by user email\n- Fix login processor to use absolute url redirects for mgr\n- [#9826] Fix errant creation of Policy Templates", "MODX Revolution 2.2.8-pl (June 4, 2013)\n====================================\n- Prevent empty HTTP_MODAUTH from succeeding\n- [#9450] Prevent non-existent Context initialization\n- [#9896] Improve performance of modTemplateVar::getRenderDirectories()\n- [#9859] Prevent conditional output filter recursion\n- [#6138] Handle offline errors in RSS feeds\n- Refresh file tree after removing file\n- [#9946] Do not cache modResource::$_isForward\n- Force browser to root on Media Source change\n- Refresh file tree after root upload\n- Fix remove file from root if no folder selected\n- [#8877] Fix inline grid datefield icon\n- [#6945] Fix datefield icon in grid toolbars\n- [#9825] Revert width increase of file and image TVs\n- [#9901] Fix empty resourceMap in sqlsrv\n- [#9912] Fix length of modResource.uri index\n- [#9846] Fix incorrect parameter order passed to findResource\n- [#9814] Fix empty cross-context links using link tags", "MODX Revolution 2.2.7-pl (April 9, 2013)\n====================================\n- [#9634] Fix notices in system/settings/update processor\n- [#9768] Fix array merge in xPDOObject::getMany()\n- [#9773] Fix classKey errors viewing manager actions\n- [#9774] Prevent resource/unpublish on site_start\n- [#8312] Allow sorting users by blocked status\n- [#1] Allow Element duplication when editing\n- [#9237] Return object from ContextSetting create/update\n- [#8327] Don't close context menu on click\n- [#8980] Fix lexicon when updating user password\n- [#9258] List languages and topics alphabetically\n- [#9152] Use default_context for New Resource toolbar actions\n- [#8138] Fix Combo Settings not saving from update dialog\n- [#9571] Fix template/update always refreshing cache\n- [#9093] Make collapsed tree panel tab more visible\n- [#8859] Add button to refresh error log\n- [#9772] Fix deprecated value for CURLOPT_SSL_VERIFYHOST\n- [#9728] Fix empty create Dashboard Widget tab\n- [#9734] Fix save button state on Content Types grid\n- Fix resizing of error log textarea\n- [#9287] Enable save button when switching templates\n- [#9132] Refresh cache when enabling/disabling plugin\n- [#9690] Fix various issues with server_offset_time\n- [#9738] Prevent working context overriding user settings\n- Fix error getting MediaSource table classes on cached Resources\n- [#9368][#9437] Fix modProcessorResponse->isError()\n- [#9681] Allow country/getlist processor to work more than once\n- Fix Auto-Tag TV value sorting\n- Make caching the aliasMap optional to reduce memory usage\n- [#9672] Fix invalid ini_get call in modDbRegister\n- [#8489] Add compound index to modTemplateVarResource\n- [#9592] Iterate all inherited parent FC rules\n- Replace location redirects with MODx.loadPage proxy\n- Add MODx.beforeLoadPage event to modExt components\n- [#9143] Fix destructors in modExt components\n- Allow loading of modExt files asynchronously\n- [#9359] Report errors about unpublishing site_start to user\n- [#9197] Load RTE for SymLinks in manager\n- [#9364] Allow Unicode chars via modX::sanitizeString()\n- [#9631] Fix image preview with special chars in filename\n- [#9608] Remove connections data from MODx.config\n- Fix invalid ini boolean evaluation in config_check processor\n- Allow modX::getParser() to get an extended modParser instance\n- [#9524] Fix invalid context assignment in modX::switchContext()\n- [#9517] modPackageGetAttributeProcessor returning wrong PACKAGE_ACTION\n- [#9451] Add modx-combo-source as settings type\n- [#5515] MODx.Browser UX improvements\n- Increase width of file and image TVs\n- [#9282] Fix Minify errors when manager on different subdomain\n- Various Manager UI Fixes\n- [#6150] Fix issues with auto_publish when encountering invalid data\n- [#8936] Fix modTemplateVarRender::_loadLexiconTopics()\n- [#9257] Fix workspace/lexicon/getlist strict notice in PHP 5.4+\n- [#9339] Use Resource context_key in update processor when not specified\n- [#9212] Fix SQL syntax error in modTemplateVar->findPolicy()\n- [#9239] Make sure class_key is passed when switching templates\n- [#8101] Add support for httpOnly session cookies in PHP 5.2+\n- [#8420] Provide multi-node support to flock-independent file locking\n- [#8420] Remove LOCK_EX from flock-independent file locking method", "MODX Revolution 2.2.6-pl (December 3, 2012)\n====================================\n- [#9178] Use PHP time for valid check in modDbRegisterMessage::getValidMessages()\n- [#9165] Fix modError::hasError false positives when loaded via getService\n- [#9029] Remove modRequest->loadErrorHandler dependency in runProcessor\n- [#9156] Fix reload data for rendering multi-value TV types properly\n- [#7916] Fix Area functionality in Element Properties and Property Sets\n- [#9097] Fix leftbar tree toolbar resizing issues\n- Image optimization applied across distribution\n- [#9006] Fix ImageMagick which convert issue (PHP 5.3.2+)\n- [#9069] Remove math output filter\n- [#9080] Fix modX::stripTags() bug allowing script execution vulnerability\n- [#9007] Prevent MODx.Browser closing window when manager loaded in a new tab\n- [#8928] Error saving Resource with access-restricted TemplateVars\n- [#8978] Fix issue where change template was not fired due to onsave check overriding listener\n- [#9026] Prevent new Content Types from having binary checked", "MODX Revolution 2.2.5-pl (October 2, 2012)\n====================================\n- [#8753] Fix variable name in security/user/removemultiple processor\n- [#7654] Fix Update processor for ResourceGroup-restricted TVs\n- [#8196] Enable save button when combo selections are made\n- [#8186] Apply FC rules to Resources when changing Template\n- [#8790] Add ability to hide changed password in Update Profile\n- [#7551] Ensure static element path is not existing directory\n- [#7631] Fix duplicate beforeSave() in modObjectCreateProcessor::process()\n- [#8754] Change elementType to objectType in various processors\n- [#4430] Return 404 error if static resource target is invalid\n- [#8767] Fix MODx.panel.Resource to inherit config.url\n- [#8545] Add ability to localize ExtJS pre-loading message\n- [#8089] Fix ability to disable drag/drop in Resource tree\n- [#7661] Prevent changing template from unsetting Empty Cache\n- [#8620] Enable type-ahead on User and Country combos\n- [#8529] Prevent empty multi-value TVs from saving as '||'\n- [#8018] Fix file creation/editing on non-default Media Source\n- [#8556] Ensure regClient functions inject only once\n- CSS Style fixes for IE 9 (8, 7)\n- [#8560] Fix Context Admin ACL automation and use Context Policy\n- [#8432] Package Browser tree not reloading on Provider change\n- [#8482] RTE Output Option for TVs does not render on frontend\n- Add Quick Create/Update File feature in Files tab\n- [#6522] Retain page in Package Manager after install/upgrade\n- [#7630] Save modUserGroupMember rank upon creation\n- [#8420] Provide flock-independent file locking to avoid cache corruption\n- [#7498] Fix Media Source error reporting for file uploads\n- [#8299] Clear action_map (and menus) in system/action create/update processors\n- [#8168] Fix JS error when compress_js=Off and compress_js_groups=On\n- [#8341] Allow Resource data pages to be extended by CRCs\n- [#6695] Close sessions before min scripts terminate\n- [#6918] Fix importing access policy items always being checked\n- [#8329] Fix syncsite checkbox being unchecked by default on resource/create\n- [#8296] Fix function passed by reference in ellipsis output filter\n- Allow numeric value in modWebLink to redirect to Resource by id\n- [#7763] Fix additional Media Source path issues with static elements\n- [#8208] Fix modDbRegister->read() with include_keys option\n- Fix PropertySet switching from Element create/update controllers\n- [#7392] Get correct modMediaSource derivative in modParser->getElement()", "MODX Revolution 2.2.4-pl (June 14, 2012)\n====================================\n- [#8105], [#8051] Fix modFileHandler::sanitizePath() infinite recursion", "MODX Revolution 2.2.3-pl (June 13, 2012)\n====================================\n- Add setting to be able to set default context for new Resources\n- Pass http_host in provider requests\n- [#7933] Add friendly_urls_strict to optionally enable non-canonical redirects\n- [#6428] Fix help tooltip for new namespace window\n- [#8054] Fix transport provider verify processor consistency\n- [#8051] Added extra sanitization for modFileHandler.sanitizePath\n- [#7925] Fix error editing Resources in multi-context sites\n- [#8052] Fix empty()/isset() on hydrated fields/related objects\n- [#7798] Avoid E_NOTICE in PHP 5.4 from array_diff_assoc in xPDO::loadClass()\n- [#7796] Fix issue with phpthumb calling non-static methods statically\n- [#7764] Compress and default to open Resource Group access wizard in window\n- [#7762] Fix issue with add/decr output filter not adding 0 if 0 is passed\n- [#7793] Fix issue with saving a new media source access on user group edit screen\n- [#7712] Fix Resource quick update showing 2 checkboxes", "MODX Revolution 2.2.2-pl (May 2, 2012)\n====================================\n- Preserve GET parameters for container_suffix redirects\n- Allow custom FURLs via URL rewriting again\n- [#7427] Fix request_method_strict with FURLs off\n- Add ability to extend manager session by relogging in without leaving manager screen\n- Add better handling for AJAX exceptions, displaying AJAX errors\n- [#7649] Prevent E_NOTICE when using ago filter within <1sec difference\n- [#7568] Add JSON to default content types\n- [#7549] Open new window for phpinfo in system info page\n- [#7531] Add manager setting for first day of week in datepicker\n- Flip page title on manager pages for easier readability in browser tabs\n- [#7543] Add extra sanity checks for ellipsis output filter\n- CLI upgrades not loading MODX config data\n- [#7652] Sessionless contexts allowing anonymous access to unpublished resources\n- [#7610] User.sudo field invalid for sqlsrv\n- [#7619] Fix issue with TV FC rules and template constraints\n- [#7613] Add ability to duplicate user\n- [#7590] Fix lazy loading errors in xPDO layer\n- [#7608] Prevent ttl=0 set on modDbRegister from expiring immediately\n- Add wizard for User Group creation to speed up ACL workflow\n- Add Context policy for proper managing of access to non-mgr Contexts\n- Add wizard for Resource Group creation to speed up ACL workflow", "MODX Revolution 2.2.1-pl (April 3, 2012)\n====================================\n- Override modAccess->getOne for Principal aggregate\n- Add GroupPrincpal/UserPrincipal aggregates to modAccess\n- [#7387] Add New Category button to Element tree toolbar\n- [#7518] Fix issue that prevented absolute URLs in media-source bound TVs\n- [#7521] Allow filtering of usergroup by request on users page\n- Add assets_path field to modNamespace\n- [#7447] Change default root node name of Files tab to \"Media\" to prevent confusion when a non-default source is selected\n- Drop no-longer used, deprecated modAction.parent field\n- [#7503] Change Duplicate Values text to Duplicate Resource Values to clear up intended behavior\n- [#7499] Fix DOM ID issues with Quick Update when multiple windows are loaded\n- [#7500] Make consistent positioning of published checkbox in quick update and normal edit page\n- [#7491] Prevent Media Source dropdown from showing in MODx.Browser when loaded from a TV\n- [#6894] Move Import button on Access Policy and Access Policy Template grids to top toolbar\n- [#7391] Fix UI error causing resource group checkboxes on TV edit page to not render correctly\n- [#7481] Fix issue with reloading resource when changing templates and the context alias cache\n- Add \"sudo\" user attribute, which bypasses access permissions for said user; upgrade to 2.2.1 makes Super Users in Administrator group sudo users\n- [#7445] Fix issues with TVs not respecting Resource Groups limiting access\n- [#7446] Added extra checks to protect against parse errors with :then and :else output filters\n- [#7455] Fallback to TV name if caption not found when displaying TV inputs\n- [#7456] Fix for minify not modified status in fastcgi environments\n- [#6931] Workaround for template changing issue on servers that have misconfigured date_timzeone setting\n- [#6687] Fix duplicated OK buttons in MODx.Console in certain situations\n- [#6501] Fix SuperBoxSelect selections spanning multiple rows\n- [#6496] Fix quick edit modal windows for elements on smaller screens.\n- [#6864] Fix rare issue where primary group is not set for user, and custom dashboard for their group does not propagate\n- [#7011] Prevent infinite recursion error in modElement::isStaticSourceMutable\n- [#7333] Prevent error when id is undefined in resource edit controller\n- [#7364] Add setting to set default sort field of MODx.Browser view\n- [#7363] Check for this.stateful in MODx.tree.Tree::_saveState\n- Add missing index to modSession.access\n- [#7357] Prevent viewing of Profile if user does not have change_profile permission\n- [#7322] Fix issue where certain regions were not able to be hid via FC; clarified FC set labels\n- [#7362] Fix issue with conflicting FC Sets when User belongs to more than one User Group with a Set\n- Update to xPDO 2.2.3-pl\n- Prevent fatal error if invalid class_key is passed to Resource edit/create page\n- [#7052] Prevent username/host/dbname from being set as a system setting placeholder\n- [#3860] Fix session issue with modUser joinGroup/leaveGroup methods\n- [#7315] Standardize default sorting for User Group access grids\n- Fixed ellipsis filter to not cut off html tags in property\n- [#7326] Fix inability to unset a TV's Input Option Values field\n- [#7306] Sanity check for reload data for resource groups when changing template of new resource\n- [#7279] Handle edge case where processor classes might already be loaded with CRCs causing issues with runProcessor\n- Add dashboard name to dashboard title\n- [#3818] Add UI/processing to set response code for weblinks\n- [#7061] Prevent Static Element access to the core/config/ directory\n- [#7088] Tweak column widths for settings grids\n- [#7102] Improve memory_limit checks to properly check for values that are not formatted to PHP standards\n- [#7191] Fix invalid api doc link in link_tag_scheme description\n- [#7194] Fix issue where save button did not enable when reordering groups on user edit screen\n- [#3818] Change modWebLink default responseCode to 301\n- [#6611] Fix issue where MODx.Browser did not sort files by name by default\n- [#7070] Do not overwrite user changes in default media sources during upgrade process\n- [#7066] Allow search locally in Package Management if cURL is not installed\n- [#7063] Fix issue with retreiving Element Media Source cache data\n- [#7036] Fix issue with multiple grid store loading when searching\n- Allow for non-PHP Dashboard File Widgets that are just HTML files\n- [#6711] Fix issue with using MODx.Browser with file nodes and clicking loading edit page\n- [#6936] Add sanity check for database tables getlist processor if user did not grant SHOW TABLES permissions for sql\n- [#6942] Add missing resource duplicate ACL permission description lexicon string\n- [#6970] Reload error log page after clearing too large error log file\n- [#6956] Fix wrong groupname for OnMediaSourceDuplicate plugin event\n- [#7013] Fix issue where modUser->getUserGroupNames was buggy with non-self users\n- [#6960] Fix rendering issue when tree_root_id is set\n- [#7031] Ensure setting from addr in modMail sets return-path as well\n- [#7010] Add in rootId config option for MODx.Browser mgr widget\n- [#6874] Fix issue where duplicating a TV did not copy Media Source relationships correctly\n- [#6582] Fix clear cache checkbox persistence in Resource page when reloading via Template change\n- Add modX::getInstance() factory method\n- Allow for MODX tags within Media Source properties\n- [#5410] Add lock_ttl to System Settings for controlling ttl for resource locks\n- [#6575] Ensure that downloads of packages work behind proxies if allow_url_fopen is on\n- [#4879] Add language selector to login page\n- [#6826] Add activate/deactivate to context menu for Plugins in tree\n- [#6509] Fix minify issue in windows environments due to doc root pathing\n- Fix CSS for active tabs in mgr in IE\n- Prevent ENTER key from firing save in textareas in various modals\n- [#6712] Fix issue with Resource Group tree being limited to 10 groups\n- Bypass modSystemSetting->clearCache() when OPT_SETUP is true\n- Allow display of custom messages from form processors\n- Fix issue with extra slashes in URIs\n- Add ability to reload permissions for all authenticated users\n- [#6651] Add properties field and API methods for modResource\n- [#6613] Ensure page redirects if removing Element via tree that is currently being edited\n- [#6608] Fix search text in package management when doing empty search\n- [#6633] Ensure change password fieldset checkbox toggles dirty status for user form\n- [#6567] Fix Suhosin check to disable compress_js setting\n- [#6587] Fix issue with combobox rendering in editable grids by providing combocolumn xtype for proper data rendering\n- [#6583] Fix duplicate upload_files values\n- Prevent editing and deleting of core standard Roles", "MODX Revolution 2.2.0-pl2 (January 4, 2012)\n====================================\n- [#6564] Fix issue where save button on New Resource does not work due to JS DOM error\n- [#6470] Fix issue where Media Sources could not be protected on new installs only", "MODX Revolution 2.2.0-pl (January 4, 2012)\n====================================\n- [#6559] Fix issue with save btn on resources not enabling after template change\n- Better handling of dynamic lexicon topic adding and deprecated manager controllers\n- [#5905] Refactor new package versions to run ACTION_UPGRADE\n- [#6120] Improve static element behavior with immutable sources\n- [#6551] Fix issue where ID instead of name of Template showed on resource combo\n- [#6509] Fix minify issue when DOCUMENT_ROOT is a symlink\n- [#6546] Reposition setting grid filter dropdowns to clarify behavior\n- [#4146] Fix issue where Content Types were always binary when created\n- [#6470] Fix issue where Media Sources could not be protected due to missing reference in principal_targets setting\n- [#6520] Fix issue with Quick Create Resource and default settings\n- [#6510] Fix minify issue with virtual dirs inside the document root\n- [#5229] Fix issue where changing parent did not reload Resource edit page\n- [#6513] Better handling for large error.log files in mgr\n- [#6519] Ensure JS config gets working context config\n- [#6507] Add missing Media Source plugin events\n- [#6505] Remove htmlentities on date output filter\n- Allow PDO driver options to be defined in MODX config\n- [#6383] Add index.php to minify paths in mgr templates", "MODX Revolution 2.2.0-rc-3 (December 22, 2011)\n====================================\n- [#6247] Fix additional minify issues with CMP controllers in MODX_ASSETS_PATH\n- [#6428] Fix improperly designated tooltip and UI for create namespace window\n- Fix various regression issues with rename/delete files/directories in the Files tree\n- Ensure hideFiles property works for the files tree\n- [#6383] Add index.php to minify paths\n- Prevent TVs tab from showing in Resources if the only TVs are of type \"hidden\"\n- [#6413] Fix missing date_timezone setting description\n- [#6297] Prevent invalid characters in property set names\n- [#5997] Fix issue where components dirs were being created in assets with non-standard assets directory paths\n- Fix issue where resource ID was not being passed to FC rule checks\n- [#6417] Fix issue with modResource class_key being incorrectly set\n- Adjust modResponse contentType loading to allow overriding in custom resource classes\n- Fix critical timezone issue introduced for [#6077]", "MODX Revolution 2.2.0-rc-2 (December 16, 2011)\n====================================\n- [#3033] Add method to reload Context data in same request\n- [#6372] Add explicit resource_duplicate permission for duplicating a resource\n- [#6364] Fix incorrect lexicon reference in package versions grid\n- [#6365] Add manager_login_url_alternate setting which allows for setting a custom manager login URL\n- [#6077] Override PHP default timezone via System/Context Settings\n- [#5709] Fix issue where drag/drop in left trees did not work when package management was open\n- [#6153] Prevent enter key from sending Message when typing in messages page\n- [#6349] Properties can now belong to areas, and are grouped in grid by area\n- [#6344] Fix various pathing issues when drag/dropping files into content\n- [#5941] Add anonymous Load Only ACL when creating contexts\n- [#6247] Fix minify issues outside of $_SERVER['DOCUMENT_ROOT']\n- Improve skipFiles attribute for file media sources to allow MODX tags and hiding directories\n- [#6336] Fix error when updating property via window in media source properties grid\n- Fix various issues with permissions and ACLs on Media Sources\n- [#6306] Fix issue with close button always prompting changes made when changes may not have been made\n- [#6317] Fix issue with combo editor rendering in grids\n- [#6307] Save button now properly resets to disabled after save\n- [#6313] Fix issue with renaming content field label on derivative resource types\n- [#6084] Fix upgrade from 2.0.x releases\n- Add OnManagerPageBeforeRender and OnManagerPageAfterRender events\n- [#6207] Prevent overwriting static element file content when changing a static source\n- [#6255] Escape html tags in readme, license and changelog files for downloaded Packages\n- [#6096] Fix more issues with Resource reloading after changing a template by making the Resource Access grid local\n- [#5418] Add ability to export/import Access Policies\n- Add ability to import/export Policy Templates, as well as a base export/import processor class\n- [#6242] Actions on regular Resources break with Custom Resource Class extended fields\n- [#6096] Fix issue where reload token in Resource create would not allow save after validation\n- [#6238] Fix rendering issue when opening multiple quick create resource windows at once\n- Fix various issues with TV input and output renders by properly objectifying them into base abstract classes\n- [#5763] Allow for 3rd-level deep category nesting\n- [#6215] Fix issues with derivative resources and non-standard manager themes\n- [#6237] Add ability to sort users by active status in mgr grid\n- [#6197] Refresh old and new context caches when moving Resource\n- Update to xPDO 2.2.1-pl\n- [#6080] Fix revert to default properties on Source Properties grid\n- [#6204] Fix issue where multiple languages could not be loaded per page in the lexicon\n- [#6196] Ensure that MODx.Browser view updates when changing a media source from dropdown in tree\n- [#6198] Fix issue with saving user groups on a new user that caused duplicate role saving\n- [#6159] Implement OnBeforeUserActivate, OnUserActivate, OnBeforeUserDeactivate, and OnUserDeactivate events\n- [#6063] Add extra settings and checks to allow for better handling of manager CSS/JS minification on servers that do not allow DOCUMENT_ROOT access\n- [#6147] Fix element processors not firing proper events and passing wrong variables to plugins.\n- [#6060] Fix issue where resources were getting class_key of modResource rather than modDocument\n- [#6030] Fix issue where alt attribute was duplicated on image output renders\n- [#6122] Clarify text for removing a dashboard widget from a dashboard\n- [#6124] Fix issue where element associations of various elements were not saved in respective create processors\n- [#6145] Allow sorting of plugin events by enabled flag\n- [#6065] Fix issue with missing paths in certain environments for new installs in setup\n- Fix provider select window width in Chrome/Windows\n- [#6081] Fix issue in modFileMediaSource that prevented source properties from being read in certain processors\n- [#5141] Remove dependency for navbar.tpl in manager templates\n- [#5760] Fix memberof filter if user is not logged in\n- [#6090] Fix issue with removing Content Types in 2.2-rc1\n- [#6088] Fix issue with :date output filter and umlauts\n- [#6093] Make for easier translations of Element context menu items\n- [#6099] Fix incorrect index name for modWorkspace", "MODX Revolution 2.2.0-rc-1 (November 17, 2011)\n====================================\n- [#6019] Configure log_level, log_target, and debug via Settings\n- [#4798] Resource create/edit: Template can be switched without saving\n- Update to xPDO 2.2.0-pl\n- [#6039] Fix issue where Resources could be improperly dropped into the right tree in the Resource Groups screen\n- [#5715] Fix issue with resetting of header in Element panels\n- [#6025] Fix issue with renaming checkbox fields via Form Customization\n- [#5697] Fix issue with allow_multiple_emails in user creation\n- [#121] Add option for Elements to pre-process default property/property set values\n- [#6017],[#2774] Add more Permissions to Administrator policy for managing security functions\n- [#5064] Fix issue where access_permissions Permission was required for creating new users\n- Improve Package Management UI\n- Add modManagerController::addLexiconTopic for easier adding of lexicon topics dynamically within mgr controllers and dashboard widgets\n- [#6009] Add ability to hide left-hand trees when rendering a Dashboard\n- [#6007] Stop upgrade from overwriting session_cookie_path system setting\n- [#5998] Add \"Create File\" option for stream-based media sources\n- [#4794] Add custom Permissions for restricting creation of core derivative Resource Types\n- [#4958] Add Resource ID to node of Resource in Resource Groups tree\n- [#5434] Change manager page title to use site_name as prefix instead of MODX\n- [#4875] Add ability to download file from Files tree\n- [#5997] Fix issue where in advanced installs with moved web path, assets directory is improperly created\n- [#5990] Fix issue where content types were not listable in Resource dropdowns\n- [#232] Enable option to render target URL for WebLinks\n- [#5963] Fix issue with Static Elements and their Source being None\n- [#5936] Fix issue where Quick Update Resource was too high on smaller screens\n- Fix issue with phpThumb and zoom crop\n- [#5983] Fix adding/updating a provider window duplicating \"username\" field.[#5948] Ensure that menu item for Change Profile is added on build\n- [#5985] Fix updating a provider not showing username\n- [#5978] [ReUp] [#5978] Fix missing fields/tabs in actions XML causing issues with form customization on resource/create\n- [#5938] Optimize modResource->getTVValue() using parser source cache when available\n- [#5973] Prevent empty user groups being loaded for anonymous users\n- [#5962] Fix phptype in modContextResource.resource field definition\n- [#5050], [#5366], [#5781] Various xPDO Database Caching Fixes (xPDO 2.2.0-rc2)\n- [#4830] Prevent removal of Content Types that are in use\n- [#5293] Prevent drag/drop from Resource Group tree to Resource tree in Resource Group page\n- [#4433] Validate paths in setup for trailing slash\n- [#564], [#4506] Make Workspace path portable by allowing path setting replacements\n- [#5086] Fix issues with Package Management when open_basedir is in effect\n- [#4947] Adjust ensuring of admin access to context to only needed policies\n- [#5078] Have default resource field context settings, such as default_template, respected in Quick create\n- [#5909] Allow blank extensions in Add Content Type window\n- [#5931] Fix code that prevents easy renaming of assets directory with package management\n- [#5841] Properly color active state for tabs in mgr ui\n- [#3287] Fix issue with dob User field in editing panel in mgr\n- [#5060], [#5043] Fix issue with openTo and TVs for MODx.Browser\n- [#3396] Allow MODX_API_MODE in mgr context\n- [#4230] Add ODF and OOXML to default uploadable file types setting\n- [#5315] Use automatic_alias behavior when updating site_start regardless of setting\n- [#3535] Fix issue with tree_default_sort not being respected on the resource tree\n- [#5892] Add for default_media_source setting for specifying the default media source for a site\n- [#5896] Make console window always closable\n- [#5757] Allow text in grids to be selectable\n- [#5471] Add publishing options to Duplicate Resource window\n- [#5879] Ensure html tags are stripped on titles in the Resource edit view\n- [#5855] Ensure if no parents are specified, resourcelist input option works as expected\n- [#5852] Fix issue where input options are wiped on quick update TV\n- Add showNone option to source/getlist processor\n- [#5619] Enable modElements to store content in external files\n- [#5856] Implement ability for derivative Resource types to have their own translatable name\n- [#4726] Implement server-side state provider for modExt to fix size problems with cookies\n- [#5860] Fix FC SQL error when user is in no groups\n- [#5843] Add required asterisk to required Element fields\n- [#5723] Add Media Source tab to User Group Access screen\n- Change \"Cancel\" references to \"Close\" for clarity\n- [#4566] Fix online users manager dashboard widget grid\n- [#5809] Change \"Remove\" to \"Delete\" where appropriate to clarify language\n- Refactor processors to be class-based\n- [#90] 301 Redirect id method requests when request_method_strict is not enabled\n- [#90], [#5676] Improvements to strict routing with friendly_urls\n- [#5323] Add system events for moving Resources in and out of Resource Groups\n- [#4610] Add locale system setting for setting locale in MODX\n- Add HTML5 local caching as a toggleable option for manager ui\n- [#5788] Fix content not output to browser until after shutdown function\n- [#5777] Fix validation of TV names against Resource field names\n- Add ability to install and upgrade MODX from command line\n- [#5745] Ensure all core passwords are not transmitted through MODx.config JS array\n- [#4304] Add default_content_type Setting for setting the default Content Type for Resources\n- [#2735] Ensure menu permissions are checked for mgr action if action has menu associated\n- [#4606] Clarify connectors language in setup\n- [#5561] Add search toolbar to packages grid\n- [#5587] Fix issue with dashboard widgets and caching\n- [#5453] Add ability to disable forgot password on manager login screen\n- Add batch remove to Namespaces grid\n- [#5671] Add :toPlaceholder, :cssToHead, :htmlToHead, :htmlToBottom, :jsToHead, :jsToBottom output filters\n- Add delete user button to user editing page toolbar\n- [#5542] Add ability to drag/drop files and folders in the Files tab\n- [#5665] Remove console.log debug references in JS\n- Add Media Sources, which allow abstraction of file management in MODX\n- [#2737] Centralize logic for changing Context of modResource Children\n- [#5068] Move token check for new resources below error validation in processor to prevent bogus duplicate resource issue\n- [#4945] Remove weblink content maxlength restriction\n- [#5270] Enable container drag 'n drop in Extended Fields tree\n- [#4790] Add support for comment tag token, e.g. [[- comments here]]\n- [#5539] Add back in compress_css/js for allowing toggling of js/css compression in manager\n- [#5556] Enable connection pooling with master/slave support\n- [#5499] Ensure modFile create returns boolean\n- [#5501] Add sanity checks on FC rules renameTab and hideField\n- [#5505] Fix issue with dropdowns in Fx5\n- Enable modTag elements to accept property sets\n- Enable modElement->getPropertySet() to merge @propertyset in name with property set specified in setName parameter\n- Allow modParser->getElement() method to accept @propertySet in name parameter\n- Prevent modParser->parsePropertyString() from trimming all backticks at beginning and end of string\n- Improve parser efficiency by returning results of nested tags if elementOutput is null|false\n- [#5392] Fix bug where policy template descriptions were not translated\n- [#5377] Fix modParser->isProcessingTag() bug preventing filtering on placeholder tags\n- Pass content by reference to OnParseDocument event\n- Add message_key and json message_format option to system/registry/register/send processor\n- Allow raw messages to be returned from system/registry/register/read processor\n- Add include_keys option to modRegister implementations\n- [#5336] Prefix non-core actions in the MODx.action JS object with their namespace\n- Avoid setting description to null in element/propertyset/create processor\n- Improve modX->logManagerAction to avoid attempts to insert NULL values\n- Accept null options in modHashing->__construct()\n- [#4607], [#3463] Add rank field for contexts to allow custom sorting in tree, fix issues with context/resource dragging and dropping and ensure context name validation rules are consistent\n- Improve UI of User's groups to allow for assigning ranks to User Groups for a User\n- Add Custom Dashboards and Dashboard Widgets\n- [#4871] Fix Access Permissions not being copied when duplicating a context\n- [#4382] Forgot Manager Password now lookups using username to prevent issues when the 'allow_multiple_emails' system setting is enabled\n- Fix rendering of combo boxes in element properties\n- Add ability to select Primary User Group for User\n- [#4637] Fix RTE checkbox not saving correctly when using Quick Create Resource\n- [#5268] Add search toolbar for Resource tree\n- [#4080] Add Content Type and Content Disposition to Quick Create/Update Resource\n- [#5250] Add check for cURL in Package Management\n- [#5204] Add search by parent to mgr search page\n- Added much better handling for custom resource classes; deprecated custom_resource_classes setting\n- [#4601] Ensure children of protected Resources inherit by default their parent's Resource Groups in create UI\n- [#4016] Update description text in grid when adding/updating element properties without need for page reload\n- [#2860] Fix 'Sent On' date when viewing an expanded message\n- [#4984] Ensure tree highlighting of currently edited resource/element/file works consistently\n- [#2638] When updating an element's category, ensure old treenode is removed\n- [#5139] Fix issues with MODx.Browser and file/image TVs in other contexts\n- [#4958] Add IDs to Resource Groups in RG tree\n- Add ability to rename Resource Groups\n- [#5185] Improve core package already extracted validation for upgrades\n- Update xPDO and regenerate schema to get new maps of derivative classes\n- [#5195] Change TV value fields from TEXT to MEDIUMTEXT (mysql)\n- [#5141] Add ability to override specific controllers/templates in a custom manager theme w/ fallback to default\n- Add modResource::getControllerPath method for better abstraction of derivative resource types\n- Add show_in_tree and hide_children_in_tree fields to modResource for better support with custom Resource types\n- Abstract all manager controllers to classes to improve usability, testing and creation of controllers", "MODX Revolution 2.1.3-pl (July 21, 2011)\n====================================\n- [#5295] Fix parents input option for Resource List TV when 0 is specified\n- [#5190] Fix includeParent input option in Resource List TV\n- [#5222] Fix nested cacheable tags being skipped in non-cacheable tags\n- Fix delegateView recursion in Resource controllers on Windows\n- [#3966] Fix double slash issue in file paths when dragging into resource content from the Files tree\n- [#4565] Fix issue with Resource tree sorting\n- [#5026] Make directory tree in MODx.Browser instance launched from Files tab consistent with other instances of MODx.Browser\n- [#4960] Prevent method declaration error for modPHPMailer::reset()\n- [#3716] Ensure consistent handling of combo-boolean property values in the database\n- [#4586] Improve number detection for Radio and Checkbox TV values\n- [#5196] Unset uri_override when duplicating creates a duplicate uri", "MODX Revolution 2.1.2-pl (July 6, 2011)\n====================================\n- Fix issue with modUser::getSettings pulling a deprecated alias\n- Update to xPDO v2.1.5-pl\n- Implement DocBlox for documentation generation\n- [#5168] Fix element and tv permission queries for SQL Server\n- [#5146] Fix issue with Firefox and button widths\n- [#5164] Fix possible issue if a TV is stranded to a non-existent category\n- Update ExtJS to 3.4.0\n- Set a default session_gc_maxlifetime to avoid frequent logout issues\n- Refresh modExt trees when drag operations fail\n- [#4918] Limit save permission check to modified nodes in resource/sort processor\n- [#5065] Fix 404 error with cross-context symlinks when cacheable\n- [#5152] Fix nested non-cacheable tags from being cached in modResource->_content\n- [#5145] Update config check on dashboard to show correct core path if core is moved\n- [#5112] Add Settings for adjusting behavior of Context sorting in Resources tree\n- [#4341] Properly clarify text and function on Resource Tree context menu options for view/preview\n- [#5046] Fix issue where parent could not be changed for new resources via Form Customization\n- [#5112] Sort contexts by name ascending in the Resources tree\n- [#5102] Fix error removing older transport package versions\n- [#4940] Fix issue where CMPs that did not use ExtJS could not scroll\n- [#5097] Ensure browser toolbar button does not show when MODx.Browser is already open\n- [#4953] Improve modx.console.js to avoid message loss\n- [#4836] Make sure modFileRegister sorts messages before reading\n- [#5087] Fix issue where class_key was not respected when using Add Another in UI\n- [#260] Implement on-the-fly compression for css/js in manager\n- [#3464] Set xPDOTransport::ACTION_UPGRADE for already installed packages\n- [#4955] Package management actions refresh packages cache partition\n- [#5071] (SqlSrv) fix/refactor Plugin Events getList processor\n- [#2870] Change internalKey default value to NULL\n- [#5072] Add missing primary key index to modEvent\n- [#5005] Fix incorrect label on introtext field in weblink panel\n- Remove session_cookie_lifetime variable when logging out of context\n- Remove legacy SESSION variables and dependencies\n- [#4703] Remove user settings when logging out of a Context\n- [#2566] Improve tv output render url to take resource pagetitle when using resourcelist TV type\n- [#5020] Improve per page field on grids to handle ENTER key\n- [#5021] Improve modUser::joinGroup to check to see if user is already in group\n- [#5025] Fix issue where duplicate resource window did not show duplicate children option\n- [#5007] Only create Lexicon Entries for Settings if they are specified\n- [#5006] Fix issue with updating a policy template with no permissions\n- [#5001] Fix issue with modauth, wctx and RTE browser", "MODX Revolution 2.1.1-pl (June 1, 2011)\n====================================\n- Make modauth calculation independent of session_id\n- Ensure login/logout processors do not add Contexts with empty keys\n- [#3145] Ensure mail_smtp_pass and proxy_password System Settings use password xtype\n- [#4360] Show current context name on MODx.Browser window for reference\n- [#4881] Fix issue where modx-combo-language was missing from system setting editing screen\n- [#4896] Fix issue where New Category window is not cleared on each load\n- [#4934] Fix missing lexicon load call in package download processor\n- [#4927] Gray out disabled plugins in elements tree, italicize locked elements\n- [#4921] Ensure Category names are not ever capitalized when displayed as tabs\n- [#4865] Fix PDO error caused by missing charset for new MySQL installs on PHP 5.3.6+\n- Improve modSessionHandler and add Settings for advanced configuration\n- [#4750] Fix various issues with duplicating Resources, such as new name not prefixed and incorrect menuindex\n- [#4910] Fix bug where ResourceList TV type could not be marked as required\n- [#4915] Fix UI glitch when creating both an Access Policy and its Template on same page load\n- [#4916] Fix issue where cache clear checkbox was always being cleared on template save\n- [#4884] Remove PHP4 constructor on modRegister\n- Harden connector CSRF security by tying user session modauth to prevent hijacking of session if modauth is known\n- [#4863] Fix issue where template changing causes unintended alias\n- [#4854] Fix bug that caused update/rename file to be missing in Files tree context menu\n- [#4851] Improve safe_mode check in setup to check for non-boolean values\n- [#4856] Fix issue with MODx.Panel instances that have no textfields, causing scrollbar issues\n- Fix issue where MODX version was not being sent to provider during package update\n- [#4850] Fix issue with MODx.Window instances that have no textfields", "MODX Revolution 2.1.0-pl (May 24, 2011)\n====================================\n- [#4818] Fix SqlSrv query errors related to TVs\n- Add modX->$sourceCache data to cached Resources\n- Fix loading of cached Resource content and processed flag\n- Fix caching of empty policies for Resources\n- Fix modSessionHandler->write() cache flag if cache_db_session is not enabled\n- Update xPDO to v2.1.4-pl for cache_db bug fixes and improvements\n- [#4832] Fix issue with moving resource parent to root\n- [#4827] Make sure editing a file sends the working context along\n- Fix erroneous call to OnDocUnpublished event that should be OnDocUnPublished\n- [#4796] fix New Resource page heading during typing of page title\n- Add Usergroup filter to users grid\n- [#4785] Fix preview of files in left tree in non-standard contexts with absolute filemanager_ settings\n- [#4473] Add other common file types to upload_files system setting\n- [#4539] Fix issue with stretching of quick update chunk and small screen resolutions\n- Automatically focus cursor to first textfield on windows in mgr\n- [#4738] Fix issue with inconsistent results in resourcelist TV\n- [#4441] Fix FC issue when parent is constraint and trying to change default template\n- [#4764] Fix issue with timestamp display on manager log page\n- [#4680] Fix javascript error when typing Template name\n- [#4681] Fix path issue which was causing 404 errors in the manager, IE 7-9\n- [#4439] Add parentheses to list of disallowed password characters in installer\n- [#4669] Fix button target size to make it more responsive to most clicks\n- [#4625] Fix sizes of buttons and submit inputs in installer - IE 8 and 9\n- [#4617] Fix custom values not being shown on Context Installation page during Advanced Upgrade\n- [#4605] modX->switchContext() now checks load permission via Context ACLs\n- [#4595] Fix display of modified/accessed times on Edit File page\n- [#4594] Fix last login time displayed in Info block of Manager welcome page\n- [#4470] Fix frozen URI not displayed when editing resource\n- [#4572] Fix installer error log filenames (characters not allowed in Windows filenames)\n- [#4585] Fix database connection processors in advanced upgrade\n- Update xPDO to v2.1.3-pl\n- [#4567] Remove calls to xPDO->log() in xPDOCacheManager->writeFile()\n- [#4557] Minor fixes on Installer Options screen for Traditional package\n- [#4556] Fix js error on Welcome screen of Traditional package's installer\n- [#4076] Fix Edit/Quick Update context menu items in protected categories\n- Fix Context Access query broken in RC4 changes for #4502", "MODX Revolution 2.1.0-rc-4 (April 29, 2011)\n====================================\n- [#4543] Fix preview URLs when FURLs are turned Off\n- [#4537] Trigger refreshURIs when related settings are modified\n- Have modAccess*::loadAttributes() check access_*_enabled settings\n- [#4502] Enable custom targets in modUser->loadAttributes()\n- [#3692] Add policy checks for new_document_in_root and add_children to resource/sort processor\n- [#4526] Additional fixes for output filters on placeholders\n- [#4504] Ensure UserGroup ACLs are deleted along with UserGroups\n- [#4507] Fix usergroup description not being set when created\n- Change modResource->isDuplicateAlias() to return id of duplicate Resource\n- [#4495] Add duplicate URI check to resource/publish action\n- [#3857] Fix placeholder processing when output filters applied\n- [#4362] Fix path issues with Static Resources and base_urls of /\n- [#4074] Require list permission on Context for Resource searches\n- [#4439] Do not allow invalid characters in username / password\n- [#4485] Fix issue with scrolling on drag/drop Element Properties window in small resolutions\n- [#4352] Fix failedlogincount / user blocking logic in login processor\n- [#4373] Fix issue with htmltag TV output render and empty values\n- [#4374] Fix issue with updating files in the edit file page\n- [#4024] Fix issue with LocalProperty grids not rendering list type properties display values correctly\n- [#4400] Trim whitespace from Namespace paths when adding/updating them\n- [#4434] Fix issue with edit panel on contexts\n- [#4372] Fix View button not getting URI change after Save Resource (all Resource types)\n- [#4369] Ensure Save button is active after Template change on Weblink, Symlink, Static Resource\n- [#4471] Set Resource alias properly on update\n- [#4469] Guard against inadvertent creation of duplicate New Resources\n- Add options to configure cache file writing attempts when exclusive locks fail\n- [#4464] Prevent unnecessary TV queries on uncached Resources\n- [#4422] Fix problems updating Boolean settings (System, Context, User)\n- [#4453] Fix File Browser when paths contain \"n_\"\n- [#4447] Fix ACL grid in Edit Context view\n- [#4438] Fix error logging to custom log targets defined by array\n- [#4399] Fix IE8 javascript error on Resource and Element update pages", "MODX Revolution 2.1.0-rc-3 (April 11, 2011)\n====================================\n- Fix invalid merge retained in master branch from 2.1.0-rc-1\n- Fix modResource::save() to refresh uri if isfolder field is dirty.", "MODX Revolution 2.1.0-rc-2 (April 11, 2011)\n====================================\n- Refresh resource tree if resource's parent has changed\n- [#4327] Fix bug with auto-publishing\n- Fix positioning of right panel in mgr UI to make tree/nav static and isolated from scrolling of right panel\n- Make alias required field in resource/create processor when friendly_urls is on but automatic_alias is off\n- [#4280] Fix issue where transport package could not be removed if transport files were removed\n- [#4281] Utilize modX::sourceCache in modParser::processElement()\n- Fix issues with Namespace grid related to context menus and search\n- [#4257] Fix issue where context menus did not show in Contexts grid\n- [#4288] Fix issue with resource preview context menu\n- [#4279] Fix undefined collResources notice with empty Contexts\n- [#3119] Fix modResource->getAliasPath() to use id if set\n- Upgrade MagpieRSS to 0.72 to fix issues with atom feeds\n- [#3623] Fix TemplateVarTemplate foreign key definition in modTemplate\n- Replace specific references to MySQL with more general language\n- [#4185] Change modx logo in mgr to new logo\n- [#4217] Add rank field to modUserGroupMember table\n- [#4271] Highlight currently editing Resource on tree\n- Fix issue with image/file TV and uploading in MODx.Browser when using a custom basePath TV\n- [#4270] Fix issue where images could not be removed when using a custom basePath TV\n- Add User Group related events\n- [#4260] Change title tag in mgr UI to reflect current page\n- [#4256] Add caption field to Quick Create/Update TV\n- [#4261] Change keyboard save shortcut to CTRL+S\n- [#4262] Ensure that FC rules htmlencode their tab/field labels\n- [#4243] Ensure that files that are read-only do not show save button; fix file tree opening\n- [#4244] Add backwards compatibility for Element properties of list type with older indexes\n- [#4236] Fix bug in Template combo that hid category name\n- Improve compression of images in mgr to reduce load times and core transport zip size\n- [#4232] Fix Output Options being ignored in TVs in 2.1.0-rc1\n- Add options to allow ACL queries to be disabled for Contexts, Categories, and Resource Groups\n- [#3941] Fix issue where Resource TV values were not copied when duplicating a Context\n- [#4202] Fix issues with file/image TVs urls/paths when using modx path placeholders\n- Fix sorting/display bugs on UserGroup ACL grids, add grouping for better visibility\n- [#4175] Add modRequest->getClientIp() for better IP handling\n- [#4217] Add rank field to modUserGroup\n- Update version to 2.1.0-rc-2\n- [#4173] Fix issues with math-related output filters and floats\n- [#4205] Ensure old modxcms.com provider is removed after change to modx.com provider\n- [#4220] Fix modX::makeUrl() when friendly_urls not enabled\n- [#4207] Fix issues with checkboxes and Form Customization rules\n- [#4013] Fix modX::_log() to pass target to parent::_log() properly", "MODX Revolution 2.1.0-rc-1 (March 28, 2011)\n====================================", "- Fix issue with properties and i18n in Element properties and in drag/drop box\n- [#4146] Fix issue where new Content Types were always created as Binary\n- [#291] Add principal_targets setting to allow custom ACLs to be loaded by MODX Principals/Users\n- [#99] Allow SymLinks/modX->sendForward() to forward to Resources in external Contexts\n- [#4147] Changing ContentType extension in grid not refreshing URIs\n- [#3967] Fix issue with running user create/update processors more than once in a session\n- [#3542] Hide Template Variables tab on Resource create/update pages if no TVs are present\n- [#788] FC Rules for TVs now display distinctly for create or update\n- [#1118] Add more help for User fields in manager editing page\n- [#2578] Fix issues with manager log view page where sorting was off and grid was not sortable\n- Fix issue where user-created FC tabs were not removable from a Set\n- [#4096] Fix Package Management archive issue when using mapped Windows drives\n- [#3785] Add category filter and search box to TV grid on Template panel\n- [#65] Make locked Resources be read-only rather than unviewable\n- Improve Package Management to show changelog, more supports information in package browser\n- [#4120] Fix issue where TV sort order is reset on Quick Update\n- [#4115] Fix issue with modPhpThumb and filenames with + signs\n- [#2719] Fix reset behavior on autotag/tag TV inputs\n- [#3586] Adjust improper text on Content Types page\n- [#2652] Fix issue where Element could be drag/dropped onto another Element in tree\n- Add ability to select a blank value for ResourceList TV input type\n- [#54] Fix issues with phpThumb and DOCUMENT_ROOT by adding a custom phpthumb_document_root System Setting\n- [#4122] Fix order of execution of validation and plugin events for Element processors\n- [#4105] Add Spanish translation\n- Refactor duplicate alias checks into duplicate URI checks\n- Cleanup deprecated code in Resource templates\n- [#3765] Ensure entries editedon values are set when editing a Lexicon Entry\n- Update ExtJS to 3.3.1\n- [#4073] Add session_name, session_cookie_path, session_cookie_domain as System Settings with blank default values\n- [#4077] Add resource_quick_create and resource_quick_update Permissions to restrict access to Quick actions on Resource tree\n- [#4050] Add tree_show_resource_ids and tree_show_element_ids Permissions to show/hide IDs of Resources/Elements in tree panels\n- Add username field to modTransportProvider, and send it and UUID to providers during transmissions\n- [#3641] Add base URL for Help links in manager for easier management and customization of URLs\n- [#3552] Fix issue causing list-xtype properties to be swapped when using drag/drop into field functionality\n- [#4069] Ensure that you cannot delete the last User in the Administrator user group\n- Add fix for ie9 to get tree nodes to work properly\n- Prevent Category ACL queries on Elements if no entries for current context\n- [#2601] Improve text and drag/drop for weblink/symlink content fields\n- [#3636] Fix issue with empty values on options in list/dropdown/checkbox/radio TVs\n- [#4024] Fix issue with display value not always showing for list properties in element property grid\n- [#4056], [#4041] Add xtype password, template, user, usergroup, etc to available xtypes for System Settings\n- [#3350] Improvements to bugfix for PHP bug 53632\n- [#4054] Improve select binding to be able to use Resource fields via placeholders\n- [#142] Add modResource.setTVValue API method\n- [#4021] Add system setting to allow setting of a custom favicon for the manager\n- [#3589] Fix issue with Static Resource paths when using custom filemanager_path\n- [#4040] Fix issue where Users were always created as active in mgr UI\n- [#4043] Enable drag/drop of users and groups in User Group tree\n- [#4052] Fix issues with element property import and invalid characters causing freezing in UI\n- [#4042] Fix issue in phpThumb base class preventing far property from working\n- [#4049] Add resource_tree_node_tooltip for controlling field in Resource Tree tooltip\n- [#3511], [#2964], [#3601] Fix issues regarding form customization and Templates by removing ajax loading of TVs in Resource panels\n- Consolidate JS for derivative Resource panels to allow to inherit from main Resource panel\n- Add context param to modx.getParentIds\n- [#3754] Ensure Resources can not have their parent set as one of their descendants\n- Add context param to modX.getChildIds\n- [#3612] Improve CDATA filter to not add spaces at beginning or end\n- [#3764] Add delete to actionbar on Resource edit panel\n- [#3585] Add description field to modUserGroup\n- [#3020] Improve trees to expand node on click if no href target is set for tree node\n- [#4006] Show children count rather than IDs on categories in element tree to lessen id ambiguity\n- Fix issue where Quick Create was not respecting unchecked setting checkboxes\n- [#3673] Add \"Save and Close\" button to quick update windows\n- [#3970] Ensure extension is lowercased before checking for allowed status when uploading files\n- [#3920] Ensure modPHPMailer resets replyTo and custom header fields\n- Add UI for managing Resource uri and uri_override fields\n- Remove all deprecated methods and variables scheduled for removal in next minor release\n- Change modxcms.com references to modx.com\n- [#3898] Prevent any non-integer being set in ?a= in mgr interface\n- [#3926] Ensure security/user/create processor can take in a class_key parameter to set class_key for SSO\n- Improve user processors event handling to allow for better SSO integration that can stop save/remove/update\n- Refactor password reset not to send password hash as activation key\n- [#325] Allow configurable user password hashing with PBKDF2 default implementation\n- [#3111] Fix bug causing unnecessary writes to Resource cache files\n- Update xPDO to v2.1.1-pl2\n- Add modResource.uri_override to allow a uri to be manually set and locked per Resource\n- [#3111] Add modResource.uri field to allow context maps to be regenerated in a single query\n- [#3859] Remove redundant check for php bug\n- [#3858] Fix javascript errors from FC hideField rule\n- [#2812] Add link_tag_scheme to define default scheme for makeUrl() call in modLinkTag\n- [#3111] Remove resourceListing, documentListing, and documentMap from context cache\n- [#3111] Cache refactoring with proper file locking, partitioning, and multiple format support\n- [#3111] Update xPDO to release 2.1.0-pl for cache improvements\n- [#3740] Add proxy support to modTransportPackage.class.php\n- [#3693] Fix reversed content-disposition logic on static resources\n- [#3427] Fix issue where User Settings were not respected with filemanager_path/url\n- [#3702] Ensure file/image TVs can have files drag/dropped onto them\n- [#3465] Add sanity check for non-object to log call in modAccessibleObject::_loadInstance\n- [#3615] Fix issue with modx->user->getResourceGroups, set resource groups in \"modx.user.{$id}.resourceGroups\" session key\n- [#3568] Fix double error->failure reference in resource/create processor\n- [#3425] MODx.Browser now loads directory of TV's current value on load\n- [#3481], [#3571], [#3304], [#3569] Fix issue with filemanager_path in non-web contexts\n- [#3009] Add ability to assign TVs to specific directories and base paths, limit file extensions shown\n- [#2679] Add Input Options to TVs, allowing TV inputs to be customized and tweaked", "MODX Revolution 2.0.7-pl (January 14, 2011)\n====================================\n- [#3472] Fix issue due to tree impr that prevented element saving success response\n- Improve loading of mgr pages by preventing trees from rendering until activated\n- [#3205] FC fixes: Ensure Resource Content field can have values set/renamed, that rules on create respect template, and that default values on create are set\n- [#3165] Fix issue where resource/updatefromgrid processor was missing published value if user does not have publish permission\n- [#2] Fix issue in user extended fields where subkeys in 2 separate containers DOM IDs conflict and prevent editing\n- [#3422], [#3374], [#3197] Fix issue with filemanager_url and Image/File TVs and their relative end result URLs\n- [#3201], [#177] Add modResource.leaveGroup, modTemplate.hasTemplateVar, modTemplateVar.hasTemplate\n- [#3350] Fix for PHP bug: http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/\n- [#3326] Fix issue where TV radio/cb options with value of 0 couldnt be selected\n- [#3329] Fix edit and cancel buttons on view resource page\n- [#3329] Clarify Preview link on Resource action toolbar to be more correct \"View\"\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run\n- Introduce pdo_sqlsrv support\n- Add database_dsn to config\n- Update xPDO to release 2.1.0-pl", "MODX Revolution 2.0.6-pl2 (January 6, 2011)\n====================================\n- [#3350] Fix for PHP bug: http://bugs.php.net/bug.php?id=53632\n- [#3347] Fix issue where renaming a file broke the browsing of directory tree\n- Fix issue where FC tvDefault rules, regardless of active state, are always run", "MODX Revolution 2.0.6-pl (December 20, 2010)\n====================================\n- [#3143] Fix lexicon grid search to respond to enter key\n- [#3144] Fix issue with reset password and @ being stripped\n- [#3142] Ensure whitespace is stripped from tags in tag/autotag TV types\n- [#3118] Ensure defaults are set in resource/create processor if values are not sent\n- [#3105] Improve memory_limit check in setup to accept integer values from PHP instances\n- [#3106] Add sanity check to resource create/update processors to disallow invalid Resource Group ID references\n- [#3038] Fix problems with filemanager_path settings and absolute URLs in image TV values\n- [#3039] Add symlink_merge_fields setting to disable modSymLink merge behavior\n- [#3103] Alter modSession data field to store more than 64Kb\n- [#3091] Add missing specific dom ID to profile change password panel\n- [#3096] Fix issue with exporting default properties not in a set from an element\n- [#3099] Fix FC rules to respect class_key constraints\n- [#3097] Fix extension_packages to support modx path placeholders, as well as new serviceClass and serviceName parameters\n- [#3085] Ensure Files tree only refreshes active node when creating/updating a file/dir\n- Improve the Permission dropdown and add window in AP Template page\n- [#3083] Fix Form Customization issue when Resource has a blank Template\n- [#3082] Fix Form Customization issue where cacheable and ID fields not able to be hidden/altered\n- [#3034] Fix error creating Resources in Contexts other than web\n- Fix issue with incorrect active permission total in Access Policy grid\n- [#3023] Fix issue where topmenu did not respect manager_language\n- [#3080] Fix missing placeholder in error message when attempting to create a duplicate Element\n- Add new header image to match new site\n- [#3078] Fix issue with htmltag TV widget properties when using = in its value\n- [#3079] Ensure GPC vars are not sent into $scriptProperties array in $modx->runProcessor\n- [#2983] Add sanity check to prevent plugins from firing if disabled (redundancy)\n- [#3057] Fix issue where parent change causes fail to save in UI\n- [#3076] Fix bug where manager returnUrl was not working due to [#2918] fix\n- [#3059] Ensure createdby is set on resource creation\n- [#3041] Fix missing lexicon entry in resource processors\n- [#3043] Fix invalid 200 response header on sendError()", "MODX Revolution 2.0.5-pl (December 8th, 2010)\n====================================\n- Change remove() to removePackage() in modTransportPackage\n- Fix issue with package setup-options attribute not loading forms\n- [#2932] Fix redirect issue after setup and on manager login page caused by [#2918]\n- [#2931] Fix issue where FC rules weren't applying if no UserGroup was set in a Profile\n- Ensure non-Resource FC rules are removed on upgrade\n- [#2918] Address XSS vuln in manager login that allows JS injection\n- Fix issue where // is stripped from filemanager_url http address\n- [#2902] Fix issue where Administrator policy ACLs in non-Administrator groups couldnt be edited\n- [#2915] Ensure UserGroups restriction is enforced in FC Profiles\n- Fix bug when editing FC profiles from a grid, issue where UserGroup wasn't respected\n- Ensure radio TV values still can select if default value is 0\n- [#2869] Fix issue with parent display text in Resource panel\n- [#2892] Fix problem creating folders on filesystem from file manager and browser\n- [#22] Allow SymLinks metadata to override target Resource metadata\n- Cache Resource ACL Policies with the Resource\n- [#2888] Fix problem with elementCache in modX::sendForward()\n- [#2610] Allow Elements to be created under a Category when a Category Policy is in effect\n- [#2869] Standardize initial parent combo value text on Resource edit page\n- [#2736] Colon character \":\" added to default FURL Alias Character Restriction Pattern\n- [#2889] Ensure that a new Resource gets an alias generated if auto_alias is On\n- [#2837] Ensure element properties import escapes <> and provide better error checking\n- [#2886] Ensure SimpleXML and XMLWriter extensions are installed when using FC Set import/export\n- [#2882] Add hidemenu_default setting for setting default hide from menus on Resources\n- Fix issue with derivative Resource types and FC rules\n- [#2858] Extra sanity checks to ensure md5 pw is never sent across get/getlist processors for Users, even if user has access level\n- [#6] Fix issue with RTL text in nodes in Resource tree\n- [#2873] Fix relativity of image urls in drag/drop and TVs when using various filemanager_path/url settings\n- [#2878] Ensure resource panel is marked dirty when drag/dropping into TV\n- [#2828] Fix issue with incorrect content field name for FC rules\n- [#2863] Fix order of execution issues with FC rules and default values\n- [#2874] Enhance User blockedafter/blockeduntil fields to accept time as well as date values\n- [#2529] Fix automatic publish/unpublish\n- Adjust FC rule ranks to properly account for prior FC rules that may affect FC constraints\n- Update xPDO to 2.0.0-pl release\n- [#2661] Fix Template getList processor to respect authority\n- [#313] Fix header error with binary modStaticResource downloads\n- [#206] Fix session bug with opcode caching systems like APC, WinCache, eAccelerator\n- [#2846] Add tag syntax to description hover text for resource fields\n- [#2849] Add ability to drag/drop onto TV fields\n- [#2848] Fix issue with file edit and base paths\n- [#2802] Ensure Category tab is hidden when all TVs are hidden in that Category\n- [#2779] Added Content Editor policy to default list of policies\n- [#2819] Fix bug in FC rules where parent constraint was not traversing up tree to inherit parents\n- [#2744] Fix bug with empty template and TV values\n- [#2841] Fix bug with File Edit page and modFileHandler reference\n- [#2839] Fix bug with failed login count not being updated\n- Add ability to view permissions inherited when viewing an ACL row in a grid\n- [#2834] Fix issue where constraint class was not set on new FC rules\n- [#2819] Fix issue with FC rules and execution order due to setting default templates, constraints\n- [#2830] Permit ability to change FC Set Template when editing a FC Set\n- [#2827] Fix issues related to FC upgrade with Rules with comma-separated names, differing constraints, and template setting\n- Fix issue related to #2625 with deferred tabpanel rendering that caused unpublishing when using Quick Update/Create\n- [#2825] Append idx to each item DOM id when using HTML tag tv output widget\n- [#2823] Add missing lexicon entry for TV output type\n- [#2817] Reorder System top menu for easier navigation\n- [#2820] Add DOM id to Profile page tabs\n- [#2814] Add longtitle, description, template to Quick Update/Create\n- [#2789] Add check to make sure safe_mode is off in setup\n- [#2565] Improve Quick Create/Update Resource to move settings into tab rather than fieldset\n- [#2807] Add tree_default_sort System Setting for configuring the default sort setting for the Resource tree\n- [#2803] Fix css issue with portal blocks on manager dashboard in Fx\n- Add new Form Customization UI, including Form Customization Profiles and Sets; much easier editing of FC rules\n- Fix issue with modInstallSmarty constructor due to Smarty upgrade\n- [#2799] Remove ext3 debug files to save space\n- [#2801] Fix bug with checkbox tvs without specified value options\n- Upgrade Smarty to 3.0.4\n- [#2782] Add changelog to Package View page\n- [#2782] Add ability to view changelog when installing a package via the \"changelog\" package attribute (similar to readme)\n- [#2770] Ensure email TV input type validates email\n- [#2776] Fix issue where context settings grid was not filterable\n- [#2790] Ensure \"number\" TV types restrict input to numbers only\n- [#2730] Fix rendering issue with policy template/group grids\n- [#2794] Allow TV URL output render to handle values that are straight Resource IDs\n- [#2741] Fix bug where Resource Group associations were not copied when duplicating a Resource\n- [#2746] Fix bug where email was sent in registration email rather than username\n- [#2733] Fix bug where Template Var associations were not copied when duplicating a Template\n- [#2742] Fix deprecated evtid reference in plugin duplicate processor\n- Fix various bugs with context settings and wctx param\n- Fix bug where modX::getDocumentChildrenTVars ignores docsort parameter\n- [#2743] Connectors using wrong permissions with processors\n- [#2758] Add modProcessorResponse class to better handle processor responses and error messages\n- [#2758] Add $modx->runProcessor($action,$scriptProperties,$options) to better handle processor execution; deprecated $modx->executeProcessor\n- [#84] Make distribution name available in manager\n- [#2666] Prevent sendRedirect() from preserving request parameters unless specified\n- [#2721] Fixed issue with per page items in MODx.grid.Grid that was incorrectly handling int value\n- [#2691] Fixed issue with duplicate aliases when duplicating a Resource\n- [#2506] Flag properties as dirty when importing from a file on properties grid\n- [#2592] Prevent cache files from being allowed in upload_files setting\n- Improved areas dropdown filter to include number of settings that have that area\n- [#2694] Fixed positioning and scrollbar issue in Fx with success status message on save\n- Added setting clear_cache_refresh_trees that allows you to toggle whether the trees refresh on site cache clear; defaults to false\n- [#2709] Fixed bug where Object-Template policies were unavailable to certain grids\n- [#2597] Fixed bug where Context Setting xtype and area are reset on grid save\n- Upgraded extension_packages setting to JSON for more options with packages and easier editing in Extras scripts\n- Fixed bugs relating to using filemanager_path in a separate context, as well as other bugs with context-specific settings in mgr\n- [#2496] Fixed bug that prevented icon from resetting when dragging Resources into a new parent\n- [#713] Prevent children resources from being prefixed with \"Duplicate of\" when duplicating a resource unless explicitly told to do so\n- [#2581] Fixed bug with resourcelist TV input type to handle resources from multiple contexts\n- [#2518] Added delay to allow FC rules to load before RTEs load to allow RTE TVs to be moved\n- [#2611] Added workaround for ExtJS bug with checkboxes/radios and an inputValue of string 0 that would prevent toggling\n- [#2512] Have remove setup/ dir checked by default if not using Git version of MODx\n- [#2699] Fixed loading issues with help panel on slow connections\n- [#2701] Fixed issue where description did not show until refresh when adding a new Permission to an Access Policy Template\n- [#2695] Postfixed Template to names of Access Policy Templates for clarity\n- [#2700] Fixed bug with Access Policy Template editor that reset values on save\n- [#2690] Renamed Administrator Access Policy Template Group to Admin\n- [#2563] Fixed chmod action on directories from File Tree\n- [#2693] Properly sort country indicies to properly display in dropdowns\n- [#2562] Added confirm dialog and success response for emptying recycle bin\n- [#2634] Ensured context key is changed when changing parent of a Resource via Edit Resource page if context is different for new parent\n- [#2631] Fixed issue when drag/dropping categories onto other categories in Element tree\n- [#2659] Fixed issue where action buttons were overlapping tabs on edit pages\n- [#2668] Fixed issue with FC rules and labels on checkbox/radio fields\n- [#2582] Fixed bug with orm tree preventing attributes on the root node\n- Fix bug in phpthumb allowing remote src parameters regardless of settings\n- [#2555] Expose additional phpthumb options in System Settings\n- [#2503] \"Preview\" inaccurately described viewing current page/site. Changed to \"View\".\n- Fixed help message strings to correct URLs\n- Fixed missing options array call in modRestClient, isArray call in modRestCurlClient\n- [#2545] Added setting resource_tree_node_name to allow users to specify the field used for the node text on the Resource Tree\n- [#2639] Prevent user from specifying a FC rule with Action of none\n- [#2641] Fixed issue where template was reset incorrectly when canceled on template change\n- Fixed issue where Permissions were being duplicated on setup due to relational db issue\n- [#2646] Prevent removal/editing of default Administrator policy ACLs to prevent users from accidentally removing access to web context\n- Added modAccessPolicyTemplate and modAccessPolicyTemplateGroup for easier managing and editing of Access Policies, including a UI for managing Access Policy Templates\n- [#2483] Auto-generate alias when duplicating a Resource\n- [#2645] Set Resources unpublished when duplicating\n- Update to xPDO v2.0.0-rc3\n- [#2501] Fixed menu not being loaded on immediately-added policies without page refresh, added bulk actions to policy grid\n- [#2505] Save Property Set now shows feedback and success message\n- [#2507] Export properties now prefixes filename with property set name\n- [#2624] Improved Users grid to allow batch editing from right-click context menu\n- [#2609] Remove filter commands and modifiers from scriptProperties passed to modElement/modTag instances\n- [#2500] Improved CSS on welcome page for Fx users\n- [#2532] Improved Resource tree icons to better shown when a Resource has children as opposed to when it is marked as a container\n- [#2602] Improved language on Users access permissions grid to clarify action\n- [#2614] Expand comment field on modUserProfile to handle more than 255 characters\n- [#2613] Ensured User Groups in mgr are sorted alphanumerically\n- [#2599] Fixed issue where Add Element to Property Set window form values were not cleared on second loading\n- [#2596] Fixed issue where User Groups could not be removed\n- [#2542] Fixed hardcoded language lexicon load reference in policy/get processor\n- [#2573] Fixed issue with backslash in TV output render property values\n- [#2594] Fixed issue where special characters were being stripped from phone numbers in user profile\n- Fixed issue with file tree that prevented image thumbnails from showing\n- [#2525] Fixed filemanager_path issues by added filemanager_path_relative setting, and then calculating from that\n- [#2589] Fixed issue with port 80 feeds in magpie RSS feed parser\n- [#2544] Fixed issue with updatefromgrid processor with User Settings\n- [#2560] Fixed issue with resourcelist TV not persisting set value\n- [#2586] Add rank field to FC rules allowing organizing of order of execution\n- Update core schemas and regenerate maps for new xPDO index elements\n- [#69] Allow Transport Vehicles to abort installation when validation fails\n- Update xPDO version to 2.0.0-rc2 (official release)\n- [#2552] Fix scope issues when passing nested arrays in Chunk properties", "MODX Revolution 2.0.4-pl2 (October 15, 2010)\n====================================\n- [#2502] Fix fatal error with Resources protected by Resource Groups\n- Fixed issue with resourcelist TV", "MODX Revolution 2.0.4-pl (October 14, 2010)\n====================================\n- Fixed issue where redirect was not working after creating new derivative resource\n- [#2485] Fixed issue where placeholder was in duplicated Access Policy\n- [#2492] Fixed reference in menu to bugs.modx.com\n- [#2486] Removed hardcoded language reference in lexicon load in access permissions getList processor\n- [#126] Ensured clearing of cache when deleting a Template Variable\n- Fixed issue where cancel button did not work on Resources after save\n- Fixed issue with URL TV Output Render and empty input values\n- Fixed issues with checkboxes/radios in TVs and widths when hidden\n- Fixed various issues with thumbnails in MODx.Browser and return paths in separate contexts\n- Added toggle setting for drag/drop in Resource and Element trees\n- [#MODX-2346] Allow login/logout processors to handle multiple contexts\n- [#MODX-2405] Fixed issue with border on portal panels in mgr home screen\n- Fixed issue with TV output render that stripped whitespace in delimiter\n- Fixed hanging save issue that occurred when HTML was in pagetitle/longtitle in a Resource\n- Fixed issue where TV values were being erased when a TV was hidden via Form Customization\n- Updated reference to help in Form Customization page\n- Fixed trivial issues with widths in richtext tvs\n- [#MODX-2415] Added fix to prevent adding of orm tree attributes with the same key on the same level\n- Added resourcelist TV input type for easier listing of resources in a tv input\n- Updated ExtJS to 3.3.0\n- [#MODX-2378] Fixed issue where action toolbar was on left in IE7\n- [#MODX-2408] Fixed issue where sorting was not available for description field on search page\n- Fixed issue where modx->resource was not available to TV input option values or default values in mgr\n- [#MODX-2410] Fixed issue with urlencoded context key on context edit page\n- [#MODX-2407] Fixed issue where user settings were not respected in connectors in mgr\n- [#MODX-2279] Fix bad AJAX response if database does not exist or can't be created during setup\n- [#MODX-2404] Fixed issue with auto_menuindex and multiple contexts\n- [#MODX-2354] Fixed issue with image TV loading incorrect URL in thumbnail preview on initial load\n- [#MODX-2357] Properly addressed issue where FC hideTab rule was causing hidden tabs to show if they were active at load\n- Refactor modAccessibleObject to centralize load policy check in _loadInstance()\n- Update xPDO for several critical bug fixes\n- [#MODX-2402] In Package Browser, Most Popular/Recently Added package names are now links to auto-search in grid\n- [#MODX-2397] Added filtering and search to FC rule grid\n- [#MODX-2401] Adjusted JS version postfix code to not adjust .php (or non-js) files used as script src targets\n- Improved context menus on FC rule grid to allow for batch actions on selected items\n- Added `for_parent` field to FC rules, to allow for more fine-grained control of rule applications\n- [#MODX-2385] Fixed issue when Context ACL is using no policy that prevented grid loading\n- [#MODX-2380] Fixed issue with upgrades and rb_base_dir, rb_base_url and filemanager_path\n- [#MODX-2246] Added topmenu_show_descriptions system setting to be able to toggle the top menus description text\n- [#MODX-2375] Improved class key field in Resource panel to a dropdown, added modClassMap for easier querying of resource/element types\n- [#MODX-2391] Fixed issues with FC rules not being respected on resource/create with default values for new Resource\n- [#MODX-2382] Fixed dynamic width of fields in windows across ui\n- [#MODX-2383] Fix inability to update rank of TV's in template editor\n- [#MODX-2379] Fixed issue where permission checks were swapped in Resource context menu with regards to delete/undelete\n- [#MODX-2384] Fixed issue where treepanel still showed if all trees were hidden via permissions\n- [#MODX-2389] Fixed issue where setup options, license and readme displays were not cleared after installation of package\n- Fixed issue where loading mask shows up and never disappears on extended Resource types\n- [#MODX-2388] Fixed issue with save button and user settings\n- [#MODX-2387] Fixed issue with user settings not able to be added via mgr ui\n- Fixed bug that would reset provider for updated packages\n- Fixed issue with paging toolbar pageSize being interpreted as string rather than int\n- Fixed issue where parent id constraint was ignored for default template on new Resources\n- Added sanitization to REQUEST_URI for login controller\n- Updated version to 2.0.4-pl", "MODX Revolution 2.0.3-pl (September 30, 2010)\n====================================\n- Fixed error in modResource::cleanAlias when context var is not available\n- [#MODX-2376] Fixed issues with updating settings on the context page\n- Fixed security issue with login screen and resource TV controller that allowed html injection\n- Fixed issue where clear cache checkbox isn't checked on Element pages\n- [#MODX-2370] Fixed various bugs with plugin event association on plugin page\n- [#MODX-1823] Improved the System Info panel by extracting data from phpinfo()\n- [#MODX-2362] Added missing OnResourceTVFormPrerender event\n- [#MODX-2374] Fixed issue where children nodes were not being moved with parent into new context\n- [#MODX-2373] Fixed imageTV issue where thumbnail was not cleared on data clearing\n- [#MODX-364] Fixed regClient* methods in cacheable Snippets on cacheable Resources\n- [#MODX-2370] Fixed issue with saving property sets on plugin events\n- [#MODX-2369] Fixed issue with modLinkTag and output filters where the filter commands were included in the URL\n- [#MODX-2350] Ensure that new Contexts always have Admin and Resource policy for Admin user group assigned to them\n- [#MODX-2352] Ensure that Context Settings appropriately override System Settings in core-level parsing where a Context is existent (example: site_unavailable_page)\n- [#MODX-2356] Ensure that OnResourceDelete and OnResourceUndelete events in update processors fire at correct times, after save()\n- [#MODX-2361] Ensure that a user in the Administrator group *always* has access to a Context when it is restricted in another user group\n- [#MODX-2357] Fixed bug that occurs when hiding a tab with FC rule that is the default active tab\n- [#MODX-2358] Fixed rare bug occurring with treestate in Chrome due to undefined variables in path\n- Fixed various issues with package management and the add new package button\n- Fixed bug where ?v=203pl is being added to content with .js in it, due to earlier commit to prevent js caching\n- Fixed issues with ellipsis/limit filters and special chars\n- [#MODX-2353] Fixed bugs with checkbox/radio TVs and complex values with HTML/quotes in them\n- Fixed some bugs with deleting a file in MODx.Browser in the actual view pane\n- [#MODX-2354] Fixed issue with imageTV and incorrect preview url reference\n- Fixed ellipsis output filter to use &#8230; instead of ...\n- [#MODX-2327] Fixed bugs with Form Customization not being respected\n- [#MODX-2349] Fixed bug with Form Customization and fieldDefault rule with template field\n- Added code to prevent caching of JS after upgrades by postfixing version to JS URLs\n- [#MODX-2342] Fixed issue where xhtml_urls setting wasnt included in build\n- [#MODX-2345] Fixed issue with templates and categories in mgr not persisting\n- [#MODX-2341] Fixed issue with redirect statement on login page in certain environments\n- [#MODX-2343] File upload now respects upload_* extension restrictions\n- [#MODX-2344] Respect context-specific filemanager_path in upload/remove actions on directory tree in mgr", "MODX Revolution 2.0.2-pl (September 17, 2010)\n====================================\n- Fixed issue where Add New Package would not work when selecting a provider manually\n- [#MODX-2339] Fixed issue with caching menus in mgr and multiple languages\n- [#MODX-2340] Fixed issue with initial resource values reverting after a save\n- [#XPDO-72] Fix invalid call to $this->manager->getPhpType()", "MODX Revolution 2.0.1-pl (September 16, 2010)\n====================================\n- [#MODX-2317] Add responseCode parameter to modX::sendRedirect() method\n- Fixed issue with @DIRECTORY binding not postfixing base path with / before value\n- Many styling enhancements, fixes for [#MODX-2264], [#MODX-2193], [#MODX-1885], [#MODX-1847]\n- Fixed issue with lexicon translations for permissions dropdown in mgr\n- Enhanced system settings grid to autosave without refresh, which allows for tabbing between settings via keyboard to set values\n- [#MODX-2325] Updated placeholders in setup lexicons for french/german languages\n- Added an editable dropdown for Permissions tab when editing an Access Policy for easier addition of Permissions\n- Fixed issue where default template was overriding empty template resources\n- [#MODX-2325] Updated Czech translation\n- [#MODX-2329] Login page now auto-focuses on username textfield\n- Add missing modCategoryClosure to create_tables script in setup\n- [#MODX-2280] Fixed bugs with IE and package management\n- Prevent issue where a User Group can select itself as a parent\n- Allow typeahead on user field when adding a User to a User Group\n- Optimized Resource Group tree in mgr UI\n- Fixed issue where > 20 records were not showing in ACL lists in User Group edit panel\n- [#MODX-2206] Prevent issue where renaming a menu's lexicon key orphans child menus\n- Fixed rendering bugs in file edit panel, as well as optimized its loading and streamlined RTE integration on the panel\n- [#MODX-2202] Removed deprecated modAction objects to prevent confusion\n- [#MODX-2325] Updated Swedish translation\n- Prevent bug that causes modal to overlap welcome screen\n- Allow non-empty responses to OnBeforeTVFormSave to prevent save\n- [#MODX-2201] Ensure MODX_PROCESSORS_PATH is upgraded correctly on upgrades where the core is moved\n- [#MODX-2323] Allow non-empty responses to OnBeforeDocFormSave to prevent save\n- [#MODX-2309] Ensure upload files button always uses the active node as the path, or if it is a file, its parent directory\n- [#MODX-2295] Ensure menuindex can be overridden in resource creation if auto_menuindex is set to true\n- Fixes to resource panels to adjust widths, loading of values properly\n- [#MODX-2318] Fixes to TVs in Resource pages to make order sorting work correctly\n- Abstracted setup database methods to driver-specific structures to accomodate for various future db drivers\n- [#MODX-2241] Added archive_with setting so users with improper ZipArchive compiles can switch back to PCLZip\n- Updated xPDO to include sqlite drivers\n- [#MODX-2308] Added UUID to all modx installs for usage in extras, custom providers, stats tracking, etc\n- [#MODX-2303] Fixed issue where resource editing pages were not respecting context settings\n- [#MODX-2302] Fixed issue with loading of input option values in TV related to optimizations in 2.0.1\n- [#MODX-2297] Fixed output filters limit/ellipsis when dealing with special character cases\n- [#MODX-2290] Added image preview when hovering over images in file tree\n- Added extra sanity checks in Package Management in case transport zips are not extracted\n- Make package grid update available Yes clickable to update\n- Cleaned up and better abstracted modRestClient and modRestCurlClient code\n- Fixed bug in setup during upgrade-advanced where DB information was not being checked correctly\n- Lots of improvements to handling and caching of thumbnails in manager\n- Fixed bug where reset filter on settings grid was not resetting to core namespace\n- [#MODX-2178] Added missing settings and lexicon values for those settings to build/lexicons\n- [#MODX-2179] Lexicons in Setup now use placeholders rather than sprintf for better i18n support\n- Added phpthumb_imagemagick_path for users that need to change the imagemagick path for different environments\n- [#MODX-2288] Dont duplicate TV Resource values when duplicating a TV unless explicitly told to\n- [#MODX-2217] Persist sort order of Resource tree\n- [#MODX-2291] Prevent editing of binary files to prevent zeroing out of file when saving\n- [#MODX-2185] Resource tree expand all toolbar button now expands all levels deep\n- [#MODX-2260] Added ability to rename ORM container nodes on extended fields\n- [#MODX-2285] Added ability to dynamically set number of results for any grid in manager, as well as a default number via default_per_page system setting\n- [#MODX-2284] Fixed bug in modX::getChildIds\n- Adjusted the way resources/elements load data in mgr edit/create pages to vastly speed up load times\n- [#MODX-2282] Fixed deprecated help menu URLs\n- Trees now properly handle state, allowing multiple state paths to be set\n- [#MODX-2163] Give area combobox in System Settings a bit more breathing room\n- [#MODX-2259] Fixed issue with empty value fields in extended/remote fields via ORM widget\n- [#MODX-2249] Fixed issue with misleading comment in modTemplateVar::getValue\n- [#MODX-2270] Added option to sort by pulishedon in the resource tree\n- [#MODX-2278] Removed non-used files and added space to empty files\n- [#MODX-2250] Fixed bug where Checkbox TVs with default value dont allow all checkboxes unchecked\n- [#MODX-2274] Introduced filemanager_url setting to handle URLs when filemanager_path is outside the webroot\n- [#MODX-2251] Fixed issue where @bindings in TVs were running during input, preventing setting values\n- Fixed bug with modContext::getOption and default values\n- [#MODX-2184] Fixed issues with MODx.rte.Browser and context-specifics\n- Fixed issue with filemanager_path in Windows\n- Fixed a possible issue in base file perms in modFileHandler\n- Fixed some random typos in system settings data and lexicon translations\n- Fixed bug where userinfo filter was outputting wrong content when user was empty\n- [#MODX-2263] Fixed IE issue with dropdowns as TVs\n- [#MODX-2183] Autotag values are now alphabetically sorted\n- [#MODX-2240] Site - Preview now dynamically previews current editing context\n- Fixed invalid login issue that prevented OnUserNotFound from firing on mgr login screen\n- [#MODX-2238] Fixed bugs regarding parent constraint and default template\n- [#MODX-2234] Fixed issue when drag/dropping a Resource into the parent field\n- [#MODX-2226] Fixed bugs with date output filter not behaving as expected\n- [#MODX-2184] Fixed issue where context was not respected in MODx.Browser instances, fixed bugs when specifying paths outside MODX_BASE_PATH\n- [#MODX-2236] Added sanity check to modTemplateVar::getRenderDirectories with custom dirs\n- Added modResource::joinGroup\n- Added helper JS function MODx.hideTV to modext\n- [#MODX-2233] Fixed issue where qtip was not showing on Elements in a Category\n- [#MODX-2203] Fixed issue where root of file tree was not accessible after navigating away\n- [#MODX-2192], [#MODX-2232] Fixed issues with settings and their translations, names in the Settings grids\n- Adjustments and optimizations to menus/actions processors and js\n- [#MODX-2231] Fixed issue where saving translated properties would overwrite key with translation\n- [#MODX-2220] Fixed bug where save_user was needed to change profile\n- [#MODX-2213] Always include english lexicon when loading a lexicon to act as a backup translation\n- [#MODX-2210] Added strip for xss in manager a variable\n- [#MODX-2205] Fixed issue with saving resources with resource fields having html and unescaped content\n- [#MODX-2198] Fixed directory checks on context web path for advanced distribution\n- [#MODX-2194] Fixed issue with modLexicon::fetch not working if a prefix is set\n- Removed SVN commit log from top header now that we're in Git\n- Adjusted version to 2.0.1-rc1", "MODX Revolution 2.0.0-pl (LastChangedRevision: 7216, LastChangedDate: 2010-07-21 09:10:12 -0500 (Thu, 21 Jul 2010))\n====================================\n- [#MODX-2159] Fixed bug where richtext_default was being ignored in Quick Create\n- [#MODX-2174] Fixed bug where manager_language was being ignored in Connectors, check for ctx init\n- [#MODX-1715] Added reference to setting keymap_save to allow for overriding of save shortcut key\n- [#MODX-2008] Updated Russian and Japanese translations\n- [#MODX-2008] Added in Thai translation\n- Fixed typo in filters english lexicon\n- [#MODX-2008] Added in French translation, updated German translation\n- [#MODX-2173] Fixed issue with IE and package installation wizard\n- Fixed setup directory checks for advanced builds\n- Fixed incorrect welcome URL in build\n- [#MODX-2008] Added in Czech translation\n- Configured phpdoc.ini file for SDK build\n- Fixed bug in file tree where URL was absolute rather than relative when being drag/dropped\n- Added OnFileEditFormPrerender event to allow plugins to fire on file editing form\n- [#MODX-2172] Fixed bug where tooltips for stay buttons were behind window\n- Sanity checks to tv render directories\n- Removed deprecated CSS icon reference\n- [#MODX-2169] Fixed bug with TV default values, inheriting and non-linear TV inputs\n- [#MODX-2170] Fixed error where element names cannot have less than 3 characters\n- [#MODX-2169] Properly handled @INHERIT binding in TV inputs\n- [#MODX-2165] Changed 'Remove Package Version' context menu item behavior to allow to show on non-installed versions to allow rollbacks from downloaded but not installed updates\n- [#MODX-2164] Fixed issue that might cause random, non-affecting error during package updates\n- [#MODX-2008] Added in Japanese translation\n- [#MODX-2163] Default settings grid to show only core namespace settings to reduce confusion\n- Added autotag TV input widget that grabs tags from a list of the tags so far for all content values for that TV\n- [#MODX-2161] Added sanity check for incorrect or invalid filemanager_path values in file tree\n- Added missing deleted checkbox on resource panels\n- [#MODX-2167] Fixed issue where duplicate button was creating incorrect duplicate name\n- [#MODX-2162] Fixed issues with set to default in TV values, reliance on processedValue\n- [#MODX-2168] Fixed new user panel issue with missing JS reference\n- [#MODX-2160] Fixed bug where config check was running checkPolicy on resources that caused inadvertent missing unavail/error page message\n- Some query optimizations in processors\n- [#MODX-2159] Ensure richtext_default setting is respected\n- Fixed bug where context settings create modal wasnt resetting values\n- Added missing tabpanel IDs for various tabpanels across mgr ui\n- Fixed bug that was strtolower'ing any strings in tabNew FC rule\n- Added grid renderer to FC grid\n- Tweaks to general UX, other slight cosmetic fixes\n- [#MODX-2156] Fixed unitialized variable in modTemplateVar::renderOutput/renderInput\n- [#MODX-2152] Fixed issue where local package dialog wasnt showing after clicking modxcms.com package browser\n- [#MODX-2154] Fixed issue where publish_document access permission was being ignored in resource processors\n- [#MODX-2149] Fixed issue where Package Management's modal would only once if hidden\n- Fixed issues with stay button on resources\n- [#MODX-2008] Added Swedish translation\n- [#MODX-2148] Fixed image TV thumbnail sizing\n- [#MODX-2145] Fixed 'New' context menu text to be easier to translate\n- Slight tweaks to CSS for MODx.Browser file thumbs\n- [#MODX-2147] Added phpThumb settings for controlling thumbnail output in manager, defaulted zoomcrop to off and force aspect ratio to on, center\n- Fixed erroneous change template message\n- [#MODX-2143] Fixed filemanager_path implementation so that thumbnails and relative URLs in browsing work with absolute and relative paths as setting\n- Removed powered-by text in request headers in AJAX calls\n- [#MODX-2143] Fixed issue where if filemanager_path was set differently that URL insertion on TVs or drag/drop was incorrect\n- Added urlencode/urldecode to filters\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings without breaking makeUrl()\n- [#MODX-2142] Fixed issue where translations in settings, properties and permissions were not being translated or falling back to english\n- [#MODX-2132] Reverting commit in r7125 due to side issue caused by fix in it\n- Hardened security on some file download actions in mgr such as console output, phpinfo, properties export\n- Adjusted setup expiry to 15 minutes\n- [#MODX-2139] Added message to display if setup has to restart due to timeout\n- [#MODX-2140] Fixed welcome page to point to static page rather than atlassian stack\n- Update Help URLs to new base url for docs\n- Some UI tweaks to lexicon grid, added reset() JS method to MODx.Window for shorter code\n- Added in create entry to lexicon management\n- Ensure $modx is available in custom TV renders\n- [#MODX-2137] Fixed bug in image TV output render\n- [#MODX-2138] Fixed textarea bug in system settings\n- Allow MODx tags in TV descriptions in input renders, but prevent HTML tags\n- Fixed bug where output render type was being ignored\n- Ensure tv data isnt sent back in resource update processor, to prevent escaping problems with richtext tvs\n- [#MODX-2109] Fixed setup to have upgrade mode not go to editing database/contexts, only advanced upgrade goes there\n- Fix object caching bug in modAccessibleObject::_loadCollectionInstance()\n- Update xPDO 2.0 to revision 429\n- Ensure extended fields can be added to users with none pre-existing\n- [#MODX-2131] Fixed other issues with TV values and rendering\n- Added ctrl+alt+p key shortcut when updating a Resource to preview it\n- Prevent illegal drops of actions to menus, menus to actions, in trees on Actions page\n- Slight fixes, tweaks to plugin events grid\n- [#MODX-2130] Fixed typos and missing references in mb-based output filters\n- [#MODX-2131] Fixed various issues with TV rendering, values, and in multiple contexts\n- [#MODX-1404] Make MySQL client version check a warning only for older versions\n- [#MODX-1404] Remove MySQL client version check for 5.0.51\n- [#MODX-2024] Fix use of %s strftime modifier in modSessionHandler::write()\n- [#MODX-2132] Remove friendly_url_prefix reference that was causing PHP warnings\n- [#MODX-2107] Fix errors with friendly alias slug generation with certain multi-byte characters\n- [#MODX-2114] Fix Error Caching Resource log message when site unavailable or other transient Resources are constructed\n- [#MODX-2129] Added missing Resource events\n- Fixes to Messages page/grid\n- Added optimize database button on database tables grid\n- Fixed reference bug in resource/update processor\n- Improvements to Users grid to dim inactive users\n- Fixed a few bugs with MODx.Browser and file tree\n- [#MODX-2127] Added message to Package Management if cURL or Sockets is not installed that prompts user to do so\n- Added ability to send warning/error messages to all MODx.* grids/trees\n- [#MODX-2128] Fixed MODx.Browser in RTE mode\n- Added modManagerRequest::addLangTopic,setLangTopics,getLangTopics assistance methods\n- [#MODX-2125] Various fixes for manager log page\n- [#MODX-2023] Added sanity checks for settings caches in setup, ensure settings caches are removed post-setup\n- [#MODX-2064] Ensure Action combos in System Actions page are reloaded when an action is updated/created/removed\n- Fixed invalid validation rule on element classes\n- [#MODX-2091] Ensure duplicate maintains published status\n- [#MODX-2123] Added workaround for IE with Quick Update Resource window\n- Modified validation on modChunk, modPlugin, modSnippet, and modTemplateVar to allow spaces within a name\n- [#MODX-2052] Fixed bug with loading multiple MODx.Browser instances in non-file management circumstances\n- Updated duplicate processors to check validation, return more informative messages, sanity checks\n- Removed duplicate days keys in lexicon\n- Fixed issues when TV render directories are overridden\n- [#MODX-2115] Fixed issue with phpthumb reference and capitalization, and when base_url is /\n- [#MODX-2113] Fixed CTRL+SHIFT+H shortcut for hiding left nav\n- Fixed bug in ORM tree relating to adding root nodes when subnode was selected\n- Added ability to add/remove attributes and containers to UI ORM trees, specifically in User extended and remote data\n- Added UI for editing extended User Profile data\n- [#MODX-2116] Fixed bug in depth search in modX::sanitize\n- [#MODX-1150] Changing class_key for a Resource now reloads the page to change editing area\n- [#MODX-2077] Config check screen in welcome panel now is same width as other panels\n- [#MODX-1648] Lexicon Management now loads by default the current manager_language\n- [#MODX-1743] Package update now shows status alert when package is already up to date, rather than an error\n- [#MODX-2119] Fixed bug in IE where onunload was firing regardless, preventing moving off page seamlessly\n- [#MODX-2112] Fixed bug where admin password reset was not working\n- [#MODX-2111] Fixed bug where language settings were not set after running setup in another language\n- [#MODX-2110] Fixed bug where resource fields were not being updated on update, causing publishedon errors\n- Adjusted version for pl development", "MODX Revolution 2.0.0-rc-3 (LastChangedRevision: 7083, LastChangedDate: 2010-07-07 12:20:55 -0500 (Wed, 07 Jul 2010))\n====================================\n- Updated German translation\n- Fixed bug with new installs and base template name\n- Fixed UI issue with Namespace path being unwantingly translated\n- Upped timeout on setup settings cache to 10 minutes; was far too short\n- [#MODX-2040] Fixed bug with setProperties and merge argument\n- Slight tweaks to phpthumb default config\n- Added sanity check when using multiple TV render directories\n- [#MODX-2100] Fixed content type creation for binary type bug, bug in build with regards to content types\n- Added flag to setup to fix proceeding error after install\n- Fixed setup to return setup process to very beginning when settings timeout, avoiding various errors about classes not being found\n- Added modx-tv-checkbox class to resource TV checkboxes for easier DOM manip\n- Added showCheckbox setting for resource TVs display to allow for extensibility and TV targeting\n- Added phpThumb specific settings\n- Added OnResourceTVFormRender event for affecting TV displays on resources\n- [#MODX-2104] Auto-detect correct value and set use_multibyte on new installs\n- [#MODX-2104] Added 'use_multibyte' setting that allows for use of mb_* functions for multibyte characters; fixes bug with MB chars in output filters\n- [#MODX-2019] Added default Element policy\n- Fixed issue with Ext.form.BasicForm and prior commit, adjust else/if condition\n- Added headers check to all Ajax requests to connectors to require unique site ID header to harden security\n- Added modx-content-above and modx-content-below divs for RTE usage\n- [#MODX-2008] Updated Russian translation\n- Enabled RTEs to be used on TV default value field\n- Added which_element_editor setting, which allows for usage of multiple RTEs for Elements vs Resources\n- Fixed bug with custom_resource_classes setting implementation on blank values\n- [#MODX-2094] Enabled Packages to be able to have their Provider changed\n- [#MODX-1809] Added manager_time_format to allow changing of time formats in mgr widgets\n- Added extra var to pass revo version in transport provider requests; helps with download metrics and version checking\n- Optimized package grid by moving menus to JS\n- Fixed issue where manager_language setting was being ignored in mgr connectors\n- Enhance security on language string loader\n- [#MODX-1834] Adjusted color on Yes/No on packages grid to more reflect intent\n- Readjust JS firing timing for Elements to prevent RTE timing errors in faster browsers\n- [#MODX-2090] Added auto_check_pkg_updates_cache_expire setting, which caches package update checks in Package Management to speed up grid load times\n- Ensure Resource pages using RTEs always have save btn enabled\n- Fixes to RTE loading in Element panes, other issues regarding timing of plugin firing\n- Fixed bug with area listings in combo in system settings\n- [#MODX-1961] Fixed bug with octal perms when creating directories in the admin\n- [#MODX-1527] Fixed bugs in admin confirm password field on install\n- Fixed Package Management in IE8\n- Styling improvements\n- Fixed IE issue on navbar, few other tweaks to package management for IE\n- [#MODX-2032] Fixed topic varchar length issue with UTF-8 installs\n- [#MODX-1612] Added Create Menu context menu on root node for menus tree\n- [#MODX-2020] Ensure error when creating duplicate context ACLs shows\n- Tweaks to Package Management browser JS to allow for more consistent rendering\n- [#MODX-2051] Stripped tags from TV description field on input rendering\n- Added 'custom_resource_classes' setting, which allows you to specify custom resource types for the resource tree\n- Tweaked FC tvMove rule to be more consistent with values of other TV FC rules\n- Allow blank names (not keys) in Settings create/update windows; tweaks to query in package management grid\n- [#MODX-1737] Container resources can now have names specified on duplicate\n- [#MODX-2074] Fixed bug where property descriptions were not i18n-able\n- [#MODX-2062] Date TV type now can store time; updated datetime ExtJS xtype to latest version\n- [#MODX-2046] Added 'collapse' toggle to left trees, shortened username on top right to allow for small resolutions\n- [#MODX-2067] Fixed bug with cleanAlias and a non-existent lexicon string\n- [#MODX-2086] Fixed a few bugs in package management styling\n- Tweaks to context menu styling\n- [#MODX-2078] Context menus now show under cursor\n- [#MODX-2083] Fixed bug where setting editedon was returning invalid date\n- [#MODX-2061] Fixed erroneous lexicon entry for cache_handler setting description\n- [#MODX-2085] Fixed issue with namespace path not being translated on get\n- Added ability to activate/deactivate FC rules from context menu\n- fieldVisible, fieldLabel, tvVisible, tvMove Form Customization rules now support multiple fields via comma-sep list\n- Added functionality to Form Customization to add new Tabs and move TVs to other tabs\n- Applied CSS gradient styling to grids, tabs\n- [#MODX-2056] Fixed CSS for topmenu, restyled to add contrast and enhanced\n- Cleaned up TV display panel, removed TV reload button, extended fields all the way across\n- [#MODX-1832] moved \"Set to Default\" to a fade-in icon\n- Prepared code for oncoming feature to move TVs into other tabs\n- Removed credits from about pane, consolidated tabs\n- Fixed permissions checks on resource tree context menu when policies are limited\n- Added prefix filtering to modLexicon::fetch\n- Added modTemplateVar::getDisplayParams for easier fetching of display_params for a TV\n- Fixed bug with custom TV render paths\n- Added phpThumb to core, added connector for secure access, integrated into MODx.Browser\n- Ensure categories in TV panel are sorted alphanumerically\n- Added stripString, cdata, replace, fuzzydate and ago output filters\n- [#MODX-2045] Added ExtJS, Smarty, PHPMailer, MagpieRSS version into System info\n- [#MODX-2057] Fixed bugs with action/menu trees\n- Fixed bug with is_writable check in setup; was checking core/config rather than just core/config/config.inc.php\n- [#MODX-2042] Fixed extra beginning slash for image/file TVs\n- Add validation to processors for Chunks, Plugins, Snippets, and Template Variables\n- [#MODX-1998] Disallow reserved Template Variable names (i.e. Resource field names)\n- [#MODX-2033] Fix bug with unchecking Template Variable access when editing a Template\n- Have modX::switchContext() update placeholders from config on successful switch\n- [#MODX-1774] Remove redundant setting of placeholders from modX::$config in modRequest::handleRequest()\n- [#MODX-2031] Fix modX::stripTags() and modX::sanitize() to properly strip nested element tags\n- [#MODX-2027] Added icon to file tree to show MODx Browser, for a different view on file management\n- [#MODX-1924] Made more precise the cursor pointer change on buttons in mgr\n- [#MODX-1904] Fixed bug with phx placeholders in modTranslate095 class\n- [#MODX-1535] Fixed bug with transparent background for grid-based comboboxes\n- [#MODX-1904] Fixed bug with phx placeholders in modParser095 class\n- [#MODX-1936] Lexicons now fallback to English if no translation is found for specified language\n- [#MODX-1781] Fixed z-index issue with top nav and window masks\n- [#MODX-217] Added create element type icons for Element tree\n- [#MODX-217] Added directory create icon to file tree toolbar, changed upload files button to icon\n- [#MODX-2022] Fixed bug regarding php file permissions and writable checks\n- Fixed bugs related to loading of RTEs for TVs in derivative resource classes\n- Enhanced image TV to show preview of image, adjusted to display below\n- [#MODX-2015] Added sanity check to prevent users from dragging Resources to a non-existent context\n- [#MODX-2013] Fixed bug where hiding fields with Form Customization would disable them from being sent\n- Fixed bugs with System Settings grid due to erroneous merge in UI styling\n- [#MODX-2012] Made Form Customization grid sortable\n- [#MODX-2011] Fixed MODx.grid.Grid::getSelectedAsList to work in Fx,IE\n- Added more sophisticated check for writable directories in setup to ensure compatibility across environments\n- Fixed bug where manager_language setting was ignored\n- [#MODX-2007] Redirect to requested mgr page when logging in\n- Adjusted version for RC-3 development", "MODX Revolution 2.0.0-rc-2 (LastChangedRevision: 6924, LastChangedDate: 2010-05-27 15:56:51 -0500 (Thu, 27 May 2010))\n====================================\n- Fixed copy-prepared-css command in build.xml to prepare for rc-2 release\n- Adjusted welcome screen URL to go to a non-release specific confluence page\n- [#MODX-2000] Fixed FC rule to apply to template fields by overriding in controller\n- [#MODX-2000] Add ability to specify a template in REQUEST or alter via plugin in resource/create controller\n- [#MODX-2004] Allow settings to be duplicated when duplicating a context\n- Added missing OnUserBeforeRemove event\n- [#MODX-1797] Fix bug with publishedby field getting updated unintentionally\n- [#MODX-1919], [#XPDO-52] Update xPDO to revision 425 for fix to xPDOManager::createObjectContainer()\n- [#MODX-1918], [#MODX-1919] Improve error reporting in database setup steps\n- Made default click behavior for Files in file tree be to edit\n- [#MODX-1995] Fixed issues regarding sending password via email with new users\n- [#MODX-1549] Preserve file tree state\n- [#MODX-1810] Gender now saves correctly in user panel\n- [#MODX-1635] Redirect to Users grid after creating a new user\n- Fixed bug with import properties\n- [#MODX-1971] Allow ./- in Context key names, but not as first character\n- [#MODX-1997] Added ability to duplicate and set inactive/active Form Customization Rules, batch actions to Rule grid\n- Cleaned up profile editing page\n- Cleaned up style for headers on welcome page\n- Reworked System Info page, cleaned up styling, display, info\n- Added batch actions to Users grid\n- Fixed bugs with removing directories in file tree\n- [#MODX-1996] Fixed missing create/update settings windows\n- Allow for separate paths on derivative resource types based on a [classkey]_delegate_path setting that points to their controllers, added checks to prevent path mapping\n- Prevent deferred render on left nav trees, to prevent loading errors for js hooks\n- Fixed bugs with MODx.grid.encodeModified/encode, plugin event saving\n- Added loadCreateMenus JS event to modx-resource-tree modext widget\n- Refactored js lang loading to allow for dynamic modification of strings\n- [#MODX-1993] Moved config.inc.tpl to core/docs to prevent confusion\n- Added description below TV rows in Resource edit\n- [#MODX-1853] Fixed issue where reload button was above MODx.Browser in TV pane\n- Switched Quick Create/Update Resource description field to more-used introtext field\n- [#MODX-1992] Fixed error in modSnippet preventing multiple executions per request\n- [#MODX-1983] Clarified package uninstall option message\n- [#MODX-1982] Fixed broken cancel button on Package View page\n- [#MODX-1989] Fixed incorrect var reference in getfiles processor\n- Added extra pagination to dropdowns in mgr that might have large #s of records to add usability for large sites\n- Fixed all Elements including Template Variables to properly respect modAccessCategory ACLs.\n- Allow base-level Element Category ACL assignments\n- Fixed some issues with Settings grid and lexicons, key not being displayed, etc\n- [#MODX-1940] Resized lexicon grid toolbar to fit better in smaller resolutions;\n- [#MODX-1950] Adjusted permissions to allow proper listing of Elements; checks 'list' policy on Element now rather than view_[element]\n- [#MODX-1975] Added warning messages for PHP 5.2.0 and 5.1.6 versions in setup asking that users upgrade to 5.3.0+; will still allow installs, however, if the user has those versions\n- [#MODX-1967] Added warning to setup for people who are using PHP 5.3.0+ and dont have date.timezone set\n- Added proper permission checks to Elements/Categories across processors/controllers\n- Added UX for managing Element Category access for User Groups\n- Add modAccessCategory to allow context-specific security policies on modCategory as well as any modElement via the related modCategory; includes policy inheritance to sub-categories\n- Add modCategoryClosure table class to allow for easy recursive queries on modCategory\n- Fixed bug caused by JS/CSS optimizations that would break left nav when too many resources were loaded\n- Fixed bug where access contexts for admin user were being duplicated on upgrades\n- Added extra options to attaching with modPhpMailer; fixed bug in phpmailer that caused E_DEPRECATED errors\n- [#MODX-1912] Added manager logging to file/directory actions\n- [#MODX-1912] Added file/directory specific permissions to allow more fine-grained security on using the file manager\n- [#MODX-1972] Added OnTVInputRenderList, OnTVOutputRenderList, and OnTVOutputRenderPropertiesList System Events to allow you to return a path to specify where to look for custom TV files\n- Allow separate caching directories for smarty when using different manager themes\n- [#MODX-1951] Ensure smarty cache is cleared on site cache clearing and settings\n- Ensure admin ACLs are set on new installs\n- Added check to modResource::stripAlias to make sure modX object is a modX instance\n- Added basic template and default home resource to new installs\n- Added load-only and load,list and view policies to build, adjusted setup to handle admin/resource policies with different IDs\n- Moved setup's global new/upgrade install scripts to separate files\n- MODExt adjustments; main layout now in central viewport so can handle browser resizing, refactored settings grid editing code, IE/FF/Chrome fixes\n- [#MODX-1970] Add scheme property to Link Tags to allow canonical, https, or any URL generation scheme from modX::makeUrl()\n- Fixed bug where core namespace was not in build\n- Update xPDO to revision 424 for fixes related to PDOException reporting\n- Ensure packages are unpacked after downloading\n- Fixed bug with removing a plugin\n- Added System Setting, 'cache_noncore_lexicon_topics', which can be used to disable caching on noncore lexicon topics, which is useful for 3PC development.\n- Deprecated modPackageBuilder::buildLexicon\n- Completely refactored the Lexicon system to now do file-based Lexicon Entries only. DB entries are only for overrides. This allows for proper overriding of\ncore lexicon entries, caches faster, and allows for much easier 3PC development.\n- [#MODX-1783] Fixed unnecessary scrollbar bug by removing unnecessary margin on body/html tags\n- Slight spacing tweaks to main layout to make layout feel more open\n- [#MODX-1806] Improvements to messages section\n- [#MODX-1913] Fixed incorrect wording on setup complete page\n- Tweaked launching of layout panel to add consistency across browsers\n- [#MODX-1835] Fixed error on Windows platforms when an extension_packages path contains a colon (:)\n- Added ORM editing formpanel object for editing v/p editing pairs, used now on modUser remote data form\n- Added panel for viewing remote data on a user\n- Added 'lexicon' field to modAccessPolicy to enable translations of descriptions of Permissions\n- Added extended field to modUserProfile to handle a majority of basic extended user profile storage/retrieval needs\n- Added 'lexicon' field to Element properties to enable automatic translating of property descriptions and option names\n- Fixed parent/context_key reference issue when creating resource from context tree node\n- Tweaks to index.css for default mgr theme to correct styling issues in webkit browsers due to ExtJS upgrade\n- Fixed deprecated references to removed images in default mgr template css that was causing 404s\n- [#MODX-1911] Allow for drag/drop reorganizing of categories in the Element tree\n- [#MODX-1892] Various fixes to TV-Template relationship grids\n- [#MODX-1895] Added sanity check for windows systems with file names in file browser\n- [#MODX-1908] Corrected logic flaw in modManagerResponse that prevented smarty templatePath from being set for CMPs\n- Optimized loading for System Settings grid\n- Updated ExtJS to 3.2.1\n- Add remote_key and remote_data to modUser\n- [#MODX-1898] Fix static calls to modX::fromJSON() and modX::toJSON() instance methods (xPDO updated to revision 421)\n- Pushed File tree nodes' context menus to JS layer, added Upload Files button to tree toolbar\n- Pushed Element tree nodes' context menus to JS layer, similar to Resource Tree optimizations\n- [#MODX-1897] Fix Date TemplateVar web output render error in PHP 5.3 due to use of ereg()\n- Fixed bug with Quick Update caused by new resource tree js changes\n- [#MODX-1848] Allowed parent selector to select contexts as the parent in Resource page\n- Pushed Resource tree nodes' context menus to the JS layer, massively decreasing the size of the JSON tree sent in the getNodes processor, vast speeding up tree functionality\n- Made publish/unpublish/delete/undelete actions on the tree only change the class of the node, rather than refreshing the node, speeding up workflow\n- Pushed modX::getService to xPDO layer\n- [#MODX-1873] Ensure setup redirects use full URL in header\n- [#MODX-1887] Adjust default widths for main layout to render panels more consistently\n- Optimized modX::getChunk() and modX::runSnippet() by caching instances within a request to modX::$sourceCache\n- Modified modX::setDebug(true) to set error_reporting(-1)\n- Optimized modLexicon::loadCache\n- [#MODX-1824] Fixed bug where duplicate wasnt fully duping resources\n- Moved Resource's duplicate method into the model, via modResource::duplicate\n- [#MODX-1868] tree_root_id now accepts a comma-delimited list of Resource IDs to restrict by. Works across contexts as well.\n- [#MODX-1871] Fixed bug with delimiter TV output render\n- Dropped unnecessary ID field on modEvent table and made `name` column PK\n- Refactored modX::invokeEvent and modX::getEventMap to take advantage of new plugin event changes\n- Adjusted the modPluginEvent model to reference the event name rather than id\n- Added new model-based System Events to work more effectively in any context\n- Removed deprecated system events\n- Added tree_root_id setting that allows you to specify the start parent ID of the left Resource tree\n- Fixed bug where User Settings could not be removed\n- Enabled ability to set absolute path and placeholders for filemanager_path and rb_base_dir\n- [#MODX-1791] modPackageBuilder::createPackage now forces lowercase package name to be more compatible across environments\n- Sanity checks to prevent user from accidentally removing admin/resource access policies\n- [#MODX-1860] Fixed bug where new password was being hidden too fast when changing user password\n- Added proxy support to modRestCurlClient for Package Management\n- Added a couple refactorings to modRestSockClient to prevent possible errors\n- Consolidated user group create system events into one event, OnUserGroupCreate\n- Fixed some various plugin event calls\n- Fixed Plugin Event code to restrict groupname to a UI filter only, not in event caching; adjusted UI grid to support groupname in display\n- Refactored file handling processors to use modFileHandler class with modFile and modDirectory derivative classes to abstract file system processing to abstract for multiple environments\n- [#MODX-1789] Added extra checks in Package Management to make sure that the correct directories are created before using it. Will now prevent usage of PM if those directories do not exist or are not writable.\n- [#MODX-1789] Added code to attempt to create core/components and assets/components after install. If fails, displays a notice to user to manually create them themselves to allow Package Management to work properly.\n- [#MODX-1839] Fixed grammatical error in forgot login link on login page\n- [#MODX-1846] Fixed invalid markup for username in top right\n- [#MODX-1854] Fixed invalid references to cultureKey that broke cultureKey setting effectiveness\n- [#MODX-1785] Fixed invalid password variable reference in invoke notfound event in login processor\n- [#MODX-1784] Fixed invalid event call on user update, as well as added event invoking into updatefromgrid processor\n- [#MODX-1836] Set default context_key in modResource objects to 'web'\n- Fixed bug with system info page and active users that would cause error in error log\n- [#MODX-1788] File tree now respects filemanager_path setting. Also cleaned up file browsing processors.\n- Upgraded ExtJS to version 3.2\n- Updated version to 2.0.0-rc-2 for svn development and issue tracking\n- [#MODX-1778] Fixed error that shows up if E_NOTICE set to true in setup/ index due to servers not posting a HTTPS server global", "MODX Revolution 2.0.0-rc-1 (LastChangedRevision: 6614, LastChangedDate: 2010-03-22 16:41:04 -0500 (Mon, 22 Mar 2010))\n====================================\n- Prepared for rc1 release\n- Fixed CSS compression copying in build.xml\n- Fixed regClient*() functions to work again on cacheable scripts\n- Move element source and include cache files outside of context cache directories since they should be cleared only when elements are updated\n- Remove eval() from modScript and re-enable remote debugging of modScript instances by caching function as include in addition to source cache\n- [#MODX-1759] Ensure manager log fires on top menu deletion\n- [#MODX-1772] Ensure array of IDs is passed to OnBeforeEmptyTrash and OnEmptyTrash plugin events\n- Added a welcome screen to show on first login to manager\n- [#MODX-1738] Fixed issue with default value on radio TVs\n- [#MODX-1741] Fixing inconsistent widths for radio options by making them list vertically rather than horizontally\n- [#MODX-1769] Lexicon grid search now searches name and value\n- [#MODX-877] Updated confusing text on TV access permissions tab\n- [#MODX-1766] Fixed PHP_SAPI issue to properly work by setting a default value on setup to provide a default http_host value to properly populate the site_url\n- Fixed bug in setup that didn't catch processors_path in prior configs\n- [#MODX-1759] Fixed bugs with manager log not storing correct PK values, or displaying missing keys in grid\n- [#MODX-1766] Fixed config.inc.tpl to work with non-httpd SAPI's\n- Added title/info for the Reports->System Info->Database page. This is return fixed the CSS styling issue as well.\n- Fixed CSS Styling on Recent Documents. 5px padding was removed.\n- Fixed bugs with modMail class and default attributes that prevented attributes from persisting after a reset()\n- Removing deprecated RTE handler code\n- [#MODX-1762] Increased file uploader window size for translations\n- Dont render unnecessary tabs in Resource TV panel if no TVs assigned to Template for that Resource\n- Sort Template Variables on the Template editing page by name\n- Ensure Element Properties that have HTML in them show markup instead of rendering the html in editing mode in mgr ui\n- [#MODX-1669] Redid File Uploader in Directory tree to be more cross-browser compatible\n- Cleaned up and enhanced login CSS\n- Standardizing and adding class constants to modRest* classes\n- Updated copyright data in lexicon entries\n- Fixes to build.xml, css compression command\n- Updated copyright dates\n- [#MODX-1750] Lots of procedural and reference fixes to Lexicon grid UI\n- Cleaned up presentation of modAction records in mgr\n- Added a fix to tree refreshParentNode; enhanced modUserGroup::getUsersIn()\n- Added saving mask to Element Property grid to fire when saving the property set\n- Removed deprecated file reference in login template\n- Added System Settings to toggle news/security feeds in welcome panel\n- Added System Setting to toggle on automatic checking of package updates in Package Management\n- [#MODX-1751] Fixed erroneous reference in friendly alias setting description\n- [#MODX-1752] Fixed bug where topmenu items without children didnt show even if they had an action\n- Some css tweaks to login page\n- Updated to xPDO 2.0.0 r419 to fix xPDOVehicle bug\n- Fixed bug with Download Output button in MODx.Console\n- Ensure forgot login activation email is HTML\n- Added Forgot Login link and form to manager, sends an activation email to specified email if user forgot login/password\n- Fixed SQL sorting algorithm for package versions, added helper methods for comparing package versions\n- Added $resource to properties passed to OnDocFormDelete in resource/delete processor\n- Updated to xPDO 2.0.0 r417 ([#XPDO-40] Fixed getCount to work when passing a criteria with a class alias set)\n- Enhanced striptags output filter to take a parameter of allowed tags\n- Make sure $paths and $options are passed to OnCacheUpdate\n- Added compression/concat references to login and browser tpls\n- Fixed build.local.xml and build.xml scripts\n- Added compress_css system setting for compressed CSS for releases, moved over modx-theme.css to templates css/ dir. Don't use compress_css without first running _build/build.local.xml Ant task.\n- Cleaned up leftover PHP4 function definitions, unescaped SQL code, added proper accessor methods for private vars, other old code\n- Fixed bug with modLexiconLanguage::clearCache\n- [#MODX-1738] Fixed issue with FC TV rules not working as expected on Resource Update\n- Fixed bug where plugin event properties were getting merged if more than one plugin was associated with the event\n- Added loading mask to editing panels to prevent accidental editing before data is loaded\n- Added sanity check for OnRichTextBrowserInit event processing\n- Added fix for RTE loading in Resource panel, should fix most RTE saving bugs\n- Added collapsibility to Document panel\n- Added 'concat_js' system setting that will concat all the common JS files into one single file\n- Adjusted lang.js.php to properly use ETag header to cache lang js\n- Added css rule to prevent hidden iframes from being shown\n- Fixed bug where Resource Groups were not editable on Create Resource\n- Added sanity check for packages with missing provider\n- Added \"Updates Available\" column to packages grid, auto-checks provider for updates\n- [#MODX-1732] Added duplicate language ability to language grid\n- [#MODX-1741] Fixed possible bug with radio/cb tv labels\n- [#MODX-1593] Fixed bug where User could not be added with no role in User Groups tree\n- [#MODX-1735] Properly URL encode link tags while still preserving = and &amp; in query string\n- [#MODX-1736] Fixed bug with assigning TVs to Resource Groups\n- [#MODX-1740] Added workaround for SQL code to properly hide TVs with FC rules\n- [#MODX-1738] Fixed bug with radiogroups and set TV default FC rule\n- Fixed some header issues, _FILES content type handling\n- [#MODX-1733] Fixed bug that was stripping tags from connector processing\n- Ensured that Static Resource filename change fires dirty status\n- Made sure Set to Default fires dirty status for Resource panel\n- Fixed possible width stretching bug in TV panel in Resource edit view\n- [#MODX-1543] Added \"Rename Category\" to category nodes in element subnodes in Element Tree\n- [#MODX-933] Can now drag/drop Elements into Categories in the Element Tree to assign them to Categories\n- [#MODX-1729] Fixed incorrect filter name to be more appropriate to function\n- [#MODX-1727] Added missing Empty Cache checkbox to derivative resource panels\n- [#MODX-1724] Fixed bug with output renders in TV panel not triggering panel dirty status\n- [#MODX-1730] Fixed bug with $scriptProperties and login processor\n- Some cleanups to MODExt flow and ID referencing\n- Changed all GPC references in processors to $scriptProperties, which is loaded at entrance points to processors with GPC vars, pushing input handling to the connector\n- [#MODX-1711] Fixed bug with strip output filter\n- Added ellipsis output filter\n- Fixed various event callings across JS implementation to properly modularize modext components\n- Added events to user's groups grid to ensure dirty firing\n- Added MODx.FormPanel::markDirty\n- Added in CSS tweaks to accommodate Opera 10.5\n- Fixed bug with users grid if access permissions tab is removed\n- Fixed deprecated method definitions in modConnector classes\n- Fixed text in language settings to more accurately reflect function\n- Added area filter to Settings grid\n- [#MODX-1721] Disabled unnecessary paging on System Events table\n- [#MODX-1726] Added sanity check to ensure TV input type is properly set\n- Fixed bug with action buttons and continue stay method\n- Added UI for managing website field in modUserProfile\n- Added website field to modUserProfile\n- Removed unnecessary and problematic editor dropdown in chunk editing screen\n- Sped up drag/drop of reordering in tree by now only framing moved nodes instead of refreshing\n- Added modRequest::getParameters() method for retrieving various GPC variables or arrays of variables; automatically strips MODx GET parameters as necessary\n- modRequest::__construct() now creates references to all GPC variables in modRequest::$parameters\n- Modified modX::makeUrl()/modContext::makeUrl() to accept query string parameters as an array or string\n- Added modX::toQueryString() static method to turn associative array into a valid query string\n- [#MODX-1709] Fixed issue with encoding of action button parameter\n- [#MODX-1554] Prevented uploading of files to files themselves in directory tree\n- [#MODX-1700] Fixed issue with text referencing setting in lexicon entry\n- Ensure tags in a Static Resource content are parsed before trying to load the source path\n- Fixed static/weblink update js\n- Removed unnecessary and redundant table prefix check later on in setup\n- Fixed css/js properties in TV tab to let RTEs auto-determine the height of their TD fields\n- Fixed missing permissions reference on resource controllers\n- Added OnHandleRequest to modManagerRequest::handleRequest\n- Properly hides UI elements for Resource buttons/pages if user doesnt have permissions\n- Refactored modResource::cleanAlias() to allow various options, including built-in and custom transliteration capabilities\n- [#MODX-717] Foreign characters (UTF8 data) needlessly removed from alias\n- Hide top menu items if there are no submenus and if the topmenu is not clickable\n- [#MODX-1690] Fixed text for confirmation dialog when removing an Element to include name and type of Element\n- [#MODX-1707] Added mail_charset and mail_encoding system settings to control charset and encoding in emails\n- [#MODX-1706] Ensure that text and qtip fields in Resource/Element trees have any tags stripped\n- [#MODX-1699] Fixed bug in Quick Edit TV where it would erase the caption and replace it with the name\n- [#MODX-1704] Fixed erroneous if statement in clear button hiding in error log panel\n- [#MODX-1675] Added fix for windows paths on Edit File panel\n- [#MODX-1681] Added checks for issue with importing lexicon in Webkit-based browsers\n- Cleanups to TV input widths\n- Removing core RTE; too much work, may take back up in a later version\n- [#MODX-1697] Added ability to edit images and links in RTE\n- Added more robust MODx.rte.Selection API\n- Added missing changes to modActions needed to load lexicon entries for RTE\n- [#MODX-1662] Fixed mismatch in menus widget field label\n- [#MODX-1687] Fixed bugs in template package browser due to changes in modx.view.js\n- Made resource panel be a fileUpload-able panel for plugins\n- [#MODX-1357] Added richtext_default system setting\n- [#MODX-1685] Added MODxEditor, a core Ext-based RTE to be the default RTE for Revolution\n- [#MODX-1674] Stabilized MODx.Browser to work with core RTE\n- - Added missing registry.db.modDbRegister* classes to setup\n- [#MODX-1642] Logging out doesn't unlock resources: added modUser::removeLocks() and modified modUser::endSession() to call this method\n- Added OnInitCulture event to core transport data.\n- [#MODX-1672] Refactor collation/connection processors in setup to be more stable\n- Updated xPDO to r414 for improvements in xPDOManager\n- modInstall::writeConfig() uses new_file_permissions if specified or umask() settings by default\n- Removed superfluous calls to xPDO/modX::setDebug() and xPDO/modX::setLogLevel() in modInstall\n- modInstall::getConnection() now uses utf8_general_ci for charset/collation by default\n- [#MODX-1691] Set Quick Create/Update windows to use anchor property rather than width to adjust for resizing\n- Added 'cultureKey' setting to enable easier language translation in contexts/fe/components\n- Fixes to styling for MODx.Browser window\n- Added 'relativeUrl' parameter to MODx.Browser file data\n- [#MODX-1674] Fixes and stabilization to MODx.Browser, specifically when used by RTEs\n- Changing default editor from TinyMCE to blank value\n- Fixed bug in setup where inplace setting was being forced to 1\n- Cleaned up most processors, fixed wrong permission references, standardized code\n- Fixed welcome panel to only show panels with permission to see\n- Fixed error log view page to restrict viewing and clearing by permission\n- Added descriptive information to Roles grid\n- Lots of permissions fixes, other bugfixes and sanity checks to Element processors/controllers\n- Added propertyset permissions\n- Cleanups to Resource controllers, processors, optimizing of security permission checks\n- Fixed various bugs with search page\n- Fixed bug with adding policies that prevented partial regexp matches in name\n- Fixed bugs when adding new policies or permissions that showed prior added perm/policy in form\n- Properly secured and refactored recently edited resources grid\n- [#MODX-1670] Adjusted permissions to allow restricted user to edit profile\n- [#MODX-1667] Removed unnecessary opacity CSS rule in menus\n- Fixed bug where page wasnt reloading on login in certain situations\n- Make rightlogin div longer to support longer translations\n- [#MODX-1653] Fixed issues with related objects, removal of aggregates, and other packaging bugs. Introduced xPDOTransport::UNINSTALL_OBJECT, which defaults to true. When off, it will prevent an object from being uninstalled.\n- Updated xPDO to r413\n- [#MODX-761] Fixed language issue in setup, now sets it correctly and loads proper lexicon for login screen\n- Ensure console window appears above other windows\n- [#MODX-1663] Added MODx.msg.status, which shows a fading status message on a successful save. This also solves the issue of user feedback.\n- Removed unnecessary field from recently-edited-resource grid on welcome screen\n- [#MODX-1660], [#MODX-1037] Revamped login screen to HTML/CSS, basic form processing to allow browsers to save password in their password management systems\n- Revamped UI in new setup options, cleared up text, simplified presented options\n- [#MODX-18] Allow editing of MODX_CONFIG_KEY in setup welcome view\n- [#MODX-18] Prompt user for MODX_CORE_PATH if not found at beginning of setup\n- [#MODX-760], [#MODX-1080], [#MODX-1528] Added setup option to set new_file_permissions and new_folder_permissions in welcome view\n- [#MODX-760], [#MODX-1528] Removed new_file_permissions and new_folder_permissions system settings from setup\n- [#MODX-760], [#MODX-1528] Updated xPDO 2.0 to revision 407: new file and folder permissions determined from umask()\n- [#MODX-878] Stay buttons now action-specific, done through Ext state rather than PHP\n- Redo logic order of modPackageBuilder::buildLexicon to ensure languages are packaged in before topics\n- [#MODX-1647] Added width specification to force width of screen to prevent scrolling off of RTE TVs\n- Cleaned up tvTitle Form Customization rule by moving code from JS to PHP\n- Fixed z-index issue for windows due to IE fix\n- [#MODX-732] Added z-index force to topmenu for IE, fixed rightlogin div on topbar for IE\n- [#MODX-1641] Optimized and cleaned code dealing with Form Customization TV visibility and default values\n- [#MODX-1658] Fixed bug where placing a menu item in a submenu would place it in top level\n- [#MODX-1624] Enabled changing of text field in menu items\n- [#MODX-1656], [#MODX-1654] Fixed CSS gap in install summary in setup\n- [#MODX-1655] Fixed hardcoded lexicon strings in setup\n- [#MODX-1621] Remove unnecessary context menu items from items in Resource Group Resources tree\n- [#MODX-1627] Fixed incorrect menu in resource group tree resources when newly dragged\n- [#MODX-1599] Added manager_date_format system setting for customizing date formats for the manager\n- [#MODX-1651] Increasing width of setup navbar buttons to accommodate translations\n- [#MODX-1649] Fixed bug where Quick Create didn't respect default_template setting\n- [#MODX-1650] Fixed bug with language specification in setup to properly set cookie for Windows machines, and set initial language properly\n- [#MODX-1626] Fixed bug where top menus could not have actions\n- [#MODX-1494] Fixed issue where some settings dont have descriptions, and cleaned up deprecated settings\n- [#MODX-1645] Fixed incorrect lexicon key for setting_site_start_err\n- [#MODX-1646] Fixed issue where download buttons were staying grayed out if there was an error message\n- [#MODX-1644] Added SMTP mail settings to default system settings to allow global SMTP usage for all modMail functions\n- [#MODX-1606] Fixed bug in modRestCurlClient class due to encoded ampersand\n- [#MODX-197] Refactored Action Buttons JS, added 'actionNew', 'actionContinue', and 'actionClose' events to MODx.FormPanel objects, ensured parent/context_key is persisted through add another resources\n- Added a couple sanity checks to modRestCurlClient\n- Added JS to disable install button when clicked in setup to prevent double-clicks\n- controllers/resources/create: Refactored template inheritance to occur before any delegate controller is called.\n- processors/resources/create: Moved OnBeforeDocFormSave event invocation until after POST vars are applied to $resource object.\n- processors/resources/create: Refactored common code to be executed before any delegate processor is called.\n- processors/resources/create: Refactored to respect add_children and new_document_in_root permissions.\n- Added various access_denied lexicons to the resource topic.\n- Added new_document_in_root permission to control access to creating Resources at the root level.\n- Updated to xPDO 2.0 revision 406.\n- [#MODX-1606] Added sanity checks and ID standardization to DOM nodes for Package Browser\n- Fixed possible bug with ta-toggle div in resource panel\n- [#MODX-1628] Fixed FC tvDefault rule by doing setting php-side\n- [#MODX-1636] Added ability to assign Role to User when adding them to a User Group from the User Groups tree\n- [#MODX-1634] Fixed bug with resource/resourcegroup/getlist processor that prevented showing of resource groups in new resource panels\n- [#MODX-1639] Fixed bug where resource panel JS didnt check for existence of possibly hidden access permissions grid\n- Fixed modUser::removeSessionContext() to call modUser::endSession() if no contexts are left\n- Fixed modUser::endSession() to destroy all SESSION data and the session cookie\n- Fixed bug in Plugin -> System Events tab caused by invalid function call in getlist processor\n- Fixed problems with various deprecated functions to increase compatibility with Evo and avoid performance issues:\n * modX::getDocuments() and modX::getDocument()\n * modX::getAllChildren()\n * modX::getActiveChildren()\n * modX::getDocumentChildren()\n * modX::getDocumentChildrenTVars()\n * modX::getParent()\n * modX::getPageInfo()\n * modX::getUserInfo()\n- Fixed modX::__construct() declaration to indicate it properly as a public method; added phpdoc comments.\n- Fixed modX::sanitize() declaration to indicate it properly as a static method.\n- Updated to xPDO 2.0 revision 405\n- [#MODX-1614] Fixed issue with cached pages going to unauthorized_page instead of error_page when user does not have load permission\n- [#MODX-411] Set system setting: emailsender to the admin email address during install\n- [#MODX-1556] Show class and id for deleted resources or elements in Manager Action Log\n- [#MODX-1552] Create New element Here shows for root elements but not those in categories\n- [#MODX-1625] Fixed bugs with menu tree preventing creating child nodes of new items, restyled menu and action icons\n- Added preventative to make sure packages are only downloaded once when in Package Browser\n- [#MODX-1623] Fixed package installation error: attempting to preserve files fails with error message\n- Updated to xPDO 2.0 revision 404\n- Setup upgrades no longer preserve existing data/files on install\n- Fixed issue with setup trying to write connector files regardless if files are already in place\n- Updated to xPDO 2.0 revision 403\n- Fixed bug where plugin properties were not being injected into the plugin event call\n- [#MODX-1617] Fixed bug with tvDefaultValue Form Customization Rule\n- [#MODX-1619] Added sanity check for modActionDom constraint check\n- [#MODX-1620] Fixed missing or incorrect lexicon entries across ui\n- [#MODX-1612] Fixed bug where Create Menu button was not working\n- [#MODX-1616] Renamed \"field\" to \"name\" in Form Customization rule windows\n- Removed any non-essential JS from the top menu items\n- Added additional check and error logging for processor_path option in modX::executeProcessor().\n- Added missing view_sysinfo permission to default Administrator policy\n- [#MODX-1595] Fixed bug regarding hiding top menu items with permissions\n- [#MODX-1596] Fixed bug related to creating a new top menu item\n- Fixed issues related to usergroup panels and anonymous usergroup editing\n- Fixed bug in template viewer for package browser that wasnt paginating right\n- Added modRestServer for generic REST request handling\n- Enable remote sorting and sorting by ID on Users grid\n- Fixed and enhanced search field on Users grid\n- Fixed bug with duplicating a context where only the first level would duplicate\n- Updated to xPDO 2.0 revision 396\n- Fixed bug where package version info wasnt being computed on download/scanlocal\n- Added check for locked status on resources, now shows locked status in tree, as well as who is editing\n- [#MODX-1592] Fixed bug with usergroup create by moving it to a window\n- [#MODX-1590] Fixed missing processors for ACL grids\n- [#MODX-1526] Added permissions resource_tree, element_tree, file_tree that restrict rendering/viewing of the left-side trees. Must be applied to access policies.\n- [#MODX-625] Adjusted text in config.inc.php writable warning message\n- [#MODX-1586] Fixed toolbar rendering bug in user settings due to hidden div, now using hideMode: offsets\n- Added search for user box in usergroup users grid\n- Changed User Group users grid to a non-local grid, now supports pagination and proper validation\n- Enhanced UI for editing User Group Context/ResourceGroup ACLs\n- [#MODX-1525] Added permissions field to modMenu to define policy permissions required to see Top Menu items\n- Fixed bug in Packages grid to properly show provider name\n- Added modRestResponse class, improved error handling for REST-based package management\n- Added verification for Providers, now check to make sure they can connect before being added or updated\n- Added Package View page to Package Management, allowing you to view more info about a package, view prior installed versions, and remove older package versions\n- Fixed typo in setup script for PM changes\n- Added version_major, version_minor, version_patch, release, and release_index fields to modTransportPackage tables to assist sorting and organization\n- Fixed bug in transport schema\n- [#MODX-1571] Fixed xtype in automatic_alias setting\n- [#MODX-1572] Fixed deprecated error in PHPMailer service\n- [#MODX-1512] Fixed bug with MODx.tree.Tree::refreshNode that caused a strange duplicate node error\n- Updated xPDO to revision 392 to get new nested condition features\n- [#MODX-1515] Fixed date picker CSS\n- [#MODX-923] Added file path to config.inc.php configcheck message on welcome page\n- [#MODX-1579] Added code to prevent invalid characters from being used in admin username/password in setup\n- [#MODX-1575] Fixed bug with Resource Group getList processor\n- Updated to xPDO 2.0 revision 389\n- Added validation to modContext.key field; must be a valid PHP identifier without underscore characters\n- Modified modError::checkValidation() to call modError::addField() for each validation message\n- [#MODX-1562] Cleaned up Site Schedule grid to properly load baseParams during refresh and adjust pagination\n- Cleaned up processor code, plugin invoking, access permission checks in processors\n- [#MODX-1562] Fixed bug in Site Schedule data\n- Fixed OnDocUnpublished and OnDocPublished calls in processors to pass modResource reference\n- [#MODX-1564] Fixed bug causing combo values to get overridden if they were set before the combo store loaded\n- Move element and resource prerender plugin events to after js registering to allow for proper event execution order\n- [#MODX-986] Added \"Duplicate Context\" to Resource tree, as well as \"Remove Context\"\n- Fixed bug with default provider on package management UI\n- [#MODX-1540] Fixed last login display in Welcome page\n- [#MODX-1567] Enabled sorting in Reports -> System Info -> Recently Edited Documents\n- [#MODX-1522] Restricted user editing to just the save_user permission\n- Added a \"reload\" button to the error log\n- Fixed Active Resources on Reports - System Info\n- Fixed database version query in Reports - System Info\n- [#MODX-1560] Added a button to truncate manager log\n- Added new browsing view for Templates in Package Management; thumbnail-based browsing.\n- [#MODX-1534] Revamped file edit page to match other page structures\n- [#MODX-1542] Added missing undelete permission to basic Resource policy\n- [#MODX-1539] Added view_user permission to solve dropdown combo users bug that needed \"edit_user\"; view is more applicable there\n- [#MODX-1553] Show current permissions in chmod window\n- [#MODX-1539] Fixed a few bugs with the manager log page\n- [#MODX-1530] Fixed permission reference in resource create/data\n- [#MODX-1532] Fixed bug in permissions reference when trying to remove element from property set\n- Fixed bug with login page and new controllers location\n- Enhanced provider home page to allow links for newest/most downloaded packages\n- Added sorting to Access Policy grid, cleaned up getList processors across site\n- Fixed Manager Log page to properly display content, log the right class key, and now display the name of the object edited\n- Enhanced Property Sets page to now allow you to edit specific implementations of Property Sets per element, as well as the default set\n- Added \"disabled\" checkbox to Quick Update Plugin\n- Fixed bug in modManagerResponse dealing with CMPs and templating paths\n- Moved controllers/* files to controllers/default/ to allow for custom manager templating\n- Fixed bugs with Property Sets not showing correctly in dropdowns\n- Updated xPDO to revision 385 to fix cache_db functionality broken by PHP 5 only changes\n- [#MODX-1514] Added css for pointer cursor to top menus\n- [#MODX-1513] Added check for SimpleXML to installer\n- Add sanity check to make sure languages arent erased on package uninstall\n- Removed confirm dialog for remove action on Access Permissions grid\n- Fixed panel layout for Access Policies, User Group editing\n- Fixed E_STRICT warning on modX::getCacheManager() [method signature did not match xPDO::getCacheManager()]", "MODX Revolution 2.0.0-beta-5 (LastChangedRevision: 6224, LastChangedDate: 2009-12-15 10:03:36 -0700 (Tue, 15 Dec 2009))\n====================================\n- Fixed bug where Set to Default on Resource TV panel was hidden unless you clicked Reload\n- Fixed some bugs with Property Sets editing\n- Fixed bug where download wasnt working for package management due to missing provider\n- Fixed bug where quick create Static Resource wasnt loading MODx.Browser\n- [#MODX-1496] Fixed issue with scrolling context menus not working on local grids\n- Fixed styling in welcome panel\n- Shrinking top menu a bit to fit in smaller window resolutions\n- Fixed invalid method reference in modInstallTest derivative classes\n- Fixed styling and JS in TV pane\n- Fixed error with charset reference in setup/\n- Clear Search in Package Browser when clicking on a Tag\n- Added Search bar to Package Browser, now can search entire repository\n- Fixed height of Package Browser to not go too far down screen\n- Fixed modRestSockClient to properly strip HTTP headers and return only XML\n- Added modStaticResource methods: getSourceFile() and getSourceFileSize()\n- Fixed bug in setup/ script with new transport package fields\n- Fixed modCacheManager to not cache reg* calls that will cause breakage on similar calls to reg* method\n- Added 'package_name' and 'metadata' fields to modTransportPackage for future development\n- Fixed styling commits; also fixed bug on Package Management when not selecting default provider\n- Added help buttons to Resource pages\n- Moved TV categories in Resource edit page to tabpanel, also cleaned up button styling\n- Fixed table styling. This is temporary until all tables are ported to ext grids. This affects welcome pane, system info, and online users.\n- Fixed bug where package browser would close on ESC key\n- [#MODX-1489] Allow spaces in Category names\n- [#MODX-1497] Fixed username not being sent in new user email\n- Fixed NOT NULL error in modManagerLog\n- Revamped Package Management UI, changed Provider hooks to REST-based, massively improved downloading UI\n- Fixed styling on the search page.\n- Fixed styling on the actions page.\n- Fixed styling on the manager logs page.\n- Fixed triggerfields in windows in Safari\n- Changed the text-size and and top margin of the Main Navbar Submenu span for more readability.\n- [#MODX-1426] Added connect check to assist with mysql_get_server_info in setup\n- Few style changes: Changed Button style text color to black - Previously it appeared that buttons were disabled. Changed Text color inside of combo boxes to black - As before it looked like the element was disabled.\n- Modified the date fields to show a drop-down box rather than the date image. Changed the text-size and spacing of the Main Navbar to 12px.\n- Fixed styling of the welcome panels.\n- Fixed some issues with OnDocFormSave, plus standardized how to render fields/html to update forms\n- Fixed bug with default values, @ bindings and other things on checkbox/radio TVs\n- Prevent tree from expanding too much on quick create, cleaned up js\n- Assigned user id/username to [[+modx.user.id]] and [[+modx.user.username]] for easier access\n- Cleaned up last PHP4 remnants to PHP5-only\n- [#MODX-1483] Fixed bug with TV saving in resource create processors\n- Recompiled MODx.Console to use Ext.Direct, now should be a bit more stable. To end a MODx.Console session, pass 'COMPLETED' to the registry.\n- Resizing the left tree now properly resizes content in the right panel and is stateful\n- Added resizability to leftbar tree\n- Removed no-longer-necessary js file references in resource controllers\n- Consolidated filetree css/js into main css/js files\n- Fixed logic error that caused removing setup directory to fail\n- Combined some common JS files, cleaned up login page css, other optimizations\n- Consolidated filetree extension CSS, removed unnecessary filetree files\n- Consolidated CSS files in templates/default/css to one single file to reduce load times from @imports\n- Added rowactions to package grid\n- Improved code in @DIRECTORY binding to be more efficient and take advantage of DirectoryIterator\n- [#MODX-1478] Fixed @SELECT binding\n- [#MODX-1474] Fixed bug with multiple list-boxes\n- [#MODX-1476] Fixed bug with TV default values with non-inherit tvs, also bug with radios/checkboxes and set to default\n- [#MODX-1479] Fixed bug with duplicate DOM ids in User Group tree\n- [#MODX-1480] Fixed bug with wrong permission reference in property set remove processor\n- Added emptyText to local and property grids\n- [#MODX-1477] Added emptyText config param with default 'No data to display' message to empty MODx grids\n- documentObject was not getting set from cached Resources.\n- Added inline help that loads official MODx documentation in a window\n- [#MODX-900] Fixed erroneous text on site_status setting description\n- Added (Inherited Value) flag to TVs that are inheriting their value\n- Added category titles to TV editing panel\n- [#MODX-1354], [#MODX-1475] Fixed @INHERIT and other bindings in TV inputs\n- Fixed bugs with dirty status not firing for certain TV input types\n- Fixed CSS for login page\n- Fixed issue where default connection charset was not persisting in setup for upgrades\n- CSS tweak to get windows working properly\n- Major styling updates (thanks lossendae!)\n- [#MODX-1473] Fixed bug with modUser and modUserProfile PK's getting mixed, causing errors if PKs for each object were different\n- Added city field to user UI\n- Optimizations to Resource panel\n- [#MODX-1466] Made \"back\" from Access Policy edit redirect to Access Controls page, made Access Controls tabs stateful\n- [#MODX-1471] Added scrollOffset: 0 to grids to hide empty space on right side\n- [#MODX-1469] Fixed dir handling in setup\n- [#MODX-1388] Updated documentation for modX.getTree and modX.getChildIds\n- [#MODX-1318] Prevent ordering of elements in dragdrop since order defaults to alphanumeric\n- Made charset in setup/ a dropdown of available charsets\n- Fixed collation grabbing for setup/\n- [#MODX-1090] Added 'Rename File' window to directory tree\n- Vast improvements to setup, including removing of mootools, using ExtCore now, simplified UI workflow to remove unnecessary AJAX calls, added in database creation checking, collation specification, etc\n- Fixed bug with modPackageBuilder that would ignore the specified path for a Namespace\n- [#MODX-1207] Changed modSession.id column to varchar(40) to support session.hash_function=1 with session.hash_bytes_per_char=4.\n- Simplified and optimized session handling, removing older PHP workarounds and adjusting preset system settings.\n- Make sure non-static Resources with binary content types get processed and output.\n- [#MODX-1450] Added paging to Template combobox to allow for large numbers of templates\n- [#MODX-1443] Tree sorting now works for modMenus\n- Removed deprecated system settings from build\n- [#MODX-1448] Fixed issue with container checkbox not persisting\n- [#MODX-1426] Fixed issue with MySQL checks on non-standard\n- [#MODX-1437] Fixed duplicate policy\n- Fixed some issues with Form Customization\n- Added 'address' field to modUserProfile\n- Added ability to edit the (anonymous) user group from the user group editing panels\n- Fixed typo in usergroup get processor\n- [#MODX-1018] Fixed bug with having to click the Clear Filter button in a settings grid twice\n- [#MODX-1380] Fixed bug with expanding node when quick creating a resource in it\n- [#MODX-1326] Fixed the access denied logout form, added styling\n- [#MODX-1423] Fixed error with duplicating a template\n- [#MODX-1409], [#MODX-919] Fixed issue where tag symbols were being stripped in Elements and breaking filtering and nested tag functionality\n- [#MODX-1347] Fixed user validation for username missing error\n- Extrapolated RTE logic to make it generic\n- Added OnRichTextBrowserInit to allow for 3rd Party RTEs to hook into MODx.Browser\n- Added system setting \"allow_multiple_users_per_email\" to allow users to have a single email shared across users. Defaults to true.\n- [#MODX-972] Fixed bug when property description was changed, grid wasnt updating\n- [#MODX-1390] Fixed docs for $modx->sendUnauthorizedPage();\n- [#MODX-895] Fixed possible rendering issue with error log scroll bar\n- Optimized setup pre-install checks, now checks both mysql client and server versions\n- [#MODX-1404] Fixed mysql version checks to only show a warning if the client/server is incorrectly setup to where PHP cannot determine the versions.\n- Package Management now restricts downloading/updating Extras to their supported MODx versions (ie, you can't download packages that support only beta-3 if you have beta-4 or beta-2)\n- [#MODX-1310] Fixed expand/collapse toolbar items in trees\n- [#MODX-1361] Make sure cache (including Smarty files) is cleared after install\n- [#MODX-1372],[#MODX-1376] Marked deprecated functions as so in phpdoc comments\n- [#MODX-1378] Fixed bug with adding a None role to a user group in the User -> Access Permissions tab\n- [#MODX-1375] Fixed documentation for modX.getRequest\n- [#MODX-1374] Fixed documentation for modX.getRegisteredClientScripts\n- [#MODX-1370] Fixed quick create to set modResource type to modDocument properly\n- [#MODX-1373] getLoginUserName and getLoginUserId now return boolean false if no user is logged in\n- [#MODX-1369] Fixed validation errors and possible loophole in error processing for user processor flow\n- Fixed column alignment with radio/checkbox TV inputs\n- [#MODX-1350] Fixed issue where reset to default wasnt working with radio TV inputs\n- [#MODX-1360] Fixed issue where publishedon was being reset in quick update\n- Sanity fixes to misc processors\n- Added access modifiers to methods in modElement\n- Moved name character sanity checks for Elements to element class.\n- Cleaned up element processors, added missing permission checks, filled out plugin event calls\n- [#MODX-1355] Fixed erroneous label for quick create resource on Contexts\n- [#MODX-1352] Remove stay-buttons from user update screen\n- [#MODX-1349] onDirty now fires on triggerfield-based TVs\n- Cleanups to getList processors, bugfixes for grids\n- [#MODX-1317] Fixed erroneous label for quick create resource; should be Document\n- [#MODX-1316] Added menu title to quick create/update resource\n- Fixed issues with User grid\n- [#MODX-1325] Fixed console's download to file functionality\n- [#MODX-1327], [#MODX-1340] Fixed issue with generation of new password\n- Fixed locking\n- Lots of PHP5-only optimizations", "MODX Revolution 2.0.0-beta-4 (LastChangedRevision: 5880, LastChangedDate: 2009-10-19 09:04:47 -0500 (Mon, 19 Oct 2009))\n====================================\n- If memory limit is lower than 24M, force to 128M if possible\n- Fixing setup text for memory limit checks.\n- [#MODX-1080] Make sure traditional distribution doesnt need base directory writability\n- Added modInstallTestSvn class for handling SVN-specific setup tests\n- Fix to setup contexts controller to read existing paths on upgrade.\n- setup/ memory_limit checks now only need to be 24M for setup/ to run.\n- Updated to xPDO 1.0 revision 363 to fix \"Error saving changes to parent object fk field action\" messages being logged during install.\n- Fixed issues with category remove dialog and lexicon topic grid\n- [#MODX-1294] Fixed possible obscure problem when using Preview after changing the alias in a Resource\n- [#MODX-1278] Fixed issues with checkbox TVs and default values, fixed the 'set to default' button for complex inputs\n- [#MODX-1280] Fixed issues with the user create processor\n- Added OnBeforeUserActivate, OnUserActivate events\n- Added 'active' boolean field to modUser. Defaults to 1.\n- Added OnCreateUser, OnDeleteUser, OnUpdateUser events\n- [#MODX-1170] Fixed issues with Export Topic\n- [#MODX-912] Fixed isinrole/ismember output filter\n- [#MODX-677] Made capitalization consistent on Resource edit/create screen\n- [#MODX-1251] Fixed issue with server offset displaying incorrectly\n- [#MODX-896] Fixed issue with server_offset setting description\n- [#MODX-928] Fixed issue where parent resource wasnt refreshing properly\n- [#MODX-777] Made consistent the checkDirty behaviour of save buttons across manager\n- [#MODX-938] Added check to build to check if core+core.transport.zip were removed before build starts.\n- [#MODX-629] Added missing automatic_alias setting to build\n- [#MODX-790] Fixed issue where couldnt browse back to root directory with MODx.Browser\n- [#MODX-902] Fixed empty warning message for removing category\n- Fixed bug with removing categories\n- Fixed issue where couldn't drag a resource onto a resource with no children\n- [#MODX-1130] Fixed issue with parent triggerfield; also redid how tree hrefs load so that clicking on a node in the tree to load url can be disabled\n- [#MODX-1133] Fixed issues with hotkey behavior\n- [#MODX-1230] Fixed issue where drag Resource to symlink/weblink content field would add tags as well\n- [#MODX-1273] Added OnLoadWebPageCache event invocation to modRequest->getResource().\n- [#MODX-1273] Fixed events in User update/create form\n- Enabled compression of manager JS scripts by changing the Setting \"compress_js\" to true.\n- Upgraded ExtJS to ExtJS 3.0.2\n- [#MODX-1270] OnManagerCreateGroup and OnWebCreateGroup events now fire\n- [#MODX-1237] Fixed warning in modParser with regards to uninitialized variable\n- [#MODX-979] Added password_generated_length (the length of the auto-generated password) and password_min_length (the minimum length for a password)\n- Cleaned up usergroup processors\n- Added sanity checks to usergroup processors\n- Prevent possible issue on usergroup update that would wipe related objects\n- Prevent possible issue that would allow user to remove Administrator group\n- Removed some legacy todo statements\n- Moved Element category reset on modCategory object remove to modCategory class\n- Cleaned up modResourceGroup, modTemplate helper methods\n- Added modUser::joinGroup(group,(optional)role) and modUser::leaveGroup(group) for easier development\n- Optimized getrecentlyeditedresources processor\n- Make sure config.js.php outputs proper headers\n- Commented out Content-Length headers on lang.js.php, for some reason was slowing down servers\n- [#MODX-1256] Fixed issue with Resource tree not being visible in Resource Groups page\n- Fixed issues with Import HTML/Resources pages; properly convert to MODExt\n- [#MODX-1202] Fixed issue where Element name was missing in Duplicate window\n- [#MODX-1233] Fixed bug where categories could only be renamed once before needing to reload page\n- [#MODX-1248] Fix bug that could wipe TV values if tab wasnt loaded\n- [#MODX-1241] Fixed Preview button on update panels\n- Prettying up of TV fields\n- Now display SVN revision number with version in top left of mgr header\n- Fixed issues with TVs setting values incorrectly\n- Added \"Set to Default\" button on TVs that will reset the TV's value to it's default value. TV Resource values can now be set to blank as a valid value.\n- [#MODX-924] Fixed errors in various system setting descriptions\n- [#MODX-935] Tooltips in Resource tree now do not show if no description or longtitle is set\n- [#MODX-1120] Now shows TV names in tag form below the caption in the TV editing panel in Resource editing\n- Fixes to plugin event calls in controllers\n- Fixes to filetree to enable in Ext3\n- [#MODX-1112] Fixed issue where checkboxes in grids werent firing dirty statuses\n- [#MODX-1229] Fixed issue where default hidemenu setting in Create Static Resource was setting incorrectly to true\n- Added some extra variables for RTE firing; also made sure MODx.loadRTE fires on new resource creation. Fixes [#TINYMCE-9], [#TINYMCE-8]\n- [#MODX-523] Fixed copy issue in console by providing \"Download to File\" link\n- [#MODX-649] Fixed issue where comboboxes were not loading proper displayValue when first rendered\n- Added category combobox to quick update/create windows\n- [#MODX-1019] Added missing site_unavailable_page System Setting.\n- [#MODX-1226] Removed modResource->checkChildren() method; isfolder should not be set based on presence/absence of children.\n- [#MODX-1213] Fixed issues with WebLink creation and loading\n- [#MODX-1178] Fixed issue where checkbox TVs were unable to be set to false; properly rendered values into a hidden field\n- [#MODX-1204] Implemented $matchAll for modUser::isMember, that allows exclusive and inclusive group membership checks\n- [#MODX-1203] Now preserves state of open tabs in left bar\n- Added \"Form Customization\" page, which emulates Evolution ManagerManager functionality and integrates it into the core\n- Revamped modMenu DB structure to allow for more proper dynamic menus; 3PCs will need to now refer to the Components menu as 'components', as the \"id\" field has been dropped and \"text\" is now the PK\n- Fixed DOM issue with Profile page\n- Improved core transport build script, lowered build times\n- Fixed issue where hiding the alias field would cause it to be erased\n- [#MODX-1169] Fixed issue where unchecking Container on a Resource that had children would hide them from the tree\n- [#MODX-1125] Fixed issue where Properties were being lost on new Elements\n- Fixed some dirty field problems in Element/Resource forms\n- [#MODX-1167] Improved isFolder checkbox tooltip\n- [#MODX-929] Changed default click functionality in Tree menu to edit Resources, unless does not have permission to, will then go to View\n- Fixed navbar structure on main menu to properly handle infinitely deep nested menus. Needs help from a CSS guru on the CSS end.\n- [#MODX-1161] Fixed bug with height argument on modX::getParentIds\n- Documentation updates to modResource class\n- [#MODX-1189] Fixed issue with TV values not setting properly with modTemplateVar->setValue\n- Added modResource->getTVValue, which gets the value of a specified TV for the Resource\n- [#MODX-1177] Adjusted Lexicon Management text to properly represent functionality\n- Added more metadata to Lexicon Topic exports\n- [#MODX-1191] Fixed issue where Namespace combo was conflicting with other DOM IDs in Lexicon Management\n- Changed Accordion to Tabs in left menu\n- In all Resource panels, Moved Page Settings back to right side, moved Template to top, moved Published to top right\n- [#MODX-1173] Added modResource->hasChildren() function. Returns # of children for the Resource.\n- [#MODX-689] Fixed error when using @SELECT binding with Template Variable Input Option values.\n- Fixed issues with modMenu creation/editing\n- [#MODX-1132] Various fixes to the user editing page\n- [#MODX-1123] Fixed bug where properties were not saving on new elements\n- [#MODX-683] Changed title for 1st tab on Resource edit screen\n- [#MODX-1118] Tweaked MODx.combo.ComboBox and other store references to possibly fix local store bug\n- Fixed issue with Sort By dropdown in the Resource Tree\n- Fixed issues with User Group update page\n- Added modAccessPermission class to properly handle access policy permissions\n- Adjusted UI to handle model change\n- Added logic in setup install to clear sessions table after install to prevent access permission changing problems (and is a good general practice anyway); users will have to re-login after setup/ is run.\n- Cleaned up access policy grid\n- Default sort roles by authority\n- Removed no-longer needed Security pages; now done in Access Control and User Group edit screens\n- Started cleanup of Security system; changed 'Authority' listing on User Group page to a more correct \"Minimum Role\".\n- Added some IDs to resource edit page\n- [#MODX-1124] Took Templates off the list of attachable elements in Tools | Property Sets", "MODX Revolution 2.0.0-beta-3 (LastChangedRevision: 5593, LastChangedDate: 2009-07-30 11:14:17 -0500 (Thu, 30 Jul 2009))\n====================================\n- Fixed issue with scrollbars and height in tree context menus\n- [#MODX-963] Fixed issue with scrollbars and height in grid context menus\n- Fixed possible error in lang.js.php\n- [#MODX-982] Added param stringLiterals to directory/getList processor\n- [#MODX-978] Updated PHPMailer to 2.0.4\n- [#MODX-960] Fixed DOM issue with User Group creation/editing screen\n- Added ability to drag/drop files in file tree into fields\n- Fixed issue with file tree hiding files\n- [#MODX-960] Fixed erroneous header in Manage User Groups and Roles\n- [#MODX-965] Removed Disabled field from Package grid since it currently is unapplicable\n- [#MODX-964] Fixed issue with toolbar buttons in package download tree by removing unneeded buttons, fixing refresh button\n- [#MODX-966] Changed Package Management grid to be easier to read, removed unnecessary information\n- [#MODX-962] Fixed issues with User panel screen\n- Replace deprecated split() call in magpierss class with explode().", "MODX Revolution 2.0.0-beta-2 (LastChangedRevision: 5416, LastChangedDate: 2009-07-16 13:15:41 -0600 (Thu, 16 Jul 2009))\n====================================\n- [#MODX-1029] Fixed incorrect URL references in browser controller template\n- Updated version info for beta2 release\n- [#MODX-942] Made sure all get-based processors use REQUEST, not POST\n- [#MODX-937] Added 'Download Extras' button to package grid which loads modxcms.com provider\n- login processor does not return site_url in response by default.\n- modResponse->outputContent() allows programmatic options to configure max_parser_iterations.\n- Updated xPDO to revision 341: package uninstall preserves and restores file resolver data\n- Changed key shortcuts to always require ctrl+shift to prevent browser collisions\n- Added in field for description key in modMenu windows\n- [#MODX-931] Added isequal, isequalto, and notequalto as modifier aliases to default Output Filter\n- Fixed issues with pagination on settings grids\n- Fixed ENTER key issues on quick create/update windows\n- Added &language option to lexicon tags.\n- Added ability to load lexicon topics via tag: [[%key? &namespace=`mynamespace` &topic=`mytopic`]]\n- [#MODX-910] Fixed issues with gte/lte/gt/lt output filters\n- [#MODX-921] Added \"isempty\" as an alias of \"ifempty\" in output filters\n- [#MODX-920] Fixed wordwrap output filter\n- [#MODX-914] Added isnotempty and hide output filters\n- [#MODX-913] Added isloggedin and isnotloggedin to output filters\n- Upgraded ExtJS from 2.2 to 3.0\n- [#MODX-925] Fixed issue where name couldnt be changed on duplicate resource window with resources with children\n- [#MODX-911] Fixed dragability issue when assigning resources to resource groups\n- [#MODX-901] System Settings grid search now searches descriptions\n- Added 'afterLayout', 'loadKeyMap', and 'loadAccordion' events to MODx.Layout\n- Fixed bugs with File TV input renders\n- [#MODX-887] Properly standardized POST/REQUEST access methods for element processors\n- Fixed issues with user emails being sent in plaintext with no linebreaks; now HTML-based for the time being\n- Package Download tree now disables already downloaded packages.\n- [#MODX-885] Fixed missing break statement in cat output filter\n- [#MODX-844] Fixed ucfirst output filter, added ucwords output filter\n- [#MODX-869] Added missing descriptions for certain menu items\n- [#MODX-868] Fixed bug on settings grid where filter box was not firing on enter key\n- Fixed bug where hidemenu was not persisting in Quick Update Resource\n- Fixed bug with tree mask rendering before panel is rendered\n- [#MODX-747] Fixed issues with access grids update windows\n- [#MODX-803] Fixed DOM issues with TV mgr input property renders\n- [#MODX-805] Fixed attribute issues with TV web output renders\n- [#MODX-859] Changed login page loader box to say 'Loading...' instead of 'Saving...'\n- [#MODX-860] Fixed z-index issues across manager\n- Added a custom loadMask to MODx.tree.Tree objects to display when they're loading but not affect page focus\n- Added a custom loadMask to the Package Management download tree to display while loading the remote provider payload\n- Added in icon for package files\n- Added fsockopen as a fallback for transport package if allow_url_fopen or cURL is not enabled\n- [#MODX-856] Added cURL method of grabbing transport packages when allow_url_fopen is set to false\n- Fixed bug in property update where list grid was not hiding if list xtype was previously selected but not now\n- Fixed import properties where it was not properly handling descriptions\n- Fixed bug where ExtJS couldnt handle text/json header responses with fileUpload set to true in form panels\n- Fixed some DOM issues with Package Management\n- [#MODX-833] Temporary fix for modManagerLog message showing up in console\n- [#MODX-853] Changed source caption of view resource data\n- [#MODX-809] Adjusted formatting of View Resource data fields\n- Fixed bugs with Resource data page not loading fully, glitching tree\n- [#MODX-772] Fixed bug where plugin events were not showing enabled if filtered by name\n- Fixed user system event calls to pass proper arguments\n- Fixed bug where you could only load 1 Quick window at a time\n- Fixed bug with duplicate resource\n- [#MODX-845] If no setup options are specified, package installation will automatically proceed\n- Added parameter to the getNodes processor for resources/elements called 'stringLiterals' which, when true, does not encode the JS literals\n- Layout can now be toggled between tabs (default) and portal panels via the setting 'manager_use_tabs'\n- Nuked the Loading Box in MODExt\n- Changed clearCache key shortcut to CTRL+U (CTRL+SHIFT+U for PC users)\n- Fixed issue where folder resources couldnt be drag/dropped\n- Added some key-events: CTRL+H for hiding accordion, CTRL+U for clearing cache, CTRL+N for Quick Create Resource (PC users will need to add SHIFT to all those calls)\n- Fixed portal issues with Safari\n- Added a few events to MODx. JS object, cleaned up code\n- Added sanity checks to context/category create/update processors\n- [#MODX-766] Added check to prevent settings starting with numbers\n- Added ability to update plugin events and dynamically manage plugins associated with them by right-clicking on them in the Plugin Event grid\n- Added 'beforeSubmit' listener to MODx.Window\n- Adjusted TreeDrop code to allow for RTEs to utilize drag/drop features\n- [#MODX-827] Fixed typo in resource container help string\n- Added prevention fix to prevent dragging of non-elements/resources into content panes\n- [#MODX-770] Fixed bug with creating Symlink\n- Fixed issues with creating and editing a static resource\n- Fixed bug with treedrop that set boolean values to string representations; changed to 1/0\n- Fixed missing context menu item to remove new properties in a property set\n- Added functionality for Element Tag Builder to use descriptions of properties\n- [#MODX-817] Redid Clear Cache window to use MODx.Console\n- Lexiconized missing \"Copy to Clipboard\" string\n- Slight tweaks to MODx.Console to get messages to display final ending messages properly\n- Changed invokeEvent missing event warning to debug msg to prevent it from logging in every console output\n- [#MODX-818] Fixed issues with Quick Create where it didnt work in FF, missing lexicon strings\n- Added Visual Element tag builder when you drag/drop an element into a field\n- Resources/Elements can now be dragged from tree straight to Resource Content pane.\n- Removed Spotlight effect on dialogs; was unnecessary.\n- Fixed bug in Namespace creation window that was preventing namespace from creating\n- Added refreshes to comboboxes in Lexicon Management to refresh combos on Namespace/Topic creation to keep panels up-to-date\n- Fixed Safari issue with Element tree displaying funky on certain pages\n- Fixed issue in Safari where combobox trigger was on left side\n- Only set lexicon entries for context/user settings if they dont exist as system settings\n- Fixed issue with Actions panel causing accordion DOM to bug\n- Fixed issue with Quick Update not persisting class_key\n- Fixed some issues with persistent settings for Quick Update Resource\n- Fixed issue with Quick Update Resource content field being too long\n- Fixed invalid lexicon entry reference for quick create resource\n- Added Quick Create/Update Resource\n- Preview context menu option now is \"smart\" and builds FURLs and separate context references\n- Fixed invalid topic reference issue with modLexiconEntry::clearCache()\n- Fixed headers for connector responses\n- Added Quick Create/Update for all Element types\n- Fixed bugs with category setting in Element processors\n- Added Clear Cache checkbox option to all Element type forms\n- Fixed bug with Category dropdown\n- Fixed tv input properties forms from double-rendering\n- [#MODX-804] TV fields now fire resource change event\n- Fixed bug in Safari with TV fields being uneditable if panel is dragged\n- [#MODX-745] Added 'cancel' button to go back to policy page when updating a policy\n- [#MODX-573] Removed no-longer-applicable 'role' column from users grid, fixed capitalization issues in processors\n- [#MODX-762] Added in missing lexicon entries to hardcoded strings\n- Added modx.localization.js for i18n translations\n- Added indexes on modLexiconEntry table\n- Properly formatted lexicon strings still using sprintf\n- Fixed bug where created was not set on transport package creation\n- Made sure package grid paginates correctly if number of packages installed exceeds 20\n- Fixed Last Modified On on Lexicon grid\n- Optimized action, menu, language, content-type, lexicon, namespace processors\n- [#MODX-765] Added fix to prevent creation of blank system settings\n- Fixed bug in Safari with TV widget properties rendering\n- Consolidated resource getNodes processor, added access policy checks\n- Added sanity check to toJSON function in modConnectorResponse\n- Properly refactor element tree to point to correct processor\n- Added delegate processors for different modes in element tree\n- Updated Context policy attributes for missing attributes\n- Fixed invalid category reference on chunk update processor\n- Added log error messages if save()/remove() fails on modElement derivatives\n- [#MODX-771] Fixed invalid lexicon string reference in element tree\n- Added WARN log message when executing a system event that doesn't exist\n- Filled out missing access policy checks in element processors\n- Fixed incorrect and missing permission check in snippet get/getList processors\n- Fixed invalid lexicon reference in template processors\n- Optimized templateTV getList processor to use only one query\n- Optimized plugin event getList processor to use only one query\n- [#MODX-194] Added sanity checks to element names\n- [#MODX-792] Added check to prevent user from creating blank context, other sanity checks\n- [#MODX-475] Prevented adding contexts with _ in name; will auto-strip\n- [#MODX-796] Fixed check for valid passwords in setup\n- Fixed problematic reference to $_lang\n- Fixed improper log message reference in lexicon's reloadFromBase processor\n- Additional access control defects and warning messages resolved for anonymous users.\n- Fixed access control defect which prevented multiple policies from being respected per principal.\n- Fixed issue with Policy Attributes not adding b/c id was not passed in\n- Added 'save' event fire to Element/Resource formpanels\n- Properly setup on*FormRender events for Element classes\n- Added MODx.onSaveEditor check, which will fire on form save, that allows 3rd Party Components to execute JS code on Element/Resource saves\n- Major refactoring to modx.actionbuttons, to render faster, as well as properly register events and button configs\n- Allowed OnRichTextEditorRegister to return a string as well as an array\n- Added MODx.releaseLock(id), which releases the lock on a Resource for a given ID\n- Added MODx.sleep(ms), which sleeps the UI for a given number of milliseconds (useful in async calls)", "MODX Revolution 2.0.0-beta-1 (LastChangedRevision: 5070 , LastChangedDate: 2009-05-28 16:20:08 -0500 (Thu, 28 May 2009))\n====================================\n- Fixed issue with cacheable toggle on derivative Resource pages\n- Fix error message when reading expired messages in modDBRegister.\n- Fixed issue with login page JS\n- Fixed issue with derivative Resource classes JS not loading Page Settings data into submit\n- Fixed issue with utilities JS not loading at right time\n- Updated build.xml to produce beta releases.\n- Quick fix to prevent blank attribute referencing\n- Fixed issue with package attributes and skipping blank options\n- [#MODX-723] Fixed issue where preview pane was picking up CSS from preview\n- Updated xPDO to revision 333.\n- Fix issues with Page settings defaulting to 1 on resource creation\n- Adjusted order of JS utils loading to make for easier min-concat loading\n- Cleanups to JS to prepare for beta-1\n- Lexicon updates\n- Updating outdated copyright notices in source code headers.\n- Fixed hardcoded version number in setup.\n- Added request_controller system setting to indicate the front-controller file (default=index.php).\n- Fixed array_merge warnings in modLexicon.\n- Added back support for anonymous user access control.\n- Added support for returnUrl parameter to be sent to login processor to allow unauthorized responses to return to the original requested page directly (NOTE: this overrides manager_login_startup and login_startup parameters, but does not work with POST requests: these will simply return to the URL with only GET parameters).\n- Export lexicon now prompts for download of exported file\n- Enhanced User Group update/create screen to now have grids that allow you to assign Resource Group / Context permissions to that user group. This will help clear up confusion with the access relationships.\n- Fixed scope issue in accordion.css that was causing odd behaviours with panels in the main content\n- Adjusted setup procedures to allow for more lexicon support for pre-load checks\n- Adjusted setup lexicon to allow for multiple topics; conformed upgrade scripts and other references to match\n- Consolidated similar code in setup, esp. with regards to fatal errors\n- Added smarter checks for xPDO failures in connectors\n- [#MODX-744] Fixed issue with invalid display of num cleared on cache claering\n- Fixed bugs with updating packages from a remote provider\n- Made sure package attr returns '' if false\n- Fixed manager log to show username, not user ID\n- Standardized derivative resource form panels to move page settings to left\n- Tweaked tree menu headers\n- Minor IE overrides for top navigation and accordion panel.\n- Added support for modLinkTag properties as url parameters, with context reserved to indicate a context to send to makeUrl().\n- Fixed error in modLinkTag when passed invalid data.\n- Added '@RESOURCE' binding alias so as to deprecate @DOCUMENT binding\n- Fixed default language setting for modLexicon\n- Fixed a couple issues with the page settings checkboxes for resources\n- Removed deprecated _tx_.gif\n- Removed home icon and replaced with tab\n- Adjusted CSS to align main content page vertically\n- Trees now have fun new icons representing their types (this includes the resource, element and file trees)\n- Cleaned up the default.inc.php lexicon topic to remove any no-longer-used entries\n- Fixing typo in subtract output modifier\n- Fixed improper reference in TV property renders for mgr context\n- Updated xPDO to revision 329.\n- Improvements to sendError() behavior.\n- Added lock stealing processor and updated remove_locks processor.\n- Added steal_lock:true policy attribute to default Resource policy to allow lock stealing permissions by ResourceGroup.\n- modTemplateVar: Fix getValue() on `value` field by storing and verifying the value requested is cached by the same resource.\n- modResource: Add resourceId value to getMany() on modTemplateVar to identify the resource caching a value on the modTemplateVar instance.\n- modX: Set logTarget based on XPDO_CLI_MODE; ECHO for CLI and HTML for non-CLI requests.\n- modX: Add sendError() function to provide customizable, named error pages on FATAL or other critical error situations.\n- modX: Refactored sendForward(), sendErrorPage(), sendUnauthorizedPage() functions to allow an array of options and better handle FATAL errors.\n- modCacheManager now Caches related modContentType data to prevent unnecessary database connection/query on fully cached pages.\n- Fixed problem with modStaticResource truncating the content to the size of the static file by setting the content length header on non-binary content types.\n- Fixed problem with modStaticResource non-binary content types rendering the path to the static file rather than the actual content of the file.\n- Calling modX->log(MODX_LOG_LEVEL_FATAL) or modX->messageQuit() now logs the error to file and then renders {MODX_CORE_PATH}errors/fatal.include.php.\n- Updated to r325 in xPDO: xPDO method changes to getOption() and _log().\n- Update 'setup-options' ability in transport packages to allow for script-based setup options that will properly handle upgrades to setup options default values\n- Updated to r323 in xPDO: Revise xPDOTransport::writeManifest to make 'setup-options' be able to be an executable script to allow for dynamic form ability\n- Updated snoopy class to version 1.2.4 (used by magpierss).\n- [#MODX-535] Removed automatic setting of isfolder based on presence or absence of children.\n- [#MODX-499] Site start Resources now return base_url from modContext->makeUrl() if no scheme is specified (i.e. when expecting relative links).\n- Improved error reporting on modX->makeUrl() to show original $id value being passed in on failures.\n- modLinkTag no longer returns empty values on first pass of parser, allowing delays until the value returns a valid value.\n- Implemented modResource editor locking (added modResource methods: getLock(), addLock($user), removeLock($user)).\n- Implemented modResource locking features in all appropriate processors.\n- modResource->checkChildren() now uses modX->getCount() to determine if children exist.\n- Added steal_locks attribute to Context access policy.\n- [#MODX-728] Made sure config check dialog is hidden if no warnings are present\n- Package Installations will now skip license agreements / readme panels if none are specified\n- Made sure More Info in download panel can scroll\n- Fixed issue with spacing in setup options panel of package install\n- modCacheManager->generateScript(): Fixed PHP notice in log message on error.\n- modInstall: Modify _modx() function to call setDebug with E_ALL & ~E_NOTICE instead of E_ALL & ~E_STRICT.\n- Optimized queries in element tree to eliminate subqueries or queries in loop, reducing to O(n) instead of O(n^2n)\n- Made clear cache results a bit smaller\n- Refresh trees after clear cache\n- [#MODX-609] Clear cache menu item now loads results in an alert dialog. No longer loads a separate page.\n- Fixed to template getlist processor\n- [#MODX-671] Fixed bug with resource group access permissions being checked when not assigned\n- [#MODX-699] Fixed to allow usage of login processor without lexicons\n- Added Import/Export to element properties grids, which allows for file-based transporting of properties.\n- Fixed issues with comboboxes dropping down a blue screen\n- [#XPDO-28] Fixed problem with multiple file resolvers on vehicles with similar basenames cause directory contents to merge unexpectedly.\n- fixed PHP notice for missing elementType variable\n- fixed subcategory elements missing from display (was counting elements in parent category rather then subcategory to determine if the subcategory should be displayed)\n- Fixed issue with default properties in TVs being locked\n- Fixed no onTVFormPrerender\n- Made sure clearDirty is fired on TV panels\n- Tweaked the css and updated copyright year.\n- Refactored all index.php gateways to support constructor options set as $options in the various config.core.php files.\n- modCacheManager/modCache: Introduced cache partitioning allowing various cache provider implementations to target specific MODx cache partitions and provide custom (system/context/user) settings for configuration options to each: cache_system_settings, cache_context_settings, cache_resource, cache_scripts, cache_lexicon_topics, cache_action_map\n- modAccessibleObject: Refactored object and collection loader logic to improve cache hit rates.\n- modRequest: Fixed warning for undefined variable $fromCache.\n- modSessionHandler: Refactored write() method to only update access time when the session data has changed or at specified intervals before the data is made available for GC.\n- modSessionHandler: Added support for cache_db_session, a new configuration setting to allow session data to be cached when cache_db is enabled.\n- modTemplateVar: Allow getValue() to use a `value` field for data if already populated for a specific resource.\n- Commented out missing image in welcome.tpl (temporary)\n- Added couple of bugfixes to modDBRegister to prevent duplicate payloads and update existing messages.\n- Fixed bug where QuickUpdateChunk was persisting values\n- Added fix to prevent DOM id problems\n- Added clearCache checkbox to chunk editing to allow toggleable cache clearing\n- Optimized chunk processors\n- Added 'Quick Update Chunk' and 'Quick Create Chunk' options to Elements tree, which allows you to quickly edit or create chunks via a window straight from the Element tree on any page\n- [#MODX-718] Fixed bug where elements without a category wouldn't show\n- [#MODX-697] Fixed problem with deprecated role topic still in action build scripts\n- [#MODX-705] Removed random numbers causing Radio TVs to render improperly\n- Fixed bug that caused policy data to be erased when creating/saving/removing policy data\n- [#MODX-711] Fixed Update Context screen to properly pass correct PK\n- modDbRegister: fixed bug with expired messages not being removed if remove_read => false\n- modDbRegister: allowed messages to be updated/overwritten\n- Fixed modCacheManager::prepare() - was returning false on already-prepared contexts\n- Added support for nested categories for elements; categories can now have subcategories\n- Fixed to treestate to properly set treestate ID so restore can work properly\n- Fixed call to onDocFormRender to make sure ID is passed on Resource update\n- Fixed to getFiles processor for MODx.Browser to properly store URL parameter with the base_url prefixed\n- [#MODX-712] Fixed errors creating context settings\n- modX: Fixed potential error when invokeEvent() is called and executes a plugin with property sets and pluginCache does not contain the object\n- modCacheManager: Fixed error when building the pluginCache with property sets\n- modCacheManager: Fixed typo in parentSql that was breaking use alias paths option.\n- modCacheManager->generateContext(): Added support for Resources to be generated in multiple contexts via modContextResource.\n- modParser: Removed errant log() statement in parseProperties().\n- modParser: Fixed problem in parsePropertyString() when passing `escaped` property values containing semi-colons (;).\n- Added in necessary reloading functions to ColumnTree\n- Fixed issue with column tree's context menu overriding the ID\n- modManagerResponse: Detect if controller responses are error arrays and render using error.tpl appropriately.\n- [#MODX-693] redirect bug - modResponse logic error\n- Moved core/config/version.inc.php to core/docs/version.inc.php\n- layout/tree/resource/getnodes.php: Additional optimization to reduce memory usage and improve performance when opening Resources containing a large number of children.\n- modConnectorResponse->toJSON() optimized to greatly reduce memory usage and improve performance with large result sets.\n- [#MODX-691] allow User Settings to be saved from prop. grid\n- Fixed bug with documentMap\n- Fixed issue with default tv render panel for resource page\n- [#MODX-690] Fixed a few events names registered in the system_eventsnames table during build/install\n- Added id's to element and category nodes for informational purposes (missed one spot).\n- Added id's to element and category nodes for informational purposes.\n- Updated drag and drop behavior to update context_key of all child Resources when dropping a container on a different context node.\n- Modified modTransportPackage.manifest field from MEDIUMTEXT to TEXT in order to handle large manifests.\n- Fixed aliasMap broken in recent cacheManager refactoring.\n- Added helper functions to MODx.tree.ColumnTree\n- Added DD events to ColumnTree\n- Added missing column tree CSS\n- Added UI for adding property sets to PluginEvents\n- Added cacheManager object checks to verify for PHP4 installs\n- modCacheManager->generateResource(): added validation of the modResource primary key before attempting to cache a record.\n- modUser: modified storage of session data to use the modUser primary key value to isolate values associated with a specific user; this will allow users to login as multiple users on the back-end and/or front-end without affecting the session data associated with a specific user.\n- modX->_initSession(): Enable session_gc_lifetime configuration setting to set session.gc_liftime ini setting regardless of what session handler is configured.\n- modPluginEvent: Added the ability of plugins to utilize Property Sets by allowing a plugin registered to a particular event to attach a Property Set and make it available during processing.\n- Fixed warning with loading of RTEs in resource page\n- [#MODX-674] Fixed content-dispo combobox bug\n- Removed allowBlank: false check on menuindex to allow for dynamic creation\n- Added in missing lexicon entries for prior menuindex commit\n- [#MODX-678] Added back in 'menuindex' field to resource panels\n- Added missing modX::__construct() options parameter.\n- Allow for extending of MODx.panel.ResourceTV by making reference to modx-resource-template field dynamic\n- Fixes for RTE loading\n- Fixed issue where smarty template path was not being reset if 3PC set path to something else\n- modX constructor now accepts a second parameter containing an array of options to be set in the config\n- Major refactoring of modCacheManager to provide more granular caching options\n- modCacheManager now accepts options, based on changes to xPDOCacheManager, and provides access via getOption()\n- generate*() methods now all return data as well as cache it to a specified cache_handler unless otherwise configured\n- modX->getCacheManager() no longer supports MODX_CACHE_DISABLED or config['cache_disabled']; the cacheManager is required, though you will still be able to effectively turn off all caching in the future via this setting (this will be worked back in)\n- manager/controllers/system/refresh_site.php changes to better target things to remove from the cache\n- Introducing modDbRegister and the modx.registry.db package, providing a database modRegister implementation.\n- Added new system settings for individual cache areas, i.e. cache_system_settings, cache_context_settings, cache_lexicon_topics, cache_scripts, etc.\n- modCacheManager: Various fixes and adjustments to latest refactoring, including clearCache improvements.\n- manager/controllers/system/refresh_site.php: Improvements to default clearCache call.\n- modCacheManager: converted generateActionMap() to support configurable cache implementations\n- Updated modAction->rebuildCache() and modManagerRequest->loadActionMap()\n- Additional tweaks to manager/controllers/system/refresh_site.php\n- Updated xPDO externals to revision 308\n- Removed unnecessary comments from the reg* functions\n- Moved all manager pages JS/CSS to inside HEAD tag using the reg* functions; this improves speed and validation of the manager\n- Fixed the way 3PCs handle their controller files. NOTE!!! This means that you no longer need a \"core/controllers\" file in your 3PC; just set the namespace path correctly, then set the controller in your modAction.\n- Added an ability for mgr pages to utilize regClientStartupScript and other reg* functions to make pages load faster and move JS/CSS to HEAD tag\n- modX->getEventMap() - Made sure prepare() creates a valid statement before calling execute()\n- Updated modStaticResource to set headers in getFileContent() for now, though this needs to be refactored for flexibility.\n- Fixed issue with saving TVs from create resource processor\n- [#MODX-637] Fixed issue with TVs not reloading on changing template in new resources\n- [#MODX-663] Fixed various issues with modAction creation\n- Fixed issue with MODx.Browser uploads not refreshing the main view\n- Fixed publishedon default date setting\n- Fixed date TV default value\n- Fixed default setting for symlinks\n- Fixed issue with Symlink/WebLink class_key storing\n- Fixed issue with textfield editing in Safari on Property Set grid\n- [#MODX-662] Fixed duplicate issue with elements\n- Fixed issue with property sets page and property lock\n- Fixed name issue on duplicating elements\n- Fixed symlink page setTimeout issue\n- Fixed missing file inclusions\n- Fixed element tree where categorized templates weren't showing\n- Added editing ability to resource's publishedon date\n- Fixes to package downloader panel due to ID conflicts\n- Adjusted modTransportPackage::transferPackage to rename incoming file to [signature].transport.zip rather than basename($source)\n- Fixed xml/json response classes to properly work\n- Added permission \"unlock_element_properties\", which gives ability to unlock editing of default element properties.\n- Added implementation of above permission into element properties grid\n- Fixed some logic issues with the lockMask\n- [#MODX-561] Added \"Locked\" ability to default properties for elements\n- [#MODX-633] Fixed issue with add another not respecting parent\n- Fixed TV access panel not working on new TVs\n- Fixed state management with tree nodes\n- [#MODX-661] Fixed URL TV input, where it was not setting prefix value\n- [#MODX-659] Fixed bug where root-level docs couldnt be updated b/c of parent issue\n- Fixed bug with parent being assigned to 0 always in derivative Resource classes\n- Made sure bad resources (where parent = id) are ignored when building the context cache files.\n- Fixed parent bug in controllers\n- Fixed transport.data.php with 'namespace' key on modActions\n- [#MODX-622] Updated top menu structure to be more consistent.\n- Fixed error if properties are null\n- [#MODX-651] Fixed bug when deleting a propset, would not empty grid\n- Fixed to resource page combos not setting display value correctly\n- [#MODX-658] Fixed issue where in TV -> Create, templates were not showing\n- Fixed template nodes to properly sort by templatename\n- Adjusted resource menus and such to refer to a 'Resource' without a specific class_key as 'Document' when applicable, with the exception of talking about Resources in the generic sense\n- Added Duplicate option to Property Sets\n- Fixed bug where template inheritance for resources wasn't happening\n- Fixed symlink page\n- [#MODX-632] Updating xmlrpc to 2.2.1\n- Corrected logic in setup to allow forced PDO emulation mode (XPDO_MODE == 2).\n- Added `category` field to modPropertySets; they can now be categorized\n- Enhanced UI to support new modPropertySet category ability\n- Modified MODx.Window so that the ENTER key submits the form\n- Added more IDs to element forms\n- Added ability to \"remove\" overridden properties, but only ones that are not in the default propset (ones that are should \"revert\")\n- Fixed OnWebPagePrerender event not firing as expected.\n- modOutputFilter: Refactored date modifier to return '' if the timestamp encountered == 0 or -1.\n- modOutputFilter: Added strtotime modifier.- Refactored connectors to execute in the context from which they are called, rather than their own context.\n- Updated xPDO to revision 304 for new xPDOFileVehicle feature to respect XPDO_TRANSPORT_RESOLVE_FILES options.\n- [#MODX-562], [#XPDO-24], [#XPDO-25], and [#XPDO-26] Updated xPDO to revision 302 to resolve various issues regarding transport packages and model generation.\n- [#XPDO-23] and [#MODX-604] Updated xPDO to revision 298 to resolve nesting error when logging messages during installation with improper cache directory permissions.\n- Added modPropertySet->getElements() method as shortcut to get all proper modElement instances available to the set.\n- Added overridden modElementPropertySet->getOne() to get related Element using the proper element_class value.\n- [#XPDO-21] Updated xPDO to revision 290 for updates to xPDOObject::addOne() and addMany().\n- [#MODX-553] Unpublished and deleted Resources now ignored properly in modRequest::getResource().\n- [#MODX-553] Core setup now automatically adds an ACL to the web context for members of the Administrator group.\n- Core setup now updates the Administrator group ACLs for accessing the mgr and connector contexts with an Authority of 0 (highest authority).\n- Modified OnUserNotFound event handling not to rely on references which no longer work properly with recent changes to property handling.\n- Added overridden modElement->get() to handle converting legacy property strings stored in the database.\n- Added modPropertySet class to represent persistent sets of properties that can be applied to modElement instances.\n- Added support for modElements to relate modPropertySet objects via modElementPropertySet (many-to-many).", "MODX Revolution 2.0.0-alpha-6 (LastChangedRevision: 4485 , LastChangedDate: 2008-11-25 11:58:49 -0600 (Tue, 25 Nov 2008))\n====================================\n- [#MODX-395] i18n'ed the modMail classes, added lexicon topic 'mail' for handling mail strings\n- Added check to make sure user cannot browse to subdirs with ../ in connector processor fetching\n- [#MODX-482] Implemented code to remove setup/ directory when box is checked.\n- [#MODX-408] Fix atrocious grammar in mail reception message\n- Fixed labels for static resource page\n- [#MODX-518] Make sure clearing cache clears registry output from package\n- Fixed in_array() checks against $_currentTimestamps in xPDOObject::save() that prevented timestamp/datetime fields from saving 0 values.\n- [#MODX-512] Fixing check in setup to make sure core/packages is writable\n- Fixed bug with RTE loading and saving\n- Changed 'Provisioner' references to 'Provider' in UI for nomenclature consistency purposes\n- Added lexicon load to resource processors\n- Fix error on resource view when template is empty.\n- Added namespace filter to settings grid\n- Fixed import trees\n- Hide the resource ID field if a new resource\n- [#MODX-514] Fixed issue with pub_date/unpub_date not being reset properly\n- [#MODX-484] Added missing ht.access sample to web context files in included in transport package.\n- Modified modWorkspace vehicle attributes to XPDO_TRANSPORT_UPDATE_OBJECT => false\n- Updated xPDO to revision 284 for new xPDO package-aware vehicle features when loading classes.\n- Slight styling improvement to grid to make alt-rows more apparent\n- Added clearCache() functions to modLexiconTopic, modLexiconLanguage\n- Added 'collapsible' options to the options tabs of resources. Can now collapse them to show only the content editor.\n- Prevent blank property value names\n- Adding css classes to modext components for easier styling\n- Fixed some issues related to installation of packages, namely dealing with the setup-options attribute and resolver handling\n- Added _build/build.local.xml to prepare an svn development copy for execution; builds core transport, minifies and concats the javascript and puts it in place, etc.\n- Slight fix to login box and css styles to get checkbox checked css to render properly\n- Updated xPDO to revision 281 to get fix to xPDOObject::save() when updating fields with NULL values.\n- Styling updates; make form fields bigger, tabs bigger, menus bigger...basically pretty up the UI\n- Fix to typo in createTable in modInstallVersion\n- Implemented version-specific upgrades to setup/\n- Updated xPDO to revision 275 (xPDOObject datetime/timestamp handling improvements, xPDOTransport pre-existing object restoration features, and more).\n- Changed System Events action to Error Log Viewer, which now allows you to view (and clear) the error log from the manager\n- [#MODX-509] Fixed issue with refreshing of incorrect node in dragdrops on trees\n- Fixes to CSS in setup, moved error box to fixed bottom right, i18n'ed more stuff, cleaned up HTML and simplified outputs\n- Fixed issue where the path for processors could not be overridden by changing the parameters for handleRequest in modConnectorRequest to an array of options\n- [#MODX-501] Fixed issue where trees didn't refresh when package was installed. All trees now refresh.\n- Fixed bug with duplicating resources\n- [#MODX-505] Fixed issue with creating weblink redirecting improperly\n- Fixed issue with emptying recycle bin and root-level resources\n- [#MODX-508] Weblinks are now not hidden by default\n- Fix missing published checkboxes in resource derivative classes\n- Applied patch to fix issue with label click of checkboxes not changing value\n- [#MODX-507] Fixed bug where Published checkbox wasnt showing in resource panel\n- Fixed bug in filetree that would scroll up topmenu\n- [#MODX-507] Adding in textbox for parent ID for now, will come up with better solution later\n- [#MODX-506] Fixed bug where cache wasn't cleared on drag/drop in tree\n- Fixed bug in modPackageBuilder that was preventing deletion of existing package directories and files.\n- Added constants MODX_INSTALL_MODE_NEW, MODX_INSTALL_MODE_UPGRADE_EVO, MODX_INSTALL_MODE_UPGRADE_REVO\n- Extracted install->test() to a separate class, then i18n'ed the test strings\n- LOTS of phpdoc additions to all processors, including parameter lists for each processor\n- Removed any last trace of modules from Revolution\n- Added phpdoc information to processors\n- Properly clear cache on install/uninstall/remove of packages\n- Removed \"require_once MODX_PROCESSORS_PATH.'index.php';\" from all processors\n- Only show 'Update Package' if the package comes from a provider\n- Fixes to get browser working with TinyMCE\n- Fixed issue with forced removing of packages not properly removing the resolvers\n- Standardized modRequest/modResponse methods across all derivatives (i.e. modRequest::handleRequest() always calls modRequest::prepareResponse(), which calls modResponse::outputContent()).\n- [#MODX-478] Fixed typo in lexicon import/export that prevented window hiding\n- Fixed issues with Symlinks\n- Fix to TV output/input renders when loading in a context other than web/mgr\n- Fix to invokeEvent to prevent unwanted caching of event name if plugin executes more than one event per runtime\n- [#MODX-424] Added readme viewing to package grid\n- Added ability to delete multiple element properties at once via a multiple row handler\n- [#MODX-488] Removing double click from properties grid for 'name' field to prevent unwanted breaking\n- Added back in setDirectory to modConnectorRequest\n- [#MODX-292] Properly format system settings editedon value\n- [#MODX-293] Properly format editedon for lexicon entries\n- [#MODX-481] Fixed rendering issues in element property grid columns\n- [#MODX-479] Fixed issue where first snippet property edited didn't show value\n- [#MODX-480] Fixed issue with lexicon entry update/create not loading proper topic\n- [#MODX-474] Removing package builder menu item from build script\n- [#MODX-456] Fixed issues with element property grids\n- Fixed MODx.grid.LocalGrid store bugs when dealing with grouped data\n- added pageSize and pageStart config items to MODx.grid.Grid\n- Fix to MODx.grid.Grid in case listeners are provided, dont ignore context menu\n- [#MODX-466] Fixes to dropdowns for element categories, field issues\n- [#MODX-115] Some fixes to rendering issues with comboboxes/datefields on Safari\n- Updated xPDO to rev 265 for improvements in xPDOValidator allowing multiple rules to be evaluated per column.\n- Refactored modError completely, removing all derivative classes and introducing modManagerResponse and modConnectorResponse to handle formatting modError responses appropriately.\n- Added modRequest::registerLogging() and relocated logic for detecting and taking action on register logging parameters out of loadErrorHandler().\n- Refactored modArrayError to remove Smarty dependencies, moving them to a new derivative, modSmartyError which the manager UI can utilize explicitly.\n- Added element property panel to all Element panels for managing default properties (except Modules).\n- Added modElement->setPlaceholders() to set placeholders and return any global placeholders that might need to be restored after an element is processed.\n- modChunk and modTemplateVar now restore any placeholders from the global scope after processing any local properties with the same name.\n- Added properties as local placeholders when processing modTemplateVar instances to match behavior of modChunk/modTemplate.\n- Updates to snippet property editor.\n- Added properties to modTemplateVar to make them consistent with all other elements.\n- Modify modX::getChunk() and runSnippet() to process those elements as non-cacheable instances.\n- Added modResource::getContent() and setContent() functions for extensible control of accessing raw source content.\n- Modify modElement::setProperties() and modTag::setProperties() to handle various property data formats.\n- Updated modParser::parsePropertyString() to handle local property xtypes from UI and convert legacy types.\n- Added isCacheable() and setCacheable() to modElement and modTag classes for direct, extensible control of caching.\n- Modified behavior of modTemplate/modChunk not to prefix properties turned into placeholders with the name of the element.\n- Added getContent(), setContent(), getProperties(), and setProperties() to modTag and derivatives.\n- Added modParser::parsePropertyString() to parse element properties from string or array representations.\n- Updated modElement::process() behavior to check cache sooner and avoid unnecessary source content access and other processing.\n- Additional foreign key and sorting indexes added to modElement classes.\n- Added properties to all modElement classes except modTemplateVar.\n- Added setProperties() to modElement for setting a set of default properties that will be used by the element.\n- Added getProperties() to modElement for getting the properties to be used when processing the element.\n- Added getContent() and setContent() function to modElement and provided overrides in the appropriate subclasses.\n- Removed modTransportPackage::loadTransport(); the manifest should always be loaded from the file.\n- Updated xPDO to rev 262 for improvements in the xPDOTransport manifest format.\n- Updated xPDO to rev 258 for bug fix in new xPDOObject::_setRaw() function with array and json phptype fields.\n- Updated xPDO to rev 256 for bug fix in xPDO::getSelectColumns() and new xPDOObject::_setRaw() implementation to resolve issues with native php types when using fromArray().\n- Added modPackageBuilder->setPackageAttributes() function for easily adding transport-level attributes to a package.\n- Updated xPDO to rev 252 to get new features allowing transport packages to carry transport attributes.\n- Added numerous foreign key and sorting indexes to site_content table (modResource) to improve performance of common queries.\n- Changed modX::changePassword() implementation to call modUser::changePassword().\n- Added getResourceGroups() and getUserGroups() to modUser class to retrieve those things and cache in session.\n- Renamed and moved modX::_checkPublishStatus() to modRequest::checkPublishStatus() and renabled this functionality.\n- Deprecated and moved modX::checkPreview() implementation to modResponse.\n- Added view_offline attribute to default Context access policy.\n- Removed deprecated and invalid modX::makeFriendlyURL().\n- Removed deprecated modX::webAlert() function.\n- [#MODX-364] Results of regClient*() functions are now cached into the Resource cache files to solve error on cached pages with cached snippets.\n- Removed deprecated modX::mergeDocumentMETATags() and moved feature to modResource::mergeMetatags() and modResource::mergeKeywords().\n- Removed deprecated modX::makeList() function.", "MODX Revolution 2.0.0-alpha-5 (LastChangedRevision: 4273 , LastChangedDate: 2008-10-09 12:42:42 -0500 (Thu, 09 Oct 2008))\n====================================\n- [#MODX-88] Move version checking to setup script and add notifications.\n- [#MODX-66] Change the way properties work within the scope of a chunk; placeholders set by the chunks properties are now removed after the chunk is processed.\n- Added modX::unsetPlaceholder() and modX::unsetPlaceholders() functions.\n- [#MODX-329] Fixed error with browser \"remembering\" user even when \"remember me\" is not checked. Was always using the system setting regardless of rememberme.\n- [#MODX-380] Created modSymLink resource class which forwards requests to other resources without changing the URL (as opposed to modWebLink which redirects).", "MODX Revolution 2.0.0-alpha-4 (LastChangedRevision: 4213 ,LastChangedDate: 2008-10-01 12:18:41 -0500 (Wed, 01 Oct 2008))\n====================================\n- Updated xPDO to rev 248\n- More log messages for modPackageBuilder\n- Fixed some bugs with MODx.Browser\n- Enabled specific path setting for MODx.Browser\n- Fix to remove redirect to system settings if version info differs.\n- Added MODX_SETUP_KEY to setup to identify the distribution type and allow setup logic to be conditional based on this information.\n- Introduced additional default policy attributes and policy checks throughout the controllers and processors for more robust access control.\n- [#MODX-349] Added processor and menu item to reload your own access policies without logging out and logging back in.\n- [#MODX-349] Added processor and menu item to flush all user sessions from the database.\n- [#MODX-349] Modified user policies to cache policies by Context; previously policies cached for one context were being applied to other contexts when switching or accessing both from the same browser session.\n- Updated xPDO to revision 246 to fix problem with modLexiconEntry rows being duplicated in upgrades after deleting modLexiconFocus records.\n- Modified Ant build to automatically compress and concatenate js files (SVN users cannot use compress_js option without performing the complete-wc task in build.xml).\n- Updating xPDO to revision 234.\n- Added support for logging to registers through any modError instance when loaded by modRequest::loadErrorHandler().\n- Removed modRegisterHandler and added logging helper functions to modRegistry.\n- Updating xPDO to revision 233.\n- Updated modAccessibleObject::loadCollection() based on xPDO::loadCollection() changes.\n- Updating xPDO to revision 231.\n- Various model updates to reduce memory usage [convert foreach with fetchAll() calls to while with fetch()].\n- [#MODX-137] Locked Elements now editable by users with the Admin policy attribute edit_locked (not locked as in being edited by another user, but locked explicitly in the Element attributes).\n- Moved makeUrl logic to modContext class and modX now determines which context to use when building the URL.\n- Introduced modX->getContext() to retrieve, prepare and store context configurations in modX->contexts array for reuse during the single request\n- Added _config, _systemConfig and _userConfig to hold on to various parts of the configuration settings before they are merged for use, allowing other functions to remerge the settings as needed.\n- Fixed modX->switchContext() to clear all contextual/user setting overrides and reload the bootstrap _config, _systemConfig, and make use of the modX->contexts array.\n- Implemented UI ability to choose vehicle-specific attributes when adding vehicles to packages\n- Added dynamic value replacement of {setting_key} in user settings in modX->getUser().\n- Added function to grab the request parameters to MODx.request\n- Added missing permission check on empty_cache attribute on refresh_site controller/processor.\n- Updated xPDO to revision 218.\n- [#MODX-282] Fixed bug where grid would show non-existent page in lexicon/settings grids\n- Removed permission check on logout action; doesn't make much sense.\n- Proper formatting of editedon time in system settings grid\n- Added System Settings \"Update Setting\" window for more detailed editin\n- Rebuilt core data files for the transport.core.php script and made correction to core namespace path to the value {core_path} which is calculated at run-time.\n- [#MODX-263] Access policy update grid moved to separate page\n- Created panel for editing access policies\n- [#MODX-277] Changed 'setting' to 'name' at top of System Settings grid\n- [#MODX-283] Fixed combo-boolean combobox to prevent overwriting of form variables. this was a bizarre bug.\n- Allowed modPackageBuilder to now use dynamic, on-the-fly namespaces. Separated out registerNamespace() from create()\n- Added support for loading extension_packages via configuration settings before the session is initialized.\n- Fixed dynamic value replacement of {setting_key} in system and context setting generators.\n- Updated xPDO to revision 216.\n- Added class_key field to modUser class/table to support modUser derivatives.\n- Fix to new modLexiconEntry table structure (was not installing due to NOT NULL and no default value).\n- Removed modResource::hasAccess() function to make sure and avoid confusion with security.\n- Add default admin user to the Administrator modUserGroup with a modUserGroupRole of 2 (SuperUser) on new installs and upgrades.", "MODX Revolution 2.0.0-alpha-3 (LastChangedRevision: 3867, LastChangedDate: 2008-07-22 08:44:38 -0500 (Tue, 22 Jul 2008))\n====================================\n- [#MODX-210] Changed no-longer-valid help text for resource panel\n- [#MODX-216] Fixed bug with pub_date/unpub_date for the Resource panel\n- [#MODX-213] manually entered passwords not being displayed after saving\n- Added editability to packages grid\n- [#MODX-205] Fixed category saving\n- [#MODX-196] Fixed snippet category error in IE7\n- Created modInstallError for base processing methods\n- Added object support to modInstallJsonError\n- [#MODX-201] Fixed bug with Category combo that prevented adding in a custom category\n- [#MODX-200] Added colored Not Installed text to not installed packages\n- [#MODX-70] Removed top buttons, as they are unnecessary and cause more problems than they are worth.\n- [#MODX-174] Language setting in setup is not loaded.\n- Note: renamed the language file to en.php to match the adopted IANA standard codes (see #MODX-187)\n- [#MODX-26] Manager User creation problems\n- Corrections to new user account email\n- Added MODX_URL_SCHEME define and url_scheme configuration setting\n- Added MODX_HTTP_HOST define and http_host configuration setting\n- Changed \"Modules\" top menu to \"Components\" top menu. Component developers are encouraged to put their 3rd party menus in there.\n- [#MODX-83] Radio Options not working in TV\n- [#MODX-103] Fixed blank template change warning message.\n- [#MODX-173] Language setting in manager pages is not loaded.\n- Removed ucwords on getlist processor for lexicons.\n- Fixed feed_modx_security/news keys in the build file.\n- [#MODX-184] Fixed show in menu checkbox, should have been labeled \"Hide Menu\" since the opposite is true in the database. Changed to match DB column properties.\n- [#MODX-190] Fixed bug with missing duplicate snippet error message\n- Added check for existing name in snippet duplicate processor\n- Updated build.src.url to branches/revolution\n- Fixed import html/resources\n- Fixed action pointer if version is incorrect", "MODX Revolution 2.0.0-alpha-2 (LastChangedRevision: 3841, LastChangedDate: 2008-07-15 09:18:24 -0500 (Tue, 15 Jul 2008))\n====================================\n- Adopting new product name, MODX Revolution, and changed version to 2.0.0\n- Fixed bug with content type grid\n- Replaced 'gender' with Role column in Users grid\n- [#MODX-182] Fixed invalid reference in tv/create.js\n- Fixed TV input type dropdown, added proper processor/connector\n- changed xPDOCriteria calls to more abstract newQuery ability\n- Added attachment capabilities to modMail/modPHPMailer classes\n- Added setHTML method to modPHPMailer\n- Updated documentation for modValidator class\n- Added explicit header call to set text/json; charset=UTF-8 on responses from modJSONError\n- Remote package installation now works.\n- Fixed invalid schema relationships with transport providers/packages\n- Included check for xPDO transport service config to prevent warning\n- [#MODX-108] Added more database info to the site info page - contrib by sottwell\n- Finished UI for modStaticResource\n- Added some inline documentation to widgets for help\n- Set a more appropriate default resolver target\n- Removed unnecessary package parameter from modPackageBuilder::buildSchema\n- Removed unnecessary package setting\n- Added buildSchema function to modPackageBuilder\n- Added tooltips to elements and contexts in the resource/element trees\n- Fixed bug in Module update page\n- Added a qtip to document tree nodes so they display resource longtitle/description in a tooltip\n- Moved styles to gray theme to prepare for css work\n- Weblinks now functional\n- Fixed slight bug with FF3 and panel collapsibility\n- Fixed plugin properties\n- [#MODX-162] Fixes problem where vehicle grid is not refreshed on 2nd build, as well as resets the form\n- Added 'success' event to MODx.FormPanel\n- [#MODX-172] Fix to option values for setup in IE 6. Fix by kmd.\n- [#MODX-166] - Fixed config cache issue - fix provided by kmd\n- [#MODX-165] could not save Template element - fix provided by SA\n- Fixed and cleaned up the actions/menus JS and combos\n- Removed unnecessary tertiary expression (check is already handled by the function)\n- [#MODX-131] Fixed Apache crash and enabled Tools -> Action\n- Added fix to _() JS function to allow for parameter passing:\n String: 'Testing: [[+hello]]';\n JS call: _('testkey',{'hello': 'Success!'});\n Result: 'Testing: Success!';\n- [#MODX-148] Added support for [[+placeholder]] tags in lexicon strings. i.e., with a lexicon string with key 'test' and value: 'Test me: [[+hello]]'\n Programmatically:\n $modx->lexicon('test',array('hello' => 'Success!');", " Tag:\n [[%test?hello=`Success!`]]\n- Fixed to typo on system info JS\n- Added namespacing ability to the addDirectory() and load() methods of modLexicon. Used like so:\n $modx->lexicon->addDirectory('pathhere/','testNS');\n $modx->lexicon->load('testNS:fociname');\n- [#MODX-102] fixed missing lexicon entries in php4\n- Added OnHandleRequest event, invoked before anything occurs in modRequest::handleRequest().\n- Set the modLexicon::_lexicon to an empty array even if nothing was loaded.\n- Added modX::switchContext(string $contextKey) function to make it easy to switch contexts using a plugin and the new OnHandleRequest event.\n- Fix to properly submit the content field for resources (should also handle multiple RTEs now)\n- Fixed typo in lexicon reference in event getlist\n- Fix to MODx.load to return multiple objects if they exist\n- General JS doc updates\n- Added MODx JS class, which allows for xtype loading via MODx.load()\n- Some JS doc updates\n- Fixed modErrorHandler to ignore suppressed errors like a proper error handler is expected to.\n- [#MODX-109] Fix bug with profile page loading of date.\n- Reconfigured context update window to separate into tabs for easier viewing and rendering\n- Changed TV resource group panel to a grid, instated proper remove/update code\n- [#MODX-126] Implemented 2 new modSystemSettings: feed_modx_news and feed_modx_security for dynamic setting of the RSS feeds in the welcome pane of the manager\n- [#MODX-137] Removed locked check until a resolution is made on locked elements.\n- [#MODX-119] Corrected issue with file editor stripping out SCRIPT tags. Was using $_REQUEST instead of $_POST so the values were sanitized by the request handler.\n- Updated Template management to a MODx.FormPanel\n- Altered the way modLexicon loads multiple foci for PHP4 compatibility\n- Added modLexicon::addDirectory, which adds a directory when loading lexicon foci\n- Properly load TV widgets and i18n their strings\n- Fixed bug with modLexicon and $modx reference\n- [#MODX-133] Prevent elements from being dragged into different types\n- [#MODX-125] Fixed saving pub/unpub date on resources\n- [#MODX-106] Removed assets/images check.\n- Configured Object field in Package Builder to be a combobox that loads a dropdown of the selected class_key\n- Added ability to remove vehicles from not yet built package\n- Added MODx.grid.LocalGrid as abstract class of local-data-based grids\n- Added MODx.panel.Wizard as abstract class of wizard panels\n- [#MODX-121] Fixed top menu loading incorrectly when clicking on icons\n- Fixed TV management page, specifically with TV->Template access\n- [#MODX-118] Fixed bug with creating/removing/updating directories from Directory tree\n- Added MODx.combo.ContentDisposition\n- Added ability for MODx.toolbar.Actionbuttons to support formpanel as an alternative for form config parameter\n- Added $modx->config properties to MODx.config JS array sent\n- Fixed update resource TV loading\n- [#MODX-113] Fixed bug in Safari with scrolling in grids, apparently Safari doesn't like Ext's autoHeight\n- Removed legacy tpl's in settings/ dir\n- [#MODX-107] Fixed tree refreshes when resource is saved, both in create and update. Update will now refresh only the parent node of the resource being saved, which speeds up save time\n- Fixed issues with TV Panel loading improperly on new resource\n- [#MODX-114] Prevented JS error from occurring when using page settings checkboxes\n- [#MODX-116] Fixed text for removing a category\n- Fixed Resource pages to allow for Resource Groups to be assigned access prior to Resource creation, as well as making grid not save until 'Save' is clicked\n- Fixed Template pages to allow for TVs to be assigned access prior to Template creation, as well as making grid not save until 'Save' is clicked\n- Fixed TV pages to allow for templates to be assigned access prior to TV creation, as well as making grid not save until 'Save' is clicked\n- Fixed module update, removing legacy code\n- Fixed plugin event grid: now can be used via create or update, also properly handles events, does not save until \"Save\" button is clicked on action bar", "MODx 0.9.7-alpha-1 (LastChangedRevision: 3664, LastChangedDate: 2008-04-28 12:43:15 -0500 (Mon, 28 Apr 2008))\n- Updated ExtJS from version 2.0 to 2.0.1\n- [Trac#20] When creating new document, make the 'Log Visits' checkbox respect the main configuration setting.\n- [Trac#9] Converted Database Tables tab in System Information to use Ext Grid.\n- [Trac#40] Default role settings are now set correctly when saving roles to the database.\n- [Trac#4] Converted Modules section to use Ext interface.\n- Added new resource import routine for creating resources from static content on the file system, as any valid modResource derivative.\n- Introducing context support to the manager resource trees.\n- [Trac#32] Display correct message counts for the Inbox section on the Welcome page.\n- [Trac#31] System Configuration page always showing 'New Install' message. Refactored code to use $modx->version.\n- [Trac#25] Several bugfixes and refactorings to make the Messages section function correctly.\n- [Trac#6] Remove Locks not working from the top menubar.\n- Removed custom_contenttype from system_settings and manager interface.\n- Converted and refactored Import HTML tool for the new APIs.\n- [Trac#29] Resource checkboxes on settings tab not showing accurate values when editing.\n- [Trac#28] Cache not cleared when resources are saved and the clear cache checkbox is checked.\n- [Trac#27] Cached modResources were not loading or rendering since getResource() moved to modRequest from modX. Cache files generated with new reference to the modX object ($this->modx vs $this).\n- Remove logic in modResource::addOne() that was disallowing binary content types.\n- Add conditional to check for $GLOBALS['https_port'] before attempting to use it.\n- Several fixes to modResource processors involving saving of boolean fields via checkboxes; make sure POST is filled with unchecked fields having a value of zero.\n- Upgrades now work for previous 0.9.7 installations\n- Add-on installation has been removed from setup in preparation for adding it to the manager itself.\n- Removed modManager095 and all related legacy support for ManagerAPI extender, moving this functionality to modManagerRequest.\n- Added/updated delegate controllers, templates, and processors for modWebLink and modStaticResource.\n- Added new static resource option to document tree context menus.\n- Fixed bug with chunk update processor deleting the chunk content.\n- [Trac#19] Bugs with password on user creation/update; was saving plain password (not encoded).\n- Introduction of new setup using transport packages (new installs only for now).\n- Modified modRequest::sanitize() to no longer strip old-style tags.\n- Moved MODx classes and maps out of core/xpdo/om/modx095 and into core/model/modx.\n- [xPDO] Add support for package specific include paths for models.\n- Refactored INCLUDE_ORDERING_ERROR to manager/includes/accesscheck.inc.php\n- Begin adding input and output filtering to all MODx elements and tags (modElement and modTag derivatives), including default filter implementations based on phX (not yet working).\n- Begin refactoring modx095 package to utilize xPDOQuery (modResource::getOne()).\n- [xPDO] Fixed error in xPDOObject::remove() that was trying to call the toCache function on xPDOObject rather than xPDO.\n- Added checkForLocks func to modx.class.php\n- Added checkIfIn to modmanager095.class.php, to do the annoying check if in manager in all the pages\n- Added splitter class for tables to get the line effect found in user management\n- Added ul.no_list to get list effect without bullets\n- Added formhandler.js - handles validation in forms by sending form through AJAX call. If response != true, then outputs response to a div with id 'errormsg'. Also evaluates JS scripts in the response.\n- Updated MODx model for modUserSettings and modWebUserSettings with appropriate primary key indexes and field types.\n- Updated installer SQL to remove the previous indexes and add the primary key index.\n- Fix to modX :: insideManager() to make sure there is a context object initialized before trying to get the context key.\n- [xPDO] Introduction of xPDOQuery for building SQL queries using only objects and the API.\n- [xPDO] Fix to timestamp phptype handling when stored as integer dbtype in database.\n- Modified modResource constructor to set createdon and createdby fields appropriately.\n- Fix for mcpuk GetUploadProgress script (see http://modxcms.com/forums/index.php/topic,11712.msg79581.html#msg79581)\n- Separated styles into their function, for easier manipulation and management\n- Ongoing Conversion of manager pages to xPDO, cleaning up XHTML\n- Emulated PDO can now be forced in PHP 5.1+ when PDO class is already available, but the required drivers are not available.\n- Added $modx->getTree() function for easily getting a tree structure of MODx resource ids in the current context.\n- Modified $modx->resourceMap to a simpler structure and optimized getParentIds() and getChildIds() functions. $modx->documentMap still holds the old structure but is deprecated.\n- Refactored entire caching layer, based on changes to xPDO. Files are now spread amongst logical directories, and automatic temp directory detection was also added.\n- Translated all core files and data in the core distribution/installation to the new native tag format.\n- Optimized modParser, removing run-time translation with modParser095 from normal execution and added modTranslate095 utility class, which can translate tags in database and file content, writing a log of the translation and/or making the changes to the database and files. modParser095 is experimental, and not recommended, as there are too many issues with mixed tags being parsed incorrectly.\n- Fix to make sure modX::parseChunk removes replacement placeholders for empty values.\n- Updates to MakeForm class.\n- Added modXMLRPCResource, modXMLRPCResponse classes and supporting code, including modified XML-RPC for PHP code (from version 2.1). You can now create resources that represent XMLRPC servers and clients.\n- Altered session cookie expiration that was getting set automatically on all sessions based on the default session cookie lifetime. Lifetime is now only applied if a session value is set for each context.\n- Added check to verify keys passed to modX::getPlaceholder() are valid strings to avoid PHP errors.\n- Various additional changes to prevent errors from revealing critical database credentials and connection information.\n- Fixed bug with system settings getting overwritten on mutate_settings manager page.\n- Merged from trunk (0.9.5.1-RC1) at revision 2251.\n- Latest updates and bug fixes from xPDO project.\n- Add ability to locate and use original manager/config/config.inc.php to upgrade directly on legacy installations.\n- Applied fixes to modResponse::outputContent(); was not assigning regClient script replacements to the output.\n- Changed parseChunk to parse new style tags to avoid any accidental matches on mixed tag situations.\n- Changed modChunk and modTemplate logic to create placeholders from any properties of the elements prefixed by the name of the element + '.' (added the .).\n- Fixed alias path generation, was reversing the order of parent paths in the resourceListing.\n- Fixed problems with recent changes to modRequest::sanitizeRequest() which was again truncating $_POST vars in the manager when encountering MODx tags.\n- Fixed generation of context cache files; was generating an eventMap for the mgr context at all times.\n- Fix to logic in modDocument::getMany('modTemplateVar').\n- Merge with 0.9.5.1 trunk at revision 2205.\n- Parsing adjustments to better deal with mixed old and new style tags.\n- [xPDO] Significant xPDO core update to prepare for SQLite, PostgreSQL and other ports.\n- Fix bug in install/upgrade SQL when resetting user and system settings for manager_theme.\n- Added some new configuration options for session handling and various caching features; more to come.\n- Minor changes to reduce number of unique db connections used during a request.\n- Various PHP 4 warnings fixed when assigning values by reference directly from functions (only variables can be assigned by reference in PHP 4).\n- Various improvements to MakeTable class based on usage in user_management and other manager interfaces.\n- Begin replacing Datagrid usage in manager with MakeTable (user_management, web_user_management, manage_modules, docmanager module); lots more Datagrids to replace.\n- Various changes to DataGrid and DatasetPager to try and support existing usage.\n- Fix for @EVAL bindings with more than one line of code.\n- Adjustments to modParser::collectElementTags() to better handle invalid tags (i.e. mispelled snippet names) with nested tags.\n- Adjustments to modParser095::translate() to properly handle translation from old to new configuration tags [(email_sender)] to [[++email_sender]].\n- DBAPI::escape() adjustment (again) to avoid certain issues when using native PDO along-side legacy manager code calling the mysql extension.\n- Removed & from getMany call in modCacheManager to prevent PHP warnings in PHP 4.\n- [xPDO] Added additional logic to xPDO::loadClass() which will return an error immediately if no class name is provided.\n- Adjusted modDocument::getMany() signature; added $cacheFlag= false parameter.\n- Remerged mutate_content.dynamic.php to fix several problems saving documents.\n- Adjusted queries in refresh_site.dynamic.php.\n- Added session table to install script due to failure of auto-table creation on some environments.\n- Removed unnecessary if statement around session_set_save_handler() in modX::_initSession(); the actual problem was auto-table creation was failing.\n- Fix DBAPI::escape() function; PDO::quote() adds single-quotes unlike the legacy mysql escape functions and this was causing content truncation.\n- [xPDO] xPDOCacheHandler class updated to allow configuration properties to determine a class for handling xPDO object and result set caching.\n- modX::_initSession() updated to better handle situations where session_set_save_handler() fails when trying to override default PHP session handling.\n- [xPDO] Modified fromArray() so it is not responsible for determining the _new attribute of xPDOObject instances. This is the responsibility of xPDO::getObject(), which uses xPDO::load(), and xPDO::getCollection().\n- Fix datasetpager error with PDO changes so DocManager module can load.\n- Fix WebUser login -- weblogin.processor.inc.php.\n- Fix makeUrl() -- no longer needs to add base_url.\n- Fix upgrade install script to insert new config settings properly.\n- Few tweaks to modX::_initSession function (was setting session_name twice).\n- Changed all line-endings to unix-style \\n on all files.\n- Removed assets/cache/* which is replaced by core/cache/*.\n- Updated version data format to be compatible with PHP's version_compare() function.\n- Resolved problems setting primary keys values and improperly identifying new objects when using xPDOObject::fromArray().\n- Several adjustments to xPDO::load(), xPDO::getCollection() and several xPDOObject methods based on changes to xPDOObject::fromArray().\n- Added stripslashes() to modRequest::_sanitize() when working with magic_quotes_gpc enabled.\n- Fix to MakeTable::prepareOrderByLink() to handle FURLs properly.\n- Reduce exposure of critical database credentials in xPDO::load() when errors are reported/logged.\n- Fixed error in xPDOObject::save(); updates to objects with compound primary keys were failing.\n- Added proper escapes to deprecated modX::getFullTableName() to fix issues when dashes (-) or other reserved (My)SQL characters appear in a database name.\n- Merged with trunk (0.9.5 final) at revision 2106.\n- Removed session_keepalive code.\n- Merged with trunk (0.9.5) at revision 2066.\n- Merged with trunk (0.9.5) at revision 2063.\n- Schema updates based on column size changes in 0.9.5.\n- Added missing modX::getSettings() method.\n- Various bug fixes.\n- Merged with trunk (0.9.5) at revision 1945.\n- [bug fix] Fixed a modParser bug when CDATA wrappers were encountered.\n- Add missing webAlert function to new modX class.\n- Modify categories save process to get the insert id using $modx->lastInsertId().\n- Fix to setup.sql; changed ENGINE= to TYPE= when creating new context table to avoid problems with MySQL versions before 4.1.\n- Fixed invalid reference to mergeDocumentMETATags in modResponse class.\n- [New feature] Allow custom error handler classes.\n- [New feature] Fine-grained configuration options for caching pages, database results, or disabling the cache altogether (see system settings starting with `cache.`). Turn the different caching options on/off or set a default time-to-live for those items being cached.\n- [New feature] Database result-set and xPDO object caching, with support for memcache, native-JSON object caching for high-performance AJAX requests.\n- [New feature] Configurable session management with default implementation configured for modSessionHandler, an xPDO-based implementation that stores sessions in a database, and allows a great deal of configurability, by site and/or context.\n- [New feature] Contexts allows a site to be organized into sub-sites, subdomains, etc, and override any system settings by context. The default contexts are 'web' and 'mgr' to support the legacy ideas of front-end and back-end session contexts.\n- Introducing the new MODx core built on top of xPDO; this will incrementally replace the entire existing codebase, but can co-exist until 1.0 release and provides about 90 to 95% legacy compatibility for existing tags and add-ons." ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [6, 321], "buggy_code_start_loc": [6, 2], "filenames": ["core/docs/changelog.txt", "core/model/phpthumb/modphpthumb.class.php"], "fixing_code_end_loc": [8, 345], "fixing_code_start_loc": [7, 2], "message": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF008510-C712-4018-9E0B-022CFA929190", "versionEndExcluding": null, "versionEndIncluding": "2.6.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68."}, {"lang": "es", "value": "MODX Revolution en versiones iguales o anteriores a la 2.6.4 contiene una vulnerabilidad de control de acceso incorrecto en el filtrado de par\u00e1metros user antes de pasarlos a la clase phpthumb, lo que puede resultar en la creaci\u00f3n de un archivo con un nombre de archivo y un contenido personalizados. Parece ser que este ataque puede ser explotado mediante una petici\u00f3n web. La vulnerabilidad parece haber sido solucionada en el commit con ID 06bc94257408f6a575de20ddb955aca505ef6e68."}], "evaluatorComment": null, "id": "CVE-2018-1000207", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-13T18:29:00.270", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory"], "url": "https://github.com/a2u/CVE-2018-1000207"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/pull/13979"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://rudnkh.me/posts/critical-vulnerability-in-modx-revolution-2-6-4"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-732"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, "type": "CWE-732"}
38
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "/**\n * @package modx\n * @subpackage phpthumb\n */\nrequire_once MODX_CORE_PATH.'model/phpthumb/phpthumb.class.php';", "/**\n * Helper class to extend phpThumb and simplify thumbnail generation process\n * since phpThumb class is overly convoluted and doesn't do enough.\n *\n * @package modx\n * @subpackage phpthumb\n */", "class modPhpThumb extends phpThumb {\n", " public $modx;", " public $config;", " function __construct(modX &$modx,array $config = array()) {", " $this->modx =& $modx;", " $this->config = array_merge(array(", " ),$config);", " parent::__construct();\n }", " /**\n * Setup some site-wide phpthumb options from modx config\n */", " public function initialize() {", " $cachePath = $this->modx->getOption('core_path',null,MODX_CORE_PATH).'cache/phpthumb/';", " if (!is_dir($cachePath)) $this->modx->cacheManager->writeTree($cachePath);\n $this->setParameter('config_cache_directory',$cachePath);\n $this->setParameter('config_temp_directory',$cachePath);", " $this->setCacheDirectory();", " $this->setParameter('config_allow_src_above_docroot',(boolean)$this->modx->getOption('phpthumb_allow_src_above_docroot',$this->config,false));\n $this->setParameter('config_cache_maxage',(float)$this->modx->getOption('phpthumb_cache_maxage',$this->config,30) * 86400);\n $this->setParameter('config_cache_maxsize',(float)$this->modx->getOption('phpthumb_cache_maxsize',$this->config,100) * 1024 * 1024);\n $this->setParameter('config_cache_maxfiles',(int)$this->modx->getOption('phpthumb_cache_maxfiles',$this->config,10000));\n $this->setParameter('config_error_bgcolor',(string)$this->modx->getOption('phpthumb_error_bgcolor',$this->config,'CCCCFF'));\n $this->setParameter('config_error_textcolor',(string)$this->modx->getOption('phpthumb_error_textcolor',$this->config,'FF0000'));\n $this->setParameter('config_error_fontsize',(int)$this->modx->getOption('phpthumb_error_fontsize',$this->config,1));\n $this->setParameter('config_nohotlink_enabled',(boolean)$this->modx->getOption('phpthumb_nohotlink_enabled',$this->config,true));\n $this->setParameter('config_nohotlink_valid_domains',explode(',', $this->modx->getOption('phpthumb_nohotlink_valid_domains',$this->config,$this->modx->getOption('http_host'))));\n $this->setParameter('config_nohotlink_erase_image',(boolean)$this->modx->getOption('phpthumb_nohotlink_erase_image',$this->config,true));\n $this->setParameter('config_nohotlink_text_message',(string)$this->modx->getOption('phpthumb_nohotlink_text_message',$this->config,'Off-server thumbnailing is not allowed'));\n $this->setParameter('config_nooffsitelink_enabled',(boolean)$this->modx->getOption('phpthumb_nooffsitelink_enabled',$this->config,false));\n $this->setParameter('config_nooffsitelink_valid_domains',explode(',', $this->modx->getOption('phpthumb_nooffsitelink_valid_domains',$this->config,$this->modx->getOption('http_host'))));\n $this->setParameter('config_nooffsitelink_require_refer',(boolean)$this->modx->getOption('phpthumb_nooffsitelink_require_refer',$this->config,false));\n $this->setParameter('config_nooffsitelink_erase_image',(boolean)$this->modx->getOption('phpthumb_nooffsitelink_erase_image',$this->config,true));\n $this->setParameter('config_nooffsitelink_watermark_src',(string)$this->modx->getOption('phpthumb_nooffsitelink_watermark_src',$this->config,''));\n $this->setParameter('config_nooffsitelink_text_message',(string)$this->modx->getOption('phpthumb_nooffsitelink_text_message',$this->config,'Off-server linking is not allowed'));", "", " $this->setParameter('cache_source_enabled',(boolean)$this->modx->getOption('phpthumb_cache_source_enabled',$this->config,false));\n $this->setParameter('cache_source_directory',$cachePath.'source/');\n $this->setParameter('allow_local_http_src',true);\n $this->setParameter('zc',$this->modx->getOption('zc',$_REQUEST,$this->modx->getOption('phpthumb_zoomcrop',$this->config,0)));\n $this->setParameter('far',$this->modx->getOption('far',$_REQUEST,$this->modx->getOption('phpthumb_far',$this->config,'C')));\n $this->setParameter('cache_directory_depth',4);", " $this->setParameter('config_ttf_directory',$this->modx->getOption('core_path',$this->config,MODX_CORE_PATH).'model/phpthumb/fonts/');", "\n $documentRoot = $this->modx->getOption('phpthumb_document_root',$this->config, '');\n if ($documentRoot == '') $documentRoot = $this->modx->getOption('base_path', null, '');\n if (!empty($documentRoot)) {\n $this->setParameter('config_document_root',$documentRoot);\n }\n", "", " /* iterate through properties */\n foreach ($this->config as $property => $value) {", " $this->setParameter($property,$value);\n }", " return true;\n }", " /**\n * Sets the source image\n */\n public function set($src) {\n $src = rawurldecode($src);\n if (empty($src)) return '';\n return $this->setSourceFilename($src);\n }", " /**\n * Check to see if cached file already exists\n */\n public function checkForCachedFile() {\n $this->SetCacheFilename();\n if (file_exists($this->cache_filename) && is_readable($this->cache_filename)) {\n return true;\n }\n return false;\n }", " /**\n * Load cached file\n */\n public function loadCache() {\n $this->RedirectToCachedFile();\n }", " /**\n * Cache the generated thumbnail.\n */\n public function cache() {\n phpthumb_functions::EnsureDirectoryExists(dirname($this->cache_filename));\n if ((file_exists($this->cache_filename) && is_writable($this->cache_filename)) || is_writable(dirname($this->cache_filename))) {\n $this->CleanUpCacheDirectory();\n if ($this->RenderToFile($this->cache_filename) && is_readable($this->cache_filename)) {\n chmod($this->cache_filename, 0644);\n $this->RedirectToCachedFile();\n }\n }\n }", " /**\n * Generate a thumbnail\n */\n public function generate() {\n if (!$this->GenerateThumbnail()) {\n $this->modx->log(modX::LOG_LEVEL_ERROR,'phpThumb was unable to generate a thumbnail for: '.$this->cache_filename);\n return false;\n }\n return true;\n }", " /**\n * Output a thumbnail.\n */\n public function output() {\n $output = $this->OutputThumbnail();\n if (!$output) {\n $this->modx->log(modX::LOG_LEVEL_ERROR,'Error outputting thumbnail:'.\"\\n\".$this->debugmessages[(count($this->debugmessages) - 1)]);\n }\n return $output;\n }", "\n /** PHPTHUMB HELPER METHODS **/", " public function RedirectToCachedFile() {", " $nice_cachefile = str_replace(DIRECTORY_SEPARATOR, '/', $this->cache_filename);\n $nice_docroot = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($this->config_document_root, '/\\\\'));", " $parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);", " $nModified = filemtime($this->cache_filename);", " if ($this->config_nooffsitelink_enabled && @$_SERVER['HTTP_REFERER'] && !in_array(@$parsed_url['host'], $this->config_nooffsitelink_valid_domains)) {", " $this->DebugMessage('Would have used cached (image/'.$this->thumbnailFormat.') file \"'.$this->cache_filename.'\" (Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT), but skipping because $_SERVER[HTTP_REFERER] ('.@$_SERVER['HTTP_REFERER'].') is not in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);", " } elseif ($this->phpThumbDebug) {", " $this->DebugTimingMessage('skipped using cached image', __FILE__, __LINE__);\n $this->DebugMessage('Would have used cached file, but skipping due to phpThumbDebug', __FILE__, __LINE__);\n $this->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT', __FILE__, __LINE__);\n $getimagesize = @getimagesize($this->cache_filename);\n if ($getimagesize) {\n $this->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);\n }\n if (preg_match('/^'.preg_quote($nice_docroot, '/').'(.*)$/', $nice_cachefile, $matches)) {\n $this->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);\n } else {\n $this->DebugMessage('* Would have sent data: readfile('.$this->cache_filename.')', __FILE__, __LINE__);\n }", " } else {\n/*\n if (headers_sent()) {\n $this->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');\n exit;\n }*/\n $this->SendSaveAsFileHeaderIfNeeded();", " header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');\n if (@$_SERVER['HTTP_IF_MODIFIED_SINCE'] && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && @$_SERVER['SERVER_PROTOCOL']) {\n header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');\n exit;\n }", " $getimagesize = @getimagesize($this->cache_filename);\n if ($getimagesize) {\n header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));\n } elseif (preg_match('#\\.ico$#i', $this->cache_filename)) {\n header('Content-Type: image/x-icon');\n }\n if (!$this->config_cache_force_passthru && preg_match('#^'.preg_quote($nice_docroot, '/').'(.*)$#', $nice_cachefile, $matches)) {\n header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));\n } else {\n @readfile($this->cache_filename);\n }\n session_write_close();\n exit;", " }\n return true;\n }\n public function SendSaveAsFileHeaderIfNeeded() {\n if (headers_sent()) {\n return false;\n }\n $downloadfilename = phpthumb_functions::SanitizeFilename(@$_GET['sia'] ? $_GET['sia'] : (@$_GET['down'] ? $_GET['down'] : 'phpThumb_generated_thumbnail'.(@$_GET['f'] ? $_GET['f'] : 'jpg')));\n if (@$downloadfilename) {\n $this->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: '.(@$_GET['down'] ? 'attachment' : 'inline').'; filename=\"'.$downloadfilename.'\"', __FILE__, __LINE__);\n header('Content-Disposition: '.(@$_GET['down'] ? 'attachment' : 'inline').'; filename=\"'.$downloadfilename.'\"');\n }\n return true;\n }", " function ResolveFilenameToAbsolute($filename) {\n if (empty($filename)) {\n return false;\n }", " if (preg_match('#^[a-z0-9]+\\:/{1,2}#i', $filename)) {\n // eg: http://host/path/file.jpg (HTTP URL)\n // eg: ftp://host/path/file.jpg (FTP URL)\n // eg: data1:/path/file.jpg (Netware path)", " //$AbsoluteFilename = $filename;\n return $filename;", " } elseif ($this->iswindows && isset($filename{1}) && ($filename{1} == ':')) {", " // absolute pathname (Windows)\n $AbsoluteFilename = $filename;", " } elseif ($this->iswindows && ((substr($filename, 0, 2) == '//') || (substr($filename, 0, 2) == '\\\\\\\\'))) {", " // absolute pathname (Windows)\n $AbsoluteFilename = $filename;", " } elseif ($filename{0} == '/') {", " if (@is_readable($filename) && !@is_readable($this->config_document_root.$filename)) {", " // absolute filename (*nix)\n $AbsoluteFilename = $filename;", " } elseif (isset($filename{1}) && ($filename{1} == '~')) {", " // /~user/path\n if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray($filename)) {\n $AbsoluteFilename = $ApacheLookupURIarray['filename'];\n } else {\n $AbsoluteFilename = realpath($filename);\n if (@is_readable($AbsoluteFilename)) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.$filename.'\", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with realpath($filename)', __FILE__, __LINE__);\n } elseif (is_dir(dirname($AbsoluteFilename))) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname($filename).'\", but the correct directory ('.dirname($AbsoluteFilename).') seems to have been resolved with realpath(.)', __FILE__, __LINE__);\n } else {\n return $this->ErrorImage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.$filename.'\". This has been known to fail on Apache2 - try using the absolute filename for the source image (ex: \"/home/user/httpdocs/image.jpg\" instead of \"/~user/image.jpg\")');\n }\n }", " } else {", " // relative filename (any OS)\n if (preg_match('#^'.preg_quote($this->config_document_root).'#', $filename)) {\n $AbsoluteFilename = $filename;\n $this->DebugMessage('ResolveFilenameToAbsolute() NOT prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = \"'.$AbsoluteFilename.'\")', __FILE__, __LINE__);\n } else {\n $AbsoluteFilename = $this->config_document_root.$filename;\n $this->DebugMessage('ResolveFilenameToAbsolute() prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = \"'.$AbsoluteFilename.'\")', __FILE__, __LINE__);\n }", " }", " } else {", " // relative to current directory (any OS)\n $AbsoluteFilename = $this->config_document_root.preg_replace('#[/\\\\\\\\]#', DIRECTORY_SEPARATOR, dirname(@$_SERVER['PHP_SELF'])).DIRECTORY_SEPARATOR.preg_replace('#[/\\\\\\\\]#', DIRECTORY_SEPARATOR, $filename);\n//\t\t\t$AbsoluteFilename = dirname(__FILE__).DIRECTORY_SEPARATOR.preg_replace('#[/\\\\\\\\]#', DIRECTORY_SEPARATOR, $filename);", " $AbsoluteFilename = preg_replace('~[\\/]+~', DIRECTORY_SEPARATOR, $AbsoluteFilename);", " //if (!@file_exists($AbsoluteFilename) && @file_exists(realpath($this->DotPadRelativeDirectoryPath($filename)))) {\n //\t$AbsoluteFilename = realpath($this->DotPadRelativeDirectoryPath($filename));\n //}", " if (substr(dirname(@$_SERVER['PHP_SELF']), 0, 2) == '/~') {\n if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) {\n $AbsoluteFilename = $ApacheLookupURIarray['filename'].DIRECTORY_SEPARATOR.$filename;\n } else {\n $AbsoluteFilename = realpath('.').DIRECTORY_SEPARATOR.$filename;\n if (@is_readable($AbsoluteFilename)) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname(@$_SERVER['PHP_SELF']).'\", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with realpath(.)/$filename', __FILE__, __LINE__);\n } elseif (is_dir(dirname($AbsoluteFilename))) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname(@$_SERVER['PHP_SELF']).'\", but the correct directory ('.dirname($AbsoluteFilename).') seems to have been resolved with realpath(.)', __FILE__, __LINE__);\n } else {\n return $this->ErrorImage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname(@$_SERVER['PHP_SELF']).'\". This has been known to fail on Apache2 - try using the absolute filename for the source image');\n }\n }\n }", " }\n if (is_link($AbsoluteFilename)) {\n $this->DebugMessage('is_link()==true, changing \"'.$AbsoluteFilename.'\" to \"'.readlink($AbsoluteFilename).'\"', __FILE__, __LINE__);\n $AbsoluteFilename = readlink($AbsoluteFilename);\n }\n if (realpath($AbsoluteFilename)) {\n $AbsoluteFilename = realpath($AbsoluteFilename);\n }\n if ($this->iswindows) {\n $AbsoluteFilename = preg_replace('#^'.preg_quote(realpath($this->config_document_root)).'#i', realpath($this->config_document_root), $AbsoluteFilename);\n $AbsoluteFilename = str_replace(DIRECTORY_SEPARATOR, '/', $AbsoluteFilename);\n }\n if (!$this->config_allow_src_above_docroot && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath($this->config_document_root))).'#', $AbsoluteFilename)) {\n $this->DebugMessage('!$this->config_allow_src_above_docroot therefore setting \"'.$AbsoluteFilename.'\" (outside \"'.realpath($this->config_document_root).'\") to null', __FILE__, __LINE__);\n return false;\n }\n if (!$this->config_allow_src_above_phpthumb && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__))).'#', $AbsoluteFilename)) {\n $this->DebugMessage('!$this->config_allow_src_above_phpthumb therefore setting \"'.$AbsoluteFilename.'\" (outside \"'.dirname(__FILE__).'\") to null', __FILE__, __LINE__);\n return false;\n }\n return $AbsoluteFilename;\n }", "", "}" ]
[ 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 ]
PreciseBugs
{"buggy_code_end_loc": [6, 321], "buggy_code_start_loc": [6, 2], "filenames": ["core/docs/changelog.txt", "core/model/phpthumb/modphpthumb.class.php"], "fixing_code_end_loc": [8, 345], "fixing_code_start_loc": [7, 2], "message": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF008510-C712-4018-9E0B-022CFA929190", "versionEndExcluding": null, "versionEndIncluding": "2.6.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68."}, {"lang": "es", "value": "MODX Revolution en versiones iguales o anteriores a la 2.6.4 contiene una vulnerabilidad de control de acceso incorrecto en el filtrado de par\u00e1metros user antes de pasarlos a la clase phpthumb, lo que puede resultar en la creaci\u00f3n de un archivo con un nombre de archivo y un contenido personalizados. Parece ser que este ataque puede ser explotado mediante una petici\u00f3n web. La vulnerabilidad parece haber sido solucionada en el commit con ID 06bc94257408f6a575de20ddb955aca505ef6e68."}], "evaluatorComment": null, "id": "CVE-2018-1000207", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-13T18:29:00.270", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory"], "url": "https://github.com/a2u/CVE-2018-1000207"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/pull/13979"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://rudnkh.me/posts/critical-vulnerability-in-modx-revolution-2-6-4"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-732"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, "type": "CWE-732"}
38
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "\nrequire_once MODX_CORE_PATH . 'model/phpthumb/phpthumb.class.php';\n", "/**\n * Helper class to extend phpThumb and simplify thumbnail generation process\n * since phpThumb class is overly convoluted and doesn't do enough.\n *\n * @package modx\n * @subpackage phpthumb\n */", "class modPhpThumb extends phpThumb\n{", " public $modx;", "\n public $config = array();", " /**\n * modPhpThumb constructor.\n * @param modX $modx\n * @param array $config\n */\n public function __construct(modX &$modx, array $config = array())\n {", " $this->modx =& $modx;", " $this->config = $config;\n", " parent::__construct();\n }", " /**\n * Setup some site-wide phpthumb options from modx config\n */", " public function initialize()\n {", " $cachePath = $this->modx->getOption('core_path',null,MODX_CORE_PATH).'cache/phpthumb/';", " if (!is_dir($cachePath)) {\n $this->modx->cacheManager->writeTree($cachePath);\n }\n $this->setParameter('config_cache_directory', $cachePath);\n $this->setParameter('config_temp_directory', $cachePath);", " $this->setCacheDirectory();", " $this->setParameter('config_allow_src_above_docroot',(boolean)$this->modx->getOption('phpthumb_allow_src_above_docroot',$this->config,false));\n $this->setParameter('config_cache_maxage',(float)$this->modx->getOption('phpthumb_cache_maxage',$this->config,30) * 86400);\n $this->setParameter('config_cache_maxsize',(float)$this->modx->getOption('phpthumb_cache_maxsize',$this->config,100) * 1024 * 1024);\n $this->setParameter('config_cache_maxfiles',(int)$this->modx->getOption('phpthumb_cache_maxfiles',$this->config,10000));\n $this->setParameter('config_error_bgcolor',(string)$this->modx->getOption('phpthumb_error_bgcolor',$this->config,'CCCCFF'));\n $this->setParameter('config_error_textcolor',(string)$this->modx->getOption('phpthumb_error_textcolor',$this->config,'FF0000'));\n $this->setParameter('config_error_fontsize',(int)$this->modx->getOption('phpthumb_error_fontsize',$this->config,1));\n $this->setParameter('config_nohotlink_enabled',(boolean)$this->modx->getOption('phpthumb_nohotlink_enabled',$this->config,true));\n $this->setParameter('config_nohotlink_valid_domains',explode(',', $this->modx->getOption('phpthumb_nohotlink_valid_domains',$this->config,$this->modx->getOption('http_host'))));\n $this->setParameter('config_nohotlink_erase_image',(boolean)$this->modx->getOption('phpthumb_nohotlink_erase_image',$this->config,true));\n $this->setParameter('config_nohotlink_text_message',(string)$this->modx->getOption('phpthumb_nohotlink_text_message',$this->config,'Off-server thumbnailing is not allowed'));\n $this->setParameter('config_nooffsitelink_enabled',(boolean)$this->modx->getOption('phpthumb_nooffsitelink_enabled',$this->config,false));\n $this->setParameter('config_nooffsitelink_valid_domains',explode(',', $this->modx->getOption('phpthumb_nooffsitelink_valid_domains',$this->config,$this->modx->getOption('http_host'))));\n $this->setParameter('config_nooffsitelink_require_refer',(boolean)$this->modx->getOption('phpthumb_nooffsitelink_require_refer',$this->config,false));\n $this->setParameter('config_nooffsitelink_erase_image',(boolean)$this->modx->getOption('phpthumb_nooffsitelink_erase_image',$this->config,true));\n $this->setParameter('config_nooffsitelink_watermark_src',(string)$this->modx->getOption('phpthumb_nooffsitelink_watermark_src',$this->config,''));\n $this->setParameter('config_nooffsitelink_text_message',(string)$this->modx->getOption('phpthumb_nooffsitelink_text_message',$this->config,'Off-server linking is not allowed'));", " $this->setParameter('config_ttf_directory', (string)$this->modx->getOption('core_path', $this->config, MODX_CORE_PATH) . 'model/phpthumb/fonts/');\n $this->setParameter('config_imagemagick_path', (string)$this->modx->getOption('phpthumb_imagemagick_path', $this->config, null));\n", " $this->setParameter('cache_source_enabled',(boolean)$this->modx->getOption('phpthumb_cache_source_enabled',$this->config,false));\n $this->setParameter('cache_source_directory',$cachePath.'source/');\n $this->setParameter('allow_local_http_src',true);\n $this->setParameter('zc',$this->modx->getOption('zc',$_REQUEST,$this->modx->getOption('phpthumb_zoomcrop',$this->config,0)));\n $this->setParameter('far',$this->modx->getOption('far',$_REQUEST,$this->modx->getOption('phpthumb_far',$this->config,'C')));\n $this->setParameter('cache_directory_depth',4);", "", "\n $documentRoot = $this->modx->getOption('phpthumb_document_root',$this->config, '');\n if ($documentRoot == '') $documentRoot = $this->modx->getOption('base_path', null, '');\n if (!empty($documentRoot)) {\n $this->setParameter('config_document_root',$documentRoot);\n }\n", " // Only public parameters of phpThumb should be allowed to pass from user input.\n // List properties between START PARAMETERS and START PARAMETERS in src/core/model/phpthumb/phpthumb.class.php\n $allowed = array(\n 'src', 'new', 'w', 'h', 'wp', 'hp', 'wl', 'hl', 'ws', 'hs',\n 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'zc', 'bc', 'bg', 'fltr',\n 'goto', 'err', 'xto', 'ra', 'ar', 'aoe', 'far', 'iar', 'maxb', 'down',\n 'md5s', 'sfn', 'dpi', 'sia', 'phpThumbDebug'\n );\n", " /* iterate through properties */\n foreach ($this->config as $property => $value) {", " if (!in_array($property, $allowed, true)) {\n $this->modx->log(modX::LOG_LEVEL_WARN,\"Detected attempt of using private parameter `$property` (for internal usage) of phpThumb that not allowed and insecure\");\n continue;\n }\n $this->setParameter($property, $value);\n }\n", " return true;\n }", " /**\n * Sets the source image\n */\n public function set($src) {\n $src = rawurldecode($src);\n if (empty($src)) return '';\n return $this->setSourceFilename($src);\n }", " /**\n * Check to see if cached file already exists\n */\n public function checkForCachedFile() {\n $this->SetCacheFilename();\n if (file_exists($this->cache_filename) && is_readable($this->cache_filename)) {\n return true;\n }\n return false;\n }", " /**\n * Load cached file\n */\n public function loadCache() {\n $this->RedirectToCachedFile();\n }", " /**\n * Cache the generated thumbnail.\n */\n public function cache() {\n phpthumb_functions::EnsureDirectoryExists(dirname($this->cache_filename));\n if ((file_exists($this->cache_filename) && is_writable($this->cache_filename)) || is_writable(dirname($this->cache_filename))) {\n $this->CleanUpCacheDirectory();\n if ($this->RenderToFile($this->cache_filename) && is_readable($this->cache_filename)) {\n chmod($this->cache_filename, 0644);\n $this->RedirectToCachedFile();\n }\n }\n }", " /**\n * Generate a thumbnail\n */\n public function generate() {\n if (!$this->GenerateThumbnail()) {\n $this->modx->log(modX::LOG_LEVEL_ERROR,'phpThumb was unable to generate a thumbnail for: '.$this->cache_filename);\n return false;\n }\n return true;\n }", " /**\n * Output a thumbnail.\n */\n public function output() {\n $output = $this->OutputThumbnail();\n if (!$output) {\n $this->modx->log(modX::LOG_LEVEL_ERROR,'Error outputting thumbnail:'.\"\\n\".$this->debugmessages[(count($this->debugmessages) - 1)]);\n }\n return $output;\n }", "\n /** PHPTHUMB HELPER METHODS **/", " public function RedirectToCachedFile() {", " $nice_cachefile = str_replace(DIRECTORY_SEPARATOR, '/', $this->cache_filename);\n $nice_docroot = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($this->config_document_root, '/\\\\'));", " $parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);", " $nModified = filemtime($this->cache_filename);", " if ($this->config_nooffsitelink_enabled && @$_SERVER['HTTP_REFERER'] && !in_array(@$parsed_url['host'], $this->config_nooffsitelink_valid_domains)) {", " $this->DebugMessage('Would have used cached (image/'.$this->thumbnailFormat.') file \"'.$this->cache_filename.'\" (Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT), but skipping because $_SERVER[HTTP_REFERER] ('.@$_SERVER['HTTP_REFERER'].') is not in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);", " } elseif ($this->phpThumbDebug) {", " $this->DebugTimingMessage('skipped using cached image', __FILE__, __LINE__);\n $this->DebugMessage('Would have used cached file, but skipping due to phpThumbDebug', __FILE__, __LINE__);\n $this->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT', __FILE__, __LINE__);\n $getimagesize = @getimagesize($this->cache_filename);\n if ($getimagesize) {\n $this->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);\n }\n if (preg_match('/^'.preg_quote($nice_docroot, '/').'(.*)$/', $nice_cachefile, $matches)) {\n $this->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);\n } else {\n $this->DebugMessage('* Would have sent data: readfile('.$this->cache_filename.')', __FILE__, __LINE__);\n }", " } else {\n/*\n if (headers_sent()) {\n $this->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');\n exit;\n }*/\n $this->SendSaveAsFileHeaderIfNeeded();", " header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');\n if (@$_SERVER['HTTP_IF_MODIFIED_SINCE'] && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && @$_SERVER['SERVER_PROTOCOL']) {\n header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');\n exit;\n }", " $getimagesize = @getimagesize($this->cache_filename);\n if ($getimagesize) {\n header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));\n } elseif (preg_match('#\\.ico$#i', $this->cache_filename)) {\n header('Content-Type: image/x-icon');\n }\n if (!$this->config_cache_force_passthru && preg_match('#^'.preg_quote($nice_docroot, '/').'(.*)$#', $nice_cachefile, $matches)) {\n header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));\n } else {\n @readfile($this->cache_filename);\n }\n session_write_close();\n exit;", " }\n return true;\n }\n public function SendSaveAsFileHeaderIfNeeded() {\n if (headers_sent()) {\n return false;\n }\n $downloadfilename = phpthumb_functions::SanitizeFilename(@$_GET['sia'] ? $_GET['sia'] : (@$_GET['down'] ? $_GET['down'] : 'phpThumb_generated_thumbnail'.(@$_GET['f'] ? $_GET['f'] : 'jpg')));\n if (@$downloadfilename) {\n $this->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: '.(@$_GET['down'] ? 'attachment' : 'inline').'; filename=\"'.$downloadfilename.'\"', __FILE__, __LINE__);\n header('Content-Disposition: '.(@$_GET['down'] ? 'attachment' : 'inline').'; filename=\"'.$downloadfilename.'\"');\n }\n return true;\n }", " function ResolveFilenameToAbsolute($filename) {\n if (empty($filename)) {\n return false;\n }", " if (preg_match('#^[a-z0-9]+\\:/{1,2}#i', $filename)) {\n // eg: http://host/path/file.jpg (HTTP URL)\n // eg: ftp://host/path/file.jpg (FTP URL)\n // eg: data1:/path/file.jpg (Netware path)", " //$AbsoluteFilename = $filename;\n return $filename;", " } elseif ($this->iswindows && isset($filename{1}) && ($filename{1} == ':')) {", " // absolute pathname (Windows)\n $AbsoluteFilename = $filename;", " } elseif ($this->iswindows && ((substr($filename, 0, 2) == '//') || (substr($filename, 0, 2) == '\\\\\\\\'))) {", " // absolute pathname (Windows)\n $AbsoluteFilename = $filename;", " } elseif ($filename{0} == '/') {", " if (@is_readable($filename) && !@is_readable($this->config_document_root.$filename)) {", " // absolute filename (*nix)\n $AbsoluteFilename = $filename;", " } elseif (isset($filename{1}) && ($filename{1} == '~')) {", " // /~user/path\n if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray($filename)) {\n $AbsoluteFilename = $ApacheLookupURIarray['filename'];\n } else {\n $AbsoluteFilename = realpath($filename);\n if (@is_readable($AbsoluteFilename)) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.$filename.'\", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with realpath($filename)', __FILE__, __LINE__);\n } elseif (is_dir(dirname($AbsoluteFilename))) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname($filename).'\", but the correct directory ('.dirname($AbsoluteFilename).') seems to have been resolved with realpath(.)', __FILE__, __LINE__);\n } else {\n return $this->ErrorImage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.$filename.'\". This has been known to fail on Apache2 - try using the absolute filename for the source image (ex: \"/home/user/httpdocs/image.jpg\" instead of \"/~user/image.jpg\")');\n }\n }", " } else {", " // relative filename (any OS)\n if (preg_match('#^'.preg_quote($this->config_document_root).'#', $filename)) {\n $AbsoluteFilename = $filename;\n $this->DebugMessage('ResolveFilenameToAbsolute() NOT prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = \"'.$AbsoluteFilename.'\")', __FILE__, __LINE__);\n } else {\n $AbsoluteFilename = $this->config_document_root.$filename;\n $this->DebugMessage('ResolveFilenameToAbsolute() prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = \"'.$AbsoluteFilename.'\")', __FILE__, __LINE__);\n }", " }", " } else {", " // relative to current directory (any OS)\n $AbsoluteFilename = $this->config_document_root.preg_replace('#[/\\\\\\\\]#', DIRECTORY_SEPARATOR, dirname(@$_SERVER['PHP_SELF'])).DIRECTORY_SEPARATOR.preg_replace('#[/\\\\\\\\]#', DIRECTORY_SEPARATOR, $filename);\n//\t\t\t$AbsoluteFilename = dirname(__FILE__).DIRECTORY_SEPARATOR.preg_replace('#[/\\\\\\\\]#', DIRECTORY_SEPARATOR, $filename);", " $AbsoluteFilename = preg_replace('~[\\/]+~', DIRECTORY_SEPARATOR, $AbsoluteFilename);", " //if (!@file_exists($AbsoluteFilename) && @file_exists(realpath($this->DotPadRelativeDirectoryPath($filename)))) {\n //\t$AbsoluteFilename = realpath($this->DotPadRelativeDirectoryPath($filename));\n //}", " if (substr(dirname(@$_SERVER['PHP_SELF']), 0, 2) == '/~') {\n if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) {\n $AbsoluteFilename = $ApacheLookupURIarray['filename'].DIRECTORY_SEPARATOR.$filename;\n } else {\n $AbsoluteFilename = realpath('.').DIRECTORY_SEPARATOR.$filename;\n if (@is_readable($AbsoluteFilename)) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname(@$_SERVER['PHP_SELF']).'\", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with realpath(.)/$filename', __FILE__, __LINE__);\n } elseif (is_dir(dirname($AbsoluteFilename))) {\n $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname(@$_SERVER['PHP_SELF']).'\", but the correct directory ('.dirname($AbsoluteFilename).') seems to have been resolved with realpath(.)', __FILE__, __LINE__);\n } else {\n return $this->ErrorImage('phpthumb_functions::ApacheLookupURIarray() failed for \"'.dirname(@$_SERVER['PHP_SELF']).'\". This has been known to fail on Apache2 - try using the absolute filename for the source image');\n }\n }\n }", " }\n if (is_link($AbsoluteFilename)) {\n $this->DebugMessage('is_link()==true, changing \"'.$AbsoluteFilename.'\" to \"'.readlink($AbsoluteFilename).'\"', __FILE__, __LINE__);\n $AbsoluteFilename = readlink($AbsoluteFilename);\n }\n if (realpath($AbsoluteFilename)) {\n $AbsoluteFilename = realpath($AbsoluteFilename);\n }\n if ($this->iswindows) {\n $AbsoluteFilename = preg_replace('#^'.preg_quote(realpath($this->config_document_root)).'#i', realpath($this->config_document_root), $AbsoluteFilename);\n $AbsoluteFilename = str_replace(DIRECTORY_SEPARATOR, '/', $AbsoluteFilename);\n }\n if (!$this->config_allow_src_above_docroot && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath($this->config_document_root))).'#', $AbsoluteFilename)) {\n $this->DebugMessage('!$this->config_allow_src_above_docroot therefore setting \"'.$AbsoluteFilename.'\" (outside \"'.realpath($this->config_document_root).'\") to null', __FILE__, __LINE__);\n return false;\n }\n if (!$this->config_allow_src_above_phpthumb && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__))).'#', $AbsoluteFilename)) {\n $this->DebugMessage('!$this->config_allow_src_above_phpthumb therefore setting \"'.$AbsoluteFilename.'\" (outside \"'.dirname(__FILE__).'\") to null', __FILE__, __LINE__);\n return false;\n }\n return $AbsoluteFilename;\n }", "", "}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [6, 321], "buggy_code_start_loc": [6, 2], "filenames": ["core/docs/changelog.txt", "core/model/phpthumb/modphpthumb.class.php"], "fixing_code_end_loc": [8, 345], "fixing_code_start_loc": [7, 2], "message": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:modx:modx_revolution:*:*:*:*:*:*:*:*", "matchCriteriaId": "EF008510-C712-4018-9E0B-022CFA929190", "versionEndExcluding": null, "versionEndIncluding": "2.6.4", "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "MODX Revolution version <=2.6.4 contains a Incorrect Access Control vulnerability in Filtering user parameters before passing them into phpthumb class that can result in Creating file with custom a filename and content. This attack appear to be exploitable via Web request. This vulnerability appears to have been fixed in commit 06bc94257408f6a575de20ddb955aca505ef6e68."}, {"lang": "es", "value": "MODX Revolution en versiones iguales o anteriores a la 2.6.4 contiene una vulnerabilidad de control de acceso incorrecto en el filtrado de par\u00e1metros user antes de pasarlos a la clase phpthumb, lo que puede resultar en la creaci\u00f3n de un archivo con un nombre de archivo y un contenido personalizados. Parece ser que este ataque puede ser explotado mediante una petici\u00f3n web. La vulnerabilidad parece haber sido solucionada en el commit con ID 06bc94257408f6a575de20ddb955aca505ef6e68."}], "evaluatorComment": null, "id": "CVE-2018-1000207", "lastModified": "2019-10-03T00:03:26.223", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 6.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 8.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 7.2, "baseSeverity": "HIGH", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "HIGH", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H", "version": "3.0"}, "exploitabilityScore": 1.2, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}], "cvssMetricV31": null}, "published": "2018-07-13T18:29:00.270", "references": [{"source": "cve@mitre.org", "tags": ["Broken Link", "Third Party Advisory"], "url": "https://github.com/a2u/CVE-2018-1000207"}, {"source": "cve@mitre.org", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://github.com/modxcms/revolution/pull/13979"}, {"source": "cve@mitre.org", "tags": ["Exploit", "Third Party Advisory"], "url": "https://rudnkh.me/posts/critical-vulnerability-in-modx-revolution-2-6-4"}], "sourceIdentifier": "cve@mitre.org", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-732"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/modxcms/revolution/commit/06bc94257408f6a575de20ddb955aca505ef6e68"}, "type": "CWE-732"}
38
Determine whether the {function_name} code is vulnerable or not.
[ "========================\n0.0.43\n========================", "- improved `flowinstance.newmessage(data)` method", "", "\n========================\n0.0.42\n========================", "- added support for JSON schemas\n- added Total Messaging Service\n- added `jsonschemas` directory\n- added `schema.jsonschema(name)` method\n- added `JSONSCHEMA()` method\n- added `NEWJSONSCHEMA()` method\n- added `NEWPUBLISH()` method\n- added `NEWSUBSCRIBE()` method\n- added `PUBLISH()` method\n- added `SUBSCRIBE()` method\n- added `UNSUBSCRIBE()` method\n- added `watcher` event for the main process in `debug` or `release` mode with the watcher\n- added HTML escaping for meta tags\n- added `WebSocketClient.destroy()` method\n- added new command `refresh_cmd`\n- added `allow_totalapilogger {Boolean}` option to the configuration\n- added `allow_totalapi {Boolean}` option to the configuration\n- added `allow_tms {Boolean}` option to the configuration\n- added `secret_tms {String}` option to the configuration\n- added `schema.jsonschema_define()` method\n- added `flowstream.load(components, design, [callback])` method\n- added `flowstream.unload(components, design, [callback])` method\n- added new delegate `flowstream.onreconfigure = function(instance) {}`\n- added new delegate `flowstream.onconnect = function(instance) {}`\n- added new delegate `flowstream.ondisconnect = function(instance) {}`\n- added new delegate `flowstream.onregister = function(component) {}`\n- added new delegate `flowstream.onunregister = function(component) {}`\n- added `uistream.load(components, design, [callback])` method\n- added `uistream.unload(components, design, [callback])` method\n- added new delegate `uistream.onreconfigure = function(instance) {}`\n- added new delegate `uistream.onconnect = function(instance) {}`\n- added new delegate `uistream.ondisconnect = function(instance) {}`\n- added new delegate `uistream.onregister = function(component) {}`\n- added new delegate `uistream.onunregister = function(component) {}`\n- fixed `Mail.attachmentfs()`\n- fixed dynamic routing\n- fixed security issue when parsing query arguments (reported by <https://github.com/fl4x>)\n- extended `schema.addTask()` by adding a new argument `callback`\n- added new method `flowstream.newmessage(data)`\n- added new method `flowstream_instance.newmessage(data)`\n- added `String.toJSONSchema(name, url)`\n- added `bundles.debug` enables watcher for `.src` directory only", "========================\n0.0.41\n========================", "- added TypeScript support\n- added support for static files in threads\n- fixed logging in threads by Tomas Novak\n- added `insecure` option to the `REQUEST()` method\n- added `builder.insecure()` method to the `RESTBuilder` instance\n- added `profile` type to the LDAP options\n- extended `base64` by adding support for `content-type;base64,data` format\n- updated `schema.define(key, type, required, [default_error_message])`\n- fixed `String.encrypt_uid()`\n- fixed `$.keys` in schemas with multiple operations\n- fixed wildcard routing combinated with dynamic arguments", "========================\n0.0.40\n========================", "- added `U.reader().list()` method\n- added `Array.findValue()`\n- added async/await mechanism to TextDB\n- added async/await mechanism to RESTBuilder\n- threads supports views\n- improved error handling in `TotalAPI()`\n- improved `Database.scalar()` by adding new argument\n- improved `QueryBuilder.in()` and `QueryBuilder.notin()`\n- fixed UTF8 chars in multi-part parser\n- fixed `NOSQL().autofill()`\n- fixed converting date via `Date.setTimeZone()`\n- fixed XML comments in `String.parseXML()`\n- fixed `Name` type in `Schemas`\n- fixed sorting in `U.reader()`", "========================\n0.0.39\n========================", "- added a new alias `request.proxy()` to `response.proxy()`\n- added `LDAP(opt, callback)` method for obtaining of users, groups or user profile (experimental)\n- added `U.normalize(path)` that normalizes path by adding `/` to begin and end of the phrase\n- added `U.link(path1, path2, pathN)` for creating of links\n- added `PATH.join()` alias to `Path.join()`\n- added `DEF.blacklist` object that performs IP blacklist\n- updated `filestorage.save()` by adding support for importing files from URL address\n- updated built-in session `AUTH()` mechanism by adding `options.strict {Boolean}` option\n- updated `$.extend([data], [callback])` method in SchemaOptions by adding `callback` argument that enables async processing\n- removed `allow_debug` option\n- fixed `abort` event for incoming `request`\n- fixed `controller.json()` method\n- fixed `array.quicksort()` method\n- fixed `controller.invalid()`, added missing second argument called `error` (optional)\n- fixed error handling in `TotalAPI`\n- fixed cookies transfering while redirecting in the `REQUEST()` method (can be disable via `opt.nocookies = true`)\n- fixed `language` in `WebSocketClient`\n- fixed merging files with the `auto` value defined in `versions`\n- fixed encoding in `content-disposition` header\n- fixed `UNAUTHORIZED()`\n- fixed `after` argument in the `PROXY()` and `res.proxy()` methods\n- improved error handling in WebSocket\n- improved HTTP caching in merged files\n- improved unit-testing\n- improved timeouts in the API endpoints", "========================\n0.0.38\n========================", "- added `PAUSE(is_paused)` method that can pause loading of all Total.js dependencies\n- added dynamic delegates for receiving of messages in FlowStream in the form `instance.mesage_<INPUT_NAME>`\n- added `response.proxy(target, [copypath], [after], [timeout])`\n- improved some parts of code\n- improved `MIDDLEWARE(name, fn, [assign], [first])` method\n- fixed measuring dimension for `.gif` images\n- fixed `BACKUP()` method (a problem with sockets)\n- fixed potential remote code execution in `U.set()` founded by [Snyk](https://snyk.io/vuln)\n- fixed routing with camel-Case URL addresses\n- fixed sending of messages via inline registered components in FlowStream\n- fixed a problem with FileStorage and opened file descriptors", "========================\n0.0.37\n========================", "- added CSRF\n\t- `CONF.secret_csrf`\n\t- `CONF.default_csrf_maxage`\n\t- `DEF.onCSRFcreate(req)`\n\t- `DEF.onCSRFcheck(req)`\n\t- `req.csrf()` generates a token\n\t- `controller.csrf()` generates a token\n\t- `@{csrf}` generates a token in View engine\n\t- `schema.csrf()` enables csrf for schemas and their routes\n\t- new `csrf` flag in `ROUTE()` method\n\t- `csrf` verification via `x-csrf-token` header or via URL argument `?csrf=TOKEN`\n\t- `RESTBuilder.csrf(token)`\n- added `HTMLMAIL(address, subject, body, [language], [callback])` for sending of raw HTML mail messages\n- added `NPMINSTALL(name, callback)` for installing of 3rd party NPM dependencies\n- added `FILESTORAGE().image()` method for reading of images\n- `CONF.default_errorbuilder_errors` for handling of all HTTP errors via ErrorBuilder\n- decreased `default_interval_websocket_ping` to `1` minute (from `3`)\n- improved image cache in `FILESTORAGE()`\n- fixed `message` with `closing bytes` in WebSocket and `WEBSOCKETCLIENT()`\n- fixed `@{resource()}` method in View engine\n- fixed read stream in `FILESTORAGE()`", "========================\n0.0.36\n========================", "- improved HTTP cache\n- fixed parsing of schema keys in `PATCH` method\n- fixed predefined session functionality (a problem with cache)\n- fixed `API` routes with empty model", "========================\n0.0.35\n========================", "- extended `EXEC()` by adding support for `Tasks` and `Operations`\n- fixed `DELETE` method for the schemas, now it works same like `PATCH` method\n- fixed `FlowStream.use()` method\n- fixed pausing of outputs/inputs in `FlowStream`\n- fixed inputs in `FlowStream`\n- fixed command injection in `Image.pipe()` and `Image.stream()`\n- fixed parsing of uploaded files (sometimes was the writeable stream unclosed)\n- fixed execution of system routes", "========================\n0.0.31\n========================", "- added `CONF.default_errorbuilder_forxhr` key (default: `true`)\n- errors in requests with `xhr` are serialized via ErrorBuilder\n- fixed reconnecting in `WEBSOCKETCLIENT()`\n- fixed `$.success()` and `$.done()` used in chaining" ]
[ 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 5563], "buggy_code_start_loc": [5, 5206], "filenames": ["changelog.txt", "utils.js"], "fixing_code_end_loc": [10, 5418], "fixing_code_start_loc": [6, 5205], "message": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total4:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "47233194-DF6F-400D-A2BB-E5B07141E828", "versionEndExcluding": "0.0.43", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions."}, {"lang": "es", "value": "El paquete total4 versiones anteriores a 0.0.43, son vulnerables a una ejecuci\u00f3n de c\u00f3digo arbitrario por medio de las funciones U.set() y U.get()"}], "evaluatorComment": null, "id": "CVE-2021-23390", "lastModified": "2021-07-14T17:38:45.477", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-07-12T16:15:09.030", "references": [{"source": "report@snyk.io", "tags": ["Broken Link"], "url": "https://github.com/totaljs/framework4/blob/master/utils.js%23L5430-L5455"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTAL4-1130527"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, "type": "CWE-94"}
39
Determine whether the {function_name} code is vulnerable or not.
[ "========================\n0.0.43\n========================", "- improved `flowinstance.newmessage(data)` method", "- removed method `U.set()`\n- removed method `U.get()`\n- removed method `U.sync()` and `global.sync()`\n- removed method `U.sync2()` and `global.sync2()`", "\n========================\n0.0.42\n========================", "- added support for JSON schemas\n- added Total Messaging Service\n- added `jsonschemas` directory\n- added `schema.jsonschema(name)` method\n- added `JSONSCHEMA()` method\n- added `NEWJSONSCHEMA()` method\n- added `NEWPUBLISH()` method\n- added `NEWSUBSCRIBE()` method\n- added `PUBLISH()` method\n- added `SUBSCRIBE()` method\n- added `UNSUBSCRIBE()` method\n- added `watcher` event for the main process in `debug` or `release` mode with the watcher\n- added HTML escaping for meta tags\n- added `WebSocketClient.destroy()` method\n- added new command `refresh_cmd`\n- added `allow_totalapilogger {Boolean}` option to the configuration\n- added `allow_totalapi {Boolean}` option to the configuration\n- added `allow_tms {Boolean}` option to the configuration\n- added `secret_tms {String}` option to the configuration\n- added `schema.jsonschema_define()` method\n- added `flowstream.load(components, design, [callback])` method\n- added `flowstream.unload(components, design, [callback])` method\n- added new delegate `flowstream.onreconfigure = function(instance) {}`\n- added new delegate `flowstream.onconnect = function(instance) {}`\n- added new delegate `flowstream.ondisconnect = function(instance) {}`\n- added new delegate `flowstream.onregister = function(component) {}`\n- added new delegate `flowstream.onunregister = function(component) {}`\n- added `uistream.load(components, design, [callback])` method\n- added `uistream.unload(components, design, [callback])` method\n- added new delegate `uistream.onreconfigure = function(instance) {}`\n- added new delegate `uistream.onconnect = function(instance) {}`\n- added new delegate `uistream.ondisconnect = function(instance) {}`\n- added new delegate `uistream.onregister = function(component) {}`\n- added new delegate `uistream.onunregister = function(component) {}`\n- fixed `Mail.attachmentfs()`\n- fixed dynamic routing\n- fixed security issue when parsing query arguments (reported by <https://github.com/fl4x>)\n- extended `schema.addTask()` by adding a new argument `callback`\n- added new method `flowstream.newmessage(data)`\n- added new method `flowstream_instance.newmessage(data)`\n- added `String.toJSONSchema(name, url)`\n- added `bundles.debug` enables watcher for `.src` directory only", "========================\n0.0.41\n========================", "- added TypeScript support\n- added support for static files in threads\n- fixed logging in threads by Tomas Novak\n- added `insecure` option to the `REQUEST()` method\n- added `builder.insecure()` method to the `RESTBuilder` instance\n- added `profile` type to the LDAP options\n- extended `base64` by adding support for `content-type;base64,data` format\n- updated `schema.define(key, type, required, [default_error_message])`\n- fixed `String.encrypt_uid()`\n- fixed `$.keys` in schemas with multiple operations\n- fixed wildcard routing combinated with dynamic arguments", "========================\n0.0.40\n========================", "- added `U.reader().list()` method\n- added `Array.findValue()`\n- added async/await mechanism to TextDB\n- added async/await mechanism to RESTBuilder\n- threads supports views\n- improved error handling in `TotalAPI()`\n- improved `Database.scalar()` by adding new argument\n- improved `QueryBuilder.in()` and `QueryBuilder.notin()`\n- fixed UTF8 chars in multi-part parser\n- fixed `NOSQL().autofill()`\n- fixed converting date via `Date.setTimeZone()`\n- fixed XML comments in `String.parseXML()`\n- fixed `Name` type in `Schemas`\n- fixed sorting in `U.reader()`", "========================\n0.0.39\n========================", "- added a new alias `request.proxy()` to `response.proxy()`\n- added `LDAP(opt, callback)` method for obtaining of users, groups or user profile (experimental)\n- added `U.normalize(path)` that normalizes path by adding `/` to begin and end of the phrase\n- added `U.link(path1, path2, pathN)` for creating of links\n- added `PATH.join()` alias to `Path.join()`\n- added `DEF.blacklist` object that performs IP blacklist\n- updated `filestorage.save()` by adding support for importing files from URL address\n- updated built-in session `AUTH()` mechanism by adding `options.strict {Boolean}` option\n- updated `$.extend([data], [callback])` method in SchemaOptions by adding `callback` argument that enables async processing\n- removed `allow_debug` option\n- fixed `abort` event for incoming `request`\n- fixed `controller.json()` method\n- fixed `array.quicksort()` method\n- fixed `controller.invalid()`, added missing second argument called `error` (optional)\n- fixed error handling in `TotalAPI`\n- fixed cookies transfering while redirecting in the `REQUEST()` method (can be disable via `opt.nocookies = true`)\n- fixed `language` in `WebSocketClient`\n- fixed merging files with the `auto` value defined in `versions`\n- fixed encoding in `content-disposition` header\n- fixed `UNAUTHORIZED()`\n- fixed `after` argument in the `PROXY()` and `res.proxy()` methods\n- improved error handling in WebSocket\n- improved HTTP caching in merged files\n- improved unit-testing\n- improved timeouts in the API endpoints", "========================\n0.0.38\n========================", "- added `PAUSE(is_paused)` method that can pause loading of all Total.js dependencies\n- added dynamic delegates for receiving of messages in FlowStream in the form `instance.mesage_<INPUT_NAME>`\n- added `response.proxy(target, [copypath], [after], [timeout])`\n- improved some parts of code\n- improved `MIDDLEWARE(name, fn, [assign], [first])` method\n- fixed measuring dimension for `.gif` images\n- fixed `BACKUP()` method (a problem with sockets)\n- fixed potential remote code execution in `U.set()` founded by [Snyk](https://snyk.io/vuln)\n- fixed routing with camel-Case URL addresses\n- fixed sending of messages via inline registered components in FlowStream\n- fixed a problem with FileStorage and opened file descriptors", "========================\n0.0.37\n========================", "- added CSRF\n\t- `CONF.secret_csrf`\n\t- `CONF.default_csrf_maxage`\n\t- `DEF.onCSRFcreate(req)`\n\t- `DEF.onCSRFcheck(req)`\n\t- `req.csrf()` generates a token\n\t- `controller.csrf()` generates a token\n\t- `@{csrf}` generates a token in View engine\n\t- `schema.csrf()` enables csrf for schemas and their routes\n\t- new `csrf` flag in `ROUTE()` method\n\t- `csrf` verification via `x-csrf-token` header or via URL argument `?csrf=TOKEN`\n\t- `RESTBuilder.csrf(token)`\n- added `HTMLMAIL(address, subject, body, [language], [callback])` for sending of raw HTML mail messages\n- added `NPMINSTALL(name, callback)` for installing of 3rd party NPM dependencies\n- added `FILESTORAGE().image()` method for reading of images\n- `CONF.default_errorbuilder_errors` for handling of all HTTP errors via ErrorBuilder\n- decreased `default_interval_websocket_ping` to `1` minute (from `3`)\n- improved image cache in `FILESTORAGE()`\n- fixed `message` with `closing bytes` in WebSocket and `WEBSOCKETCLIENT()`\n- fixed `@{resource()}` method in View engine\n- fixed read stream in `FILESTORAGE()`", "========================\n0.0.36\n========================", "- improved HTTP cache\n- fixed parsing of schema keys in `PATCH` method\n- fixed predefined session functionality (a problem with cache)\n- fixed `API` routes with empty model", "========================\n0.0.35\n========================", "- extended `EXEC()` by adding support for `Tasks` and `Operations`\n- fixed `DELETE` method for the schemas, now it works same like `PATCH` method\n- fixed `FlowStream.use()` method\n- fixed pausing of outputs/inputs in `FlowStream`\n- fixed inputs in `FlowStream`\n- fixed command injection in `Image.pipe()` and `Image.stream()`\n- fixed parsing of uploaded files (sometimes was the writeable stream unclosed)\n- fixed execution of system routes", "========================\n0.0.31\n========================", "- added `CONF.default_errorbuilder_forxhr` key (default: `true`)\n- errors in requests with `xhr` are serialized via ErrorBuilder\n- fixed reconnecting in `WEBSOCKETCLIENT()`\n- fixed `$.success()` and `$.done()` used in chaining" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 5563], "buggy_code_start_loc": [5, 5206], "filenames": ["changelog.txt", "utils.js"], "fixing_code_end_loc": [10, 5418], "fixing_code_start_loc": [6, 5205], "message": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total4:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "47233194-DF6F-400D-A2BB-E5B07141E828", "versionEndExcluding": "0.0.43", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions."}, {"lang": "es", "value": "El paquete total4 versiones anteriores a 0.0.43, son vulnerables a una ejecuci\u00f3n de c\u00f3digo arbitrario por medio de las funciones U.set() y U.get()"}], "evaluatorComment": null, "id": "CVE-2021-23390", "lastModified": "2021-07-14T17:38:45.477", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-07-12T16:15:09.030", "references": [{"source": "report@snyk.io", "tags": ["Broken Link"], "url": "https://github.com/totaljs/framework4/blob/master/utils.js%23L5430-L5455"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTAL4-1130527"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, "type": "CWE-94"}
39
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict';", "const Dns = require('dns');\nconst Url = require('url');\nconst Http = require('http');\nconst Https = require('https');\nconst Path = require('path');\nconst Fs = require('fs');\nconst Crypto = require('crypto');\nconst Zlib = require('zlib');\nconst Tls = require('tls');\nconst Net = require('net');\nconst KeepAlive = new Http.Agent({ keepAlive: true, timeout: 60000 });\nconst KeepAliveHttps = new Https.Agent({ keepAlive: true, timeout: 60000 });\nconst SKIPBODYENCRYPTOR = { ':': 1, '\"': 1, '[': 1, ']': 1, '\\'': 1, '_': 1, '{': 1, '}': 1, '&': 1, '=': 1, '+': 1, '-': 1, '\\\\': 1, '/': 1, ',': 1 };\nconst REG_EMPTYBUFFER = /\\0|%00|\\\\u0000/g;\nconst REG_EMPTYBUFFER_TEST = /\\0|%00|\\\\u0000/;", "const COMPRESS = { gzip: 1, deflate: 1 };\nconst CONCAT = [null, null];\nconst SKIPPORTS = { '80': 1, '443': 1 };", "const COMPARER = function(a, b) {\n\tif (!a && b)\n\t\treturn -1;\n\tif (a && !b)\n\t\treturn 1;\n\tif (a === b)\n\t\treturn 0;\n\treturn global.Intl.Collator().compare(a, b);\n};", "const COMPARER_DESC = function(a, b) {", "\tif (!a && b)\n\t\treturn 1;", "\tif (a && !b)\n\t\treturn -1;", "\tif (a === b)\n\t\treturn 0;", "\tvar val = global.Intl.Collator().compare(a, b);\n\treturn val ? val * -1 : 0;\n};", "if (!global.framework_utils)\n\tglobal.framework_utils = exports;", "const Internal = require('./internal');\nvar regexpSTATIC = /\\.\\w{2,8}($|\\?)+/;\nconst regexpTRIM = /^[\\s]+|[\\s]+$/g;\nconst regexpDATE = /(\\d{1,2}\\.\\d{1,2}\\.\\d{4})|(\\d{4}-\\d{1,2}-\\d{1,2})|(\\d{1,2}:\\d{1,2}(:\\d{1,2})?)/g;\nconst regexpDATEFORMAT = /YYYY|yyyy|YY|yy|MMMM|MMM|MM|M|dddd|DDDD|DDD|ddd|DD|dd|D|d|HH|H|hh|h|mm|m|ss|s|a|ww|w/g;\nconst regexpSTRINGFORMAT = /\\{\\d+\\}/g;\nconst regexpPATH = /\\\\/g;\nconst regexpTags = /<\\/?[^>]+(>|$)/g;\nconst regexpDiacritics = /[^\\u0000-\\u007e]/g;\nconst regexpUA = /[a-z]+/gi;\nconst regexpXML = /\\w+=\".*?\"/g;\nconst regexpDECODE = /&#?[a-z0-9]+;/g;\nconst regexpARG = /\\{{1,2}[a-z0-9_.-\\s]+\\}{1,2}/gi;\nconst regexpINTEGER = /(^-|\\s-)?[0-9]+/g;\nconst regexpFLOAT = /(^-|\\s-)?[0-9.,]+/g;\nconst regexpSEARCH = /[^a-zA-ZÑ-žÁ-Ž\\d\\s:]/g;\nconst regexpTERMINAL = /[\\w\\S]+/g;\nconst regexpCONFIGURE = /\\[\\w+\\]/g;\nconst regexpY = /y/g;\nconst regexpN = /\\n/g;\nconst regexpCHARS = /\\W|_/g;\nconst regexpCHINA = /[\\u3400-\\u9FBF]/;\nconst regexpLINES = /\\n|\\r|\\r\\n/;\nconst regexpBASE64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;\nconst regexpBASE64_2 = /^|,([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;\nconst ENCODING = 'utf8';\nconst NEWLINE = '\\r\\n';\nconst isWindows = require('os').platform().substring(0, 3).toLowerCase() === 'win';\nconst DIACRITICSMAP = {};\nconst ALPHA_INDEX = { '&lt': '<', '&gt': '>', '&quot': '\"', '&apos': '\\'', '&amp': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"', '&apos;': '\\'', '&amp;': '&' };\nconst STREAMPIPE = { end: false };\nconst CT = 'Content-Type';\nconst CRC32TABLE = '00000000,77073096,EE0E612C,990951BA,076DC419,706AF48F,E963A535,9E6495A3,0EDB8832,79DCB8A4,E0D5E91E,97D2D988,09B64C2B,7EB17CBD,E7B82D07,90BF1D91,1DB71064,6AB020F2,F3B97148,84BE41DE,1ADAD47D,6DDDE4EB,F4D4B551,83D385C7,136C9856,646BA8C0,FD62F97A,8A65C9EC,14015C4F,63066CD9,FA0F3D63,8D080DF5,3B6E20C8,4C69105E,D56041E4,A2677172,3C03E4D1,4B04D447,D20D85FD,A50AB56B,35B5A8FA,42B2986C,DBBBC9D6,ACBCF940,32D86CE3,45DF5C75,DCD60DCF,ABD13D59,26D930AC,51DE003A,C8D75180,BFD06116,21B4F4B5,56B3C423,CFBA9599,B8BDA50F,2802B89E,5F058808,C60CD9B2,B10BE924,2F6F7C87,58684C11,C1611DAB,B6662D3D,76DC4190,01DB7106,98D220BC,EFD5102A,71B18589,06B6B51F,9FBFE4A5,E8B8D433,7807C9A2,0F00F934,9609A88E,E10E9818,7F6A0DBB,086D3D2D,91646C97,E6635C01,6B6B51F4,1C6C6162,856530D8,F262004E,6C0695ED,1B01A57B,8208F4C1,F50FC457,65B0D9C6,12B7E950,8BBEB8EA,FCB9887C,62DD1DDF,15DA2D49,8CD37CF3,FBD44C65,4DB26158,3AB551CE,A3BC0074,D4BB30E2,4ADFA541,3DD895D7,A4D1C46D,D3D6F4FB,4369E96A,346ED9FC,AD678846,DA60B8D0,44042D73,33031DE5,AA0A4C5F,DD0D7CC9,5005713C,270241AA,BE0B1010,C90C2086,5768B525,206F85B3,B966D409,CE61E49F,5EDEF90E,29D9C998,B0D09822,C7D7A8B4,59B33D17,2EB40D81,B7BD5C3B,C0BA6CAD,EDB88320,9ABFB3B6,03B6E20C,74B1D29A,EAD54739,9DD277AF,04DB2615,73DC1683,E3630B12,94643B84,0D6D6A3E,7A6A5AA8,E40ECF0B,9309FF9D,0A00AE27,7D079EB1,F00F9344,8708A3D2,1E01F268,6906C2FE,F762575D,806567CB,196C3671,6E6B06E7,FED41B76,89D32BE0,10DA7A5A,67DD4ACC,F9B9DF6F,8EBEEFF9,17B7BE43,60B08ED5,D6D6A3E8,A1D1937E,38D8C2C4,4FDFF252,D1BB67F1,A6BC5767,3FB506DD,48B2364B,D80D2BDA,AF0A1B4C,36034AF6,41047A60,DF60EFC3,A867DF55,316E8EEF,4669BE79,CB61B38C,BC66831A,256FD2A0,5268E236,CC0C7795,BB0B4703,220216B9,5505262F,C5BA3BBE,B2BD0B28,2BB45A92,5CB36A04,C2D7FFA7,B5D0CF31,2CD99E8B,5BDEAE1D,9B64C2B0,EC63F226,756AA39C,026D930A,9C0906A9,EB0E363F,72076785,05005713,95BF4A82,E2B87A14,7BB12BAE,0CB61B38,92D28E9B,E5D5BE0D,7CDCEFB7,0BDBDF21,86D3D2D4,F1D4E242,68DDB3F8,1FDA836E,81BE16CD,F6B9265B,6FB077E1,18B74777,88085AE6,FF0F6A70,66063BCA,11010B5C,8F659EFF,F862AE69,616BFFD3,166CCF45,A00AE278,D70DD2EE,4E048354,3903B3C2,A7672661,D06016F7,4969474D,3E6E77DB,AED16A4A,D9D65ADC,40DF0B66,37D83BF0,A9BCAE53,DEBB9EC5,47B2CF7F,30B5FFE9,BDBDF21C,CABAC28A,53B39330,24B4A3A6,BAD03605,CDD70693,54DE5729,23D967BF,B3667A2E,C4614AB8,5D681B02,2A6F2B94,B40BBE37,C30C8EA1,5A05DF1B,2D02EF8D'.split(',').map(s => parseInt(s, 16));\nconst REGISARR = /\\[\\d+\\]|\\[\\]$/;\nconst REGREPLACEARR = /\\[\\]/g;\nconst PROXYBLACKLIST = { 'localhost': 1, '127.0.0.1': 1, '0.0.0.0': 1 };\nconst PROXYOPTIONS = { headers: {}, method: 'CONNECT', agent: false };\nconst PROXYTLS = { headers: {}};\nconst PROXYOPTIONSHTTP = {};\nconst REG_ROOT = /@\\{#\\}(\\/)?/g;\nconst REG_NOREMAP = /@\\{noremap\\}(\\n)?/g;\nconst REG_REMAP = /href=\".*?\"|src=\".*?\"/gi;\nconst REG_AJAX = /('|\")+(!)?(GET|POST|PUT|DELETE|PATCH)\\s(\\(.*?\\)\\s)?\\//g;\nconst REG_URLEXT = /(https|http|wss|ws|file):\\/\\/|\\/\\/[a-z0-9]|[a-z]:/i;\nconst REG_TEXTAPPLICATION = /text|application/i;\nconst REG_TIME = /am|pm/i;\nconst REG_XMLKEY = /\\[|\\]|:|\\.|_/g;\nconst HEADEREND = Buffer.from('\\r\\n\\r\\n', 'ascii');\nconst HEADERCHECK = 'Content-Disposition: form-data;'.toLowerCase();", "exports.MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nexports.DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];", "var DIACRITICS=[{b:' ',c:'\\u00a0'},{b:'0',c:'\\u07c0'},{b:'A',c:'\\u24b6\\uff21\\u00c0\\u00c1\\u00c2\\u1ea6\\u1ea4\\u1eaa\\u1ea8\\u00c3\\u0100\\u0102\\u1eb0\\u1eae\\u1eb4\\u1eb2\\u0226\\u01e0\\u00c4\\u01de\\u1ea2\\u00c5\\u01fa\\u01cd\\u0200\\u0202\\u1ea0\\u1eac\\u1eb6\\u1e00\\u0104\\u023a\\u2c6f'},{b:'AA',c:'\\ua732'},{b:'AE',c:'\\u00c6\\u01fc\\u01e2'},{b:'AO',c:'\\ua734'},{b:'AU',c:'\\ua736'},{b:'AV',c:'\\ua738\\ua73a'},{b:'AY',c:'\\ua73c'},{b:'B',c:'\\u24b7\\uff22\\u1e02\\u1e04\\u1e06\\u0243\\u0181'},{b:'C',c:'\\u24b8\\uff23\\ua73e\\u1e08\\u0106C\\u0108\\u010a\\u010c\\u00c7\\u0187\\u023b'},{b:'D',c:'\\u24b9\\uff24\\u1e0a\\u010e\\u1e0c\\u1e10\\u1e12\\u1e0e\\u0110\\u018a\\u0189\\u1d05\\ua779'},{b:'Dh',c:'\\u00d0'},{b:'DZ',c:'\\u01f1\\u01c4'},{b:'Dz',c:'\\u01f2\\u01c5'},{b:'E',c:'\\u025b\\u24ba\\uff25\\u00c8\\u00c9\\u00ca\\u1ec0\\u1ebe\\u1ec4\\u1ec2\\u1ebc\\u0112\\u1e14\\u1e16\\u0114\\u0116\\u00cb\\u1eba\\u011a\\u0204\\u0206\\u1eb8\\u1ec6\\u0228\\u1e1c\\u0118\\u1e18\\u1e1a\\u0190\\u018e\\u1d07'},{b:'F',c:'\\ua77c\\u24bb\\uff26\\u1e1e\\u0191\\ua77b'}, {b:'G',c:'\\u24bc\\uff27\\u01f4\\u011c\\u1e20\\u011e\\u0120\\u01e6\\u0122\\u01e4\\u0193\\ua7a0\\ua77d\\ua77e\\u0262'},{b:'H',c:'\\u24bd\\uff28\\u0124\\u1e22\\u1e26\\u021e\\u1e24\\u1e28\\u1e2a\\u0126\\u2c67\\u2c75\\ua78d'},{b:'I',c:'\\u24be\\uff29\\u00cc\\u00cd\\u00ce\\u0128\\u012a\\u012c\\u0130\\u00cf\\u1e2e\\u1ec8\\u01cf\\u0208\\u020a\\u1eca\\u012e\\u1e2c\\u0197'},{b:'J',c:'\\u24bf\\uff2a\\u0134\\u0248\\u0237'},{b:'K',c:'\\u24c0\\uff2b\\u1e30\\u01e8\\u1e32\\u0136\\u1e34\\u0198\\u2c69\\ua740\\ua742\\ua744\\ua7a2'},{b:'L',c:'\\u24c1\\uff2c\\u013f\\u0139\\u013d\\u1e36\\u1e38\\u013b\\u1e3c\\u1e3a\\u0141\\u023d\\u2c62\\u2c60\\ua748\\ua746\\ua780'}, {b:'LJ',c:'\\u01c7'},{b:'Lj',c:'\\u01c8'},{b:'M',c:'\\u24c2\\uff2d\\u1e3e\\u1e40\\u1e42\\u2c6e\\u019c\\u03fb'},{b:'N',c:'\\ua7a4\\u0220\\u24c3\\uff2e\\u01f8\\u0143\\u00d1\\u1e44\\u0147\\u1e46\\u0145\\u1e4a\\u1e48\\u019d\\ua790\\u1d0e'},{b:'NJ',c:'\\u01ca'},{b:'Nj',c:'\\u01cb'},{b:'O',c:'\\u24c4\\uff2f\\u00d2\\u00d3\\u00d4\\u1ed2\\u1ed0\\u1ed6\\u1ed4\\u00d5\\u1e4c\\u022c\\u1e4e\\u014c\\u1e50\\u1e52\\u014e\\u022e\\u0230\\u00d6\\u022a\\u1ece\\u0150\\u01d1\\u020c\\u020e\\u01a0\\u1edc\\u1eda\\u1ee0\\u1ede\\u1ee2\\u1ecc\\u1ed8\\u01ea\\u01ec\\u00d8\\u01fe\\u0186\\u019f\\ua74a\\ua74c'}, {b:'OE',c:'\\u0152'},{b:'OI',c:'\\u01a2'},{b:'OO',c:'\\ua74e'},{b:'OU',c:'\\u0222'},{b:'P',c:'\\u24c5\\uff30\\u1e54\\u1e56\\u01a4\\u2c63\\ua750\\ua752\\ua754'},{b:'Q',c:'\\u24c6\\uff31\\ua756\\ua758\\u024a'},{b:'R',c:'\\u24c7\\uff32\\u0154\\u1e58\\u0158\\u0210\\u0212\\u1e5a\\u1e5c\\u0156\\u1e5e\\u024c\\u2c64\\ua75a\\ua7a6\\ua782'},{b:'S',c:'\\u24c8\\uff33\\u1e9e\\u015a\\u1e64\\u015c\\u1e60\\u0160\\u1e66\\u1e62\\u1e68\\u0218\\u015e\\u2c7e\\ua7a8\\ua784'},{b:'T',c:'\\u24c9\\uff34\\u1e6a\\u0164\\u1e6c\\u021a\\u0162\\u1e70\\u1e6e\\u0166\\u01ac\\u01ae\\u023e\\ua786'}, {b:'Th',c:'\\u00de'},{b:'TZ',c:'\\ua728'},{b:'U',c:'\\u24ca\\uff35\\u00d9\\u00da\\u00db\\u0168\\u1e78\\u016a\\u1e7a\\u016c\\u00dc\\u01db\\u01d7\\u01d5\\u01d9\\u1ee6\\u016e\\u0170\\u01d3\\u0214\\u0216\\u01af\\u1eea\\u1ee8\\u1eee\\u1eec\\u1ef0\\u1ee4\\u1e72\\u0172\\u1e76\\u1e74\\u0244'},{b:'V',c:'\\u24cb\\uff36\\u1e7c\\u1e7e\\u01b2\\ua75e\\u0245'},{b:'VY',c:'\\ua760'},{b:'W',c:'\\u24cc\\uff37\\u1e80\\u1e82\\u0174\\u1e86\\u1e84\\u1e88\\u2c72'},{b:'X',c:'\\u24cd\\uff38\\u1e8a\\u1e8c'},{b:'Y',c:'\\u24ce\\uff39\\u1ef2\\u00dd\\u0176\\u1ef8\\u0232\\u1e8e\\u0178\\u1ef6\\u1ef4\\u01b3\\u024e\\u1efe'}, {b:'Z',c:'\\u24cf\\uff3a\\u0179\\u1e90\\u017b\\u017d\\u1e92\\u1e94\\u01b5\\u0224\\u2c7f\\u2c6b\\ua762'},{b:'a',c:'\\u24d0\\uff41\\u1e9a\\u00e0\\u00e1\\u00e2\\u1ea7\\u1ea5\\u1eab\\u1ea9\\u00e3\\u0101\\u0103\\u1eb1\\u1eaf\\u1eb5\\u1eb3\\u0227\\u01e1\\u00e4\\u01df\\u1ea3\\u00e5\\u01fb\\u01ce\\u0201\\u0203\\u1ea1\\u1ead\\u1eb7\\u1e01\\u0105\\u2c65\\u0250\\u0251'},{b:'aa',c:'\\ua733'},{b:'ae',c:'\\u00e6\\u01fd\\u01e3'},{b:'ao',c:'\\ua735'},{b:'au',c:'\\ua737'},{b:'av',c:'\\ua739\\ua73b'},{b:'ay',c:'\\ua73d'}, {b:'b',c:'\\u24d1\\uff42\\u1e03\\u1e05\\u1e07\\u0180\\u0183\\u0253\\u0182'},{b:'c',c:'\\uff43\\u24d2\\u0107\\u0109\\u010b\\u010d\\u00e7\\u1e09\\u0188\\u023c\\ua73f\\u2184'},{b:'d',c:'\\u24d3\\uff44\\u1e0b\\u010f\\u1e0d\\u1e11\\u1e13\\u1e0f\\u0111\\u018c\\u0256\\u0257\\u018b\\u13e7\\u0501\\ua7aa'},{b:'dh',c:'\\u00f0'},{b:'dz',c:'\\u01f3\\u01c6'},{b:'e',c:'\\u24d4\\uff45\\u00e8\\u00e9\\u00ea\\u1ec1\\u1ebf\\u1ec5\\u1ec3\\u1ebd\\u0113\\u1e15\\u1e17\\u0115\\u0117\\u00eb\\u1ebb\\u011b\\u0205\\u0207\\u1eb9\\u1ec7\\u0229\\u1e1d\\u0119\\u1e19\\u1e1b\\u0247\\u01dd'}, {b:'f',c:'\\u24d5\\uff46\\u1e1f\\u0192'},{b:'ff',c:'\\ufb00'},{b:'fi',c:'\\ufb01'},{b:'fl',c:'\\ufb02'},{b:'ffi',c:'\\ufb03'},{b:'ffl',c:'\\ufb04'},{b:'g',c:'\\u24d6\\uff47\\u01f5\\u011d\\u1e21\\u011f\\u0121\\u01e7\\u0123\\u01e5\\u0260\\ua7a1\\ua77f\\u1d79'},{b:'h',c:'\\u24d7\\uff48\\u0125\\u1e23\\u1e27\\u021f\\u1e25\\u1e29\\u1e2b\\u1e96\\u0127\\u2c68\\u2c76\\u0265'},{b:'hv',c:'\\u0195'},{b:'i',c:'\\u24d8\\uff49\\u00ec\\u00ed\\u00ee\\u0129\\u012b\\u012d\\u00ef\\u1e2f\\u1ec9\\u01d0\\u0209\\u020b\\u1ecb\\u012f\\u1e2d\\u0268\\u0131'}, {b:'j',c:'\\u24d9\\uff4a\\u0135\\u01f0\\u0249'},{b:'k',c:'\\u24da\\uff4b\\u1e31\\u01e9\\u1e33\\u0137\\u1e35\\u0199\\u2c6a\\ua741\\ua743\\ua745\\ua7a3'},{b:'l',c:'\\u24db\\uff4c\\u0140\\u013a\\u013e\\u1e37\\u1e39\\u013c\\u1e3d\\u1e3b\\u017f\\u0142\\u019a\\u026b\\u2c61\\ua749\\ua781\\ua747\\u026d'},{b:'lj',c:'\\u01c9'},{b:'m',c:'\\u24dc\\uff4d\\u1e3f\\u1e41\\u1e43\\u0271\\u026f'},{b:'n',c:'\\u24dd\\uff4e\\u01f9\\u0144\\u00f1\\u1e45\\u0148\\u1e47\\u0146\\u1e4b\\u1e49\\u019e\\u0272\\u0149\\ua791\\ua7a5\\u043b\\u0509'},{b:'nj', c:'\\u01cc'},{b:'o',c:'\\u24de\\uff4f\\u00f2\\u00f3\\u00f4\\u1ed3\\u1ed1\\u1ed7\\u1ed5\\u00f5\\u1e4d\\u022d\\u1e4f\\u014d\\u1e51\\u1e53\\u014f\\u022f\\u0231\\u00f6\\u022b\\u1ecf\\u0151\\u01d2\\u020d\\u020f\\u01a1\\u1edd\\u1edb\\u1ee1\\u1edf\\u1ee3\\u1ecd\\u1ed9\\u01eb\\u01ed\\u00f8\\u01ff\\ua74b\\ua74d\\u0275\\u0254\\u1d11'},{b:'oe',c:'\\u0153'},{b:'oi',c:'\\u01a3'},{b:'oo',c:'\\ua74f'},{b:'ou',c:'\\u0223'},{b:'p',c:'\\u24df\\uff50\\u1e55\\u1e57\\u01a5\\u1d7d\\ua751\\ua753\\ua755\\u03c1'},{b:'q',c:'\\u24e0\\uff51\\u024b\\ua757\\ua759'}, {b:'r',c:'\\u24e1\\uff52\\u0155\\u1e59\\u0159\\u0211\\u0213\\u1e5b\\u1e5d\\u0157\\u1e5f\\u024d\\u027d\\ua75b\\ua7a7\\ua783'},{b:'s',c:'\\u24e2\\uff53\\u015b\\u1e65\\u015d\\u1e61\\u0161\\u1e67\\u1e63\\u1e69\\u0219\\u015f\\u023f\\ua7a9\\ua785\\u1e9b\\u0282'},{b:'ss',c:'\\u00df'},{b:'t',c:'\\u24e3\\uff54\\u1e6b\\u1e97\\u0165\\u1e6d\\u021b\\u0163\\u1e71\\u1e6f\\u0167\\u01ad\\u0288\\u2c66\\ua787'},{b:'th',c:'\\u00fe'},{b:'tz',c:'\\ua729'},{b:'u',c:'\\u24e4\\uff55\\u00f9\\u00fa\\u00fb\\u0169\\u1e79\\u016b\\u1e7b\\u016d\\u00fc\\u01dc\\u01d8\\u01d6\\u01da\\u1ee7\\u016f\\u0171\\u01d4\\u0215\\u0217\\u01b0\\u1eeb\\u1ee9\\u1eef\\u1eed\\u1ef1\\u1ee5\\u1e73\\u0173\\u1e77\\u1e75\\u0289'}, {b:'v',c:'\\u24e5\\uff56\\u1e7d\\u1e7f\\u028b\\ua75f\\u028c'},{b:'vy',c:'\\ua761'},{b:'w',c:'\\u24e6\\uff57\\u1e81\\u1e83\\u0175\\u1e87\\u1e85\\u1e98\\u1e89\\u2c73'},{b:'x',c:'\\u24e7\\uff58\\u1e8b\\u1e8d'},{b:'y',c:'\\u24e8\\uff59\\u1ef3\\u00fd\\u0177\\u1ef9\\u0233\\u1e8f\\u00ff\\u1ef7\\u1e99\\u1ef5\\u01b4\\u024f\\u1eff'},{b:'z',c:'\\u24e9\\uff5a\\u017a\\u1e91\\u017c\\u017e\\u1e93\\u1e95\\u01b6\\u0225\\u0240\\u2c6c\\ua763'}];\nvar UPLOADINDEXER = 1;", "for (var i=0; i <DIACRITICS.length; i+=1)\n\tfor (var chars=DIACRITICS[i].c,j=0;j<chars.length;j+=1)\n\t\tDIACRITICSMAP[chars[j]]=DIACRITICS[i].b;", "const DP = Date.prototype;\nconst SP = String.prototype;\nconst NP = Number.prototype;", "DIACRITICS = null;", "var CONTENTTYPES = {\n\taac: 'audio/aac',\n\tai: 'application/postscript',\n\tappcache: 'text/cache-manifest',\n\tavi: 'video/avi',\n\tbin: 'application/octet-stream',\n\tbmp: 'image/bmp',\n\tcoffee: 'text/coffeescript',\n\tcss: 'text/css',\n\tcsv: 'text/csv',\n\tdoc: 'application/msword',\n\tdocx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n\tdtd: 'application/xml-dtd',\n\teps: 'application/postscript',\n\texe: 'application/octet-stream',\n\tflac: 'audio/x-flac',\n\tgeojson: 'application/json',\n\tgif: 'image/gif',\n\tgzip: 'application/x-gzip',\n\theic: 'image/heic',\n\theif: 'image/heif',\n\thtm: 'text/html',\n\thtml: 'text/html',\n\tico: 'image/x-icon',\n\tics: 'text/calendar',\n\tifb: 'text/calendar',\n\tjpe: 'image/jpeg',\n\tjpeg: 'image/jpeg',\n\tjpg: 'image/jpeg',\n\tjs: 'text/javascript',\n\tjson: 'application/json',\n\tjsx: 'text/jsx',\n\tless: 'text/css',\n\tm4a: 'audio/mp4a-latm',\n\tm4v: 'video/x-m4v',\n\tmanifest: 'text/cache-manifest',\n\tmd: 'text/x-markdown',\n\tmid: 'audio/midi',\n\tmidi: 'audio/midi',\n\tmjs: 'text/javascript',\n\tmov: 'video/quicktime',\n\tmp3: 'audio/mpeg',\n\tmp4: 'video/mp4',\n\tmpe: 'video/mpeg',\n\tmpeg: 'video/mpeg',\n\tmpg: 'video/mpeg',\n\tmpga: 'audio/mpeg',\n\tmtl: 'text/plain',\n\tmv4: 'video/mv4',\n\tobj: 'text/plain',\n\togg: 'application/ogg',\n\togv: 'video/ogg',\n\tpackage: 'text/plain',\n\tpdf: 'application/pdf',\n\tpng: 'image/png',\n\tppt: 'application/vnd.ms-powerpoint',\n\tpptx: 'application/vnd.ms-powerpoint',\n\tps: 'application/postscript',\n\trar: 'application/x-rar-compressed',\n\trtf: 'text/rtf',\n\tsass: 'text/css',\n\tscss: 'text/css',\n\tsh: 'application/x-sh',\n\tstl: 'application/sla',\n\tsvg: 'image/svg+xml',\n\tswf: 'application/x-shockwave-flash',\n\ttar: 'application/x-tar',\n\ttif: 'image/tiff',\n\ttiff: 'image/tiff',\n\ttxt: 'text/plain',\n\tsql: 'text/plain',\n\twav: 'audio/x-wav',\n\twebm: 'video/webm',\n\twebp: 'image/webp',\n\twoff: 'application/font-woff',\n\twoff2: 'application/font-woff2',\n\txht: 'application/xhtml+xml',\n\txhtml: 'application/xhtml+xml',\n\txls: 'application/vnd.ms-excel',\n\txlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\txml: 'application/xml',\n\txpm: 'image/x-xpixmap',\n\txsl: 'application/xml',\n\txslt: 'application/xslt+xml',\n\tzip: 'application/zip'\n};", "var dnscache = {};\nvar datetimeformat = {};", "global.DIFFARR = exports.diffarr = function(prop, db, form) {", "\tvar an = [];\n\tvar au = [];\n\tvar ar = [];\n\tvar is, oa, ob;", "\tfor (var i = 0; i < db.length; i++) {\n\t\toa = db[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < form.length; j++) {\n\t\t\tob = form[j];\n\t\t\tif (oa[prop] == ob[prop]) {\n\t\t\t\tau.push({ db: oa, form: ob });\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tar.push(oa[prop]);\n\t}", "\tfor (var i = 0; i < form.length; i++) {\n\t\tob = form[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < db.length; j++) {\n\t\t\toa = db[j];\n\t\t\tif (ob[prop] == oa[prop]) {\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tan.push(ob);\n\t}", "\tvar obj = {};\n\tobj.add = an;\n\tobj.upd = au;\n\tobj.rem = ar;\n\treturn obj;\n};", "exports.toURLEncode = function(value) {\n\tvar builder = [];", "\tfor (var key in value) {\n\t\tvar val = value[key];", "\t\tif (val == null || val === '')\n\t\t\tcontinue;", "\t\tvar type = typeof(val);\n\t\tswitch (type) {\n\t\t\tcase 'string':\n\t\t\t\tbuilder.push(key + '=' + encodeURIComponent(val));\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\t\tbuilder.push(key + '=' + encodeURIComponent(val.format('utc')));\n\t\t\t\tbreak;\n\t\t\tcase 'boolean':\n\t\t\tcase 'number':\n\t\t\t\tbuilder.push(key + '=' + val);\n\t\t\t\tbreak;\n\t\t\tcase 'object':\n\t\t\t\tif (val instanceof Array)\n\t\t\t\t\tbuilder.push(key + '=' + encodeURIComponent(val.join(',')));\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn builder.length ? builder.join('&') : '';\n};", "exports.resolve = function(url, callback, param) {", "\tvar uri;", "\ttry {\n\t\turi = Url.parse(url);\n\t} catch (e) {\n\t\tcallback(e);\n\t\treturn;\n\t}", "\tvar cache = dnscache[uri.host];", "\tif (!callback)\n\t\treturn cache;", "\tif (cache) {\n\t\turi.host = cache[0];\n\t\tcallback(null, uri, param, cache);\n\t\treturn;\n\t}", "\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (e)\n\t\t\tsetImmediate(dnsresolve_callback, uri, callback, param);\n\t\telse {\n\t\t\tdnscache[uri.host] = addresses;\n\t\t\turi.host = addresses[0];\n\t\t\tcallback(null, uri, param, addresses);\n\t\t}\n\t});\n};", "function dnsresolve_callback(uri, callback, param) {\n\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (addresses && addresses.length) {\n\t\t\tdnscache[uri.host] = addresses;\n\t\t\turi.host = addresses[0];\n\t\t}\n\t\tcallback(e, uri, param, addresses);\n\t});\n}", "setImmediate(function() {\n\tglobal.F && NEWCOMMAND('clear_dnscache', function() {\n\t\tdnscache = {};\n\t});\n});", "exports.keywords = function(content, forSearch, alternative, max_count, max_length, min_length) {", "\tif (forSearch === undefined)\n\t\tforSearch = true;", "\tmin_length = min_length || 2;\n\tmax_count = max_count || 200;\n\tmax_length = max_length || 20;", "\tvar words = [];", "\tif (content instanceof Array) {\n\t\tfor (var i = 0, length = content.length; i < length; i++) {\n\t\t\tif (!content[i])\n\t\t\t\tcontinue;\n\t\t\tvar tmp = (forSearch ? content[i].toASCII().toLowerCase().replace(regexpY, 'i') : content[i].toLowerCase()).replace(regexpN, ' ').split(' ');\n\t\t\tif (!tmp || !tmp.length)\n\t\t\t\tcontinue;\n\t\t\tfor (var j = 0, jl = tmp.length; j < jl; j++)\n\t\t\t\twords.push(tmp[j]);\n\t\t}\n\t} else\n\t\twords = (forSearch ? content.toASCII().toLowerCase().replace(regexpY, 'i') : content.toLowerCase()).replace(regexpN, ' ').split(' ');", "\tif (!words)\n\t\twords = [];", "\tvar dic = {};\n\tvar counter = 0;", "\tfor (var i = 0, length = words.length; i < length; i++) {", "\t\tvar word = words[i].trim().replace(regexpCHARS, keywordscleaner);", "\t\tif (regexpCHINA.test(word)) {", "\t\t\tvar tmpw = word.split('', max_count);", "\t\t\tfor (var j = 0; j < tmpw.length; j++) {\n\t\t\t\tword = tmpw[j];\n\t\t\t\tif (dic[word])\n\t\t\t\t\tdic[word]++;\n\t\t\t\telse\n\t\t\t\t\tdic[word] = 1;\n\t\t\t\tcounter++;\n\t\t\t}", "\t\t\tif (counter >= max_count)\n\t\t\t\tbreak;", "\t\t\tcontinue;\n\t\t}", "\t\tif (word.length < min_length)\n\t\t\tcontinue;", "\t\tif (counter >= max_count)\n\t\t\tbreak;", "\t\t// Gets 80% length of word\n\t\tif (alternative) {\n\t\t\tvar size = (word.length / 100) * 80;\n\t\t\tif (size > min_length + 1)\n\t\t\t\tword = word.substring(0, size);\n\t\t}", "\t\tif (word.length < min_length || word.length > max_length)\n\t\t\tcontinue;", "\t\tif (dic[word])\n\t\t\tdic[word]++;\n\t\telse\n\t\t\tdic[word] = 1;", "\t\tcounter++;\n\t}", "\tvar keys = Object.keys(dic);", "\tkeys.sort(function(a, b) {\n\t\tvar countA = dic[a];\n\t\tvar countB = dic[b];\n\t\treturn countA > countB ? -1 : countA < countB ? 1 : 0;\n\t});", "\treturn keys;\n};", "function keywordscleaner(c) {\n\treturn c.charCodeAt(0) < 200 ? '' : c;\n}", "function parseProxy(p) {\n\tvar key = 'proxy_' + p;\n\tif (F.temporary.other[key])\n\t\treturn F.temporary.other[key];", "\tif (p.indexOf('://') === -1)\n\t\tp = 'http://' + p;", "\tvar obj = Url.parse(p);", "\tif (obj.auth)\n\t\tobj._auth = 'Basic ' + Buffer.from(obj.auth).toString('base64');", "\tobj.port = +obj.port;", "\tif (p.indexOf('https:') !== -1) {\n\t\tobj.rejectUnauthorized = false;\n\t\tobj.requestCert = true;\n\t}", "\treturn F.temporary.other[key] = obj;\n}", "global.REQUEST = function(opt, callback) {", "\tvar options = { length: 0, timeout: opt.timeout || CONF.default_restbuilder_timeout, encoding: opt.encoding || ENCODING, callback: opt.callback || NOOP, post: true, redirect: 0 };\n\tvar proxy;", "\tif (callback)\n\t\topt.callback = callback;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tif (opt.headers)\n\t\topt.headers = exports.extend({}, opt.headers);\n\telse\n\t\topt.headers = {};", "\tif (!opt.method)\n\t\topt.method = 'GET';", "\toptions.$totalinit = opt;", "\t// opt.encrypt {String}\n\t// opt.limit in kB\n\t// opt.key {Buffer}\n\t// opt.cert {Buffer}\n\t// opt.onprogress(percentage)\n\t// opt.ondata(chunk, percentage)", "\tif (opt.ondata)\n\t\toptions.ondata = opt.ondata;", "\tif (opt.onprogress)\n\t\toptions.onprogress = opt.onprogress;", "\tif (opt.proxy)\n\t\tproxy = parseProxy(opt.proxy);", "\tif (opt.xhr)\n\t\topt.headers['X-Requested-With'] = 'XMLHttpRequest';", "\toptions.response = opt.response ? opt.response : {};\n\toptions.response.body = '';\n\toptions.iserror = false;", "\tif (opt.resolve || opt.dnscache)\n\t\toptions.resolve = true;", "\tif (opt.custom)\n\t\toptions.custom = true;", "\tif (opt.noredirect)\n\t\toptions.noredirect = true;", "\tif (opt.keepalive)\n\t\toptions.keepalive = true;", "\tif (opt.type) {\n\t\tswitch (opt.type) {\n\t\t\tcase 'plain':\n\t\t\t\topt.headers[CT] = 'text/plain';\n\t\t\t\tbreak;\n\t\t\tcase 'html':\n\t\t\t\topt.headers[CT] = 'text/html';\n\t\t\t\tbreak;\n\t\t\tcase 'raw':\n\t\t\t\topt.headers[CT] = 'application/octet-stream';\n\t\t\t\tbreak;\n\t\t\tcase 'json':\n\t\t\t\topt.headers[CT] = 'application/json';\n\t\t\t\tbreak;\n\t\t\tcase 'urlencoded':\n\t\t\t\topt.headers[CT] = 'application/x-www-form-urlencoded';\n\t\t\t\tbreak;\n\t\t\tcase 'xml':\n\t\t\t\topt.headers[CT] = 'text/xml';\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tif (opt.files) {\n\t\toptions.boundary = '----TOTALFILE_' + Math.random().toString(36).substring(3);\n\t\topt.headers[CT] = 'multipart/form-data; boundary=' + options.boundary;\n\t\toptions.files = opt.files;\n\t\toptions.upload = true;", "\t\t// Must be object { key: value }\n\t\tif (opt.body)\n\t\t\toptions.body = opt.body;", "\t} else {\n\t\tif (opt.body) {\n\t\t\tif (!(opt.body instanceof Buffer)) {\n\t\t\t\tif (opt.encrypt) {\n\t\t\t\t\topt.body = exports.encrypt_data(opt.body, opt.encrypt);\n\t\t\t\t\topt.headers['X-Encryption'] = 'a';\n\t\t\t\t}\n\t\t\t\topt.body = Buffer.from(opt.body, ENCODING);\n\t\t\t}\n\t\t\topt.headers['Content-Length'] = opt.body.length;\n\t\t}\n\t\toptions.body = opt.body;\n\t}", "\tif (opt.cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in opt.cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + opt.cookies[m];\n\t\tif (builder)\n\t\t\topt.headers.Cookie = builder;\n\t}", "\tif (opt.query) {\n\t\tif (typeof(opt.query) !== 'string')\n\t\t\topt.query = U.toURLEncode(opt.query);\n\t\tif (opt.url) {\n\t\t\tif (opt.url.lastIndexOf('?') === -1)\n\t\t\t\topt.url += '?' + opt.query;\n\t\t\telse\n\t\t\t\topt.url += '&' + opt.query;\n\t\t} else if (opt.unixsocket.path) {\n\t\t\tif (opt.unixsocket.path.lastIndexOf('?') === -1)\n\t\t\t\topt.unixsocket.path += '?' + opt.query;\n\t\t\telse\n\t\t\t\topt.unixsocket.path += '&' + opt.query;\n\t\t}\n\t}", "\tvar uri = opt.unixsocket ? { socketPath: opt.unixsocket.socket, path: opt.unixsocket.path } : Url.parse(opt.url);", "\tif ((opt.unixsocket && !uri.socketPath) || (!opt.unixsocket && (!uri.hostname || !uri.host))) {\n\t\toptions.response.canceled = true;\n\t\topt.callback && opt.callback('Invalid hostname', options.response);\n\t\treturn;\n\t}", "\turi.method = opt.method;\n\turi.headers = opt.headers;", "\tif (options.insecure) {\n\t\turi.rejectUnauthorized = false;\n\t\turi.requestCert = true;\n\t}", "\toptions.uri = uri;\n\toptions.opt = opt;", "\tif (opt.key)\n\t\turi.key = opt.key;", "\tif (opt.cert)\n\t\turi.cert = opt.cert;", "\tif (opt.dhparam)\n\t\turi.dhparam = opt.dhparam;", "\tif (options.resolve && (opt.unixsocket || (uri.hostname === 'localhost' || uri.hostname.charCodeAt(0) < 64)))\n\t\toptions.resolve = false;", "\tif (!opt.unixsocket && CONF.default_proxy && !proxy && !PROXYBLACKLIST[uri.hostname])\n\t\tproxy = parseProxy(CONF.default_proxy);", "\tif (!opt.unixsocket && proxy && (uri.hostname === 'localhost' || uri.hostname === '127.0.0.1'))\n\t\tproxy = null;", "\toptions.proxy = proxy;", "\tif (proxy && uri.protocol === 'https:') {\n\t\tproxy.tls = true;\n\t\turi.agent = new ProxyAgent(options);\n\t\turi.agent.request = Http.request;\n\t\turi.agent.createSocket = createSecureSocket;\n\t\turi.agent.defaultPort = 443;\n\t}", "\tif (options.keepalive && !options.proxy) {\n\t\tif (uri.protocol === 'https:') {\n\t\t\tif (!uri.port)\n\t\t\t\turi.port = 443;\n\t\t\turi.agent = KeepAliveHttps;\n\t\t} else\n\t\t\turi.agent = KeepAlive;\n\t} else\n\t\turi.agent = null;", "\tif (proxy)\n\t\trequest_call(uri, options);\n\telse if (options.resolve)\n\t\texports.resolve(opt.url, request_resolve, options);\n\telse\n\t\trequest_call(uri, options);\n};", "function request_resolve(err, uri, options, origin) {\n\tif (!err) {\n\t\toptions.uri.host = uri.host;\n\t\toptions.origin = origin;\n\t}\n\trequest_call(options.uri, options);\n}", "function ProxyAgent(options) {\n\tvar self = this;\n\tself.options = options;\n\tself.maxSockets = Http.Agent.defaultMaxSockets;\n\tself.requests = [];\n}", "const PAP = ProxyAgent.prototype;", "PAP.createConnection = function(pending) {\n\tvar self = this;\n\tself.createSocket(pending, function(socket) {\n\t\tpending.request.onSocket(socket);\n\t});\n};", "PAP.createSocket = function(options, callback) {", "\tvar self = this;\n\tvar proxy = self.options.proxy;\n\tvar uri = self.options.uri;", "\tPROXYOPTIONS.host = proxy.hostname;\n\tPROXYOPTIONS.port = proxy.port;\n\tPROXYOPTIONS.path = PROXYOPTIONS.headers.host = uri.hostname + ':' + (uri.port || '443');", "\tif (proxy._auth)\n\t\tPROXYOPTIONS.headers['Proxy-Authorization'] = proxy._auth;", "\tvar req = self.request(PROXYOPTIONS);\n\treq.setTimeout(10000);\n\treq.on('response', proxyagent_response);\n\treq.on('connect', function(res, socket) {", "\t\tif (res.statusCode === 200) {\n\t\t\tsocket.$req = req;\n\t\t\tcallback(socket);\n\t\t} else {\n\t\t\tvar err = new Error('Proxy could not be established (maybe a problem in auth), code: ' + res.statusCode);\n\t\t\terr.code = 'ECONNRESET';\n\t\t\treq.destroy && req.destroy();\n\t\t\treq = null;\n\t\t\tself.requests = null;\n\t\t\tself.options = null;\n\t\t}", "\t});", "\treq.on('error', function(err) {\n\t\tvar e = new Error('Request Proxy \"proxy {0} --> target {1}\": {2}'.format(PROXYOPTIONS.host + ':' + proxy.port, PROXYOPTIONS.path, err.toString()));\n\t\te.code = err.code;\n\t\treq.destroy && req.destroy();\n\t\treq = null;\n\t\tself.requests = null;\n\t\tself.options = null;\n\t});", "\treq.end();\n};", "function proxyagent_response(res) {\n\tres.upgrade = true;\n}", "PAP.addRequest = function(req, options) {\n\tthis.createConnection({ host: options.host, port: options.port, request: req });\n};", "function createSecureSocket(options, callback) {\n\tvar self = this;\n\tPAP.createSocket.call(self, options, function(socket) {\n\t\tPROXYTLS.servername = self.options.uri.hostname;\n\t\tPROXYTLS.headers = self.options.uri.headers;\n\t\tPROXYTLS.socket = socket;\n\t\tvar tls = Tls.connect(0, PROXYTLS);\n\t\tcallback(tls);\n\t});\n}", "function request_call(uri, options) {", "\tvar opt;", "\tif (options.proxy && !options.proxy.tls) {\n\t\topt = PROXYOPTIONSHTTP;\n\t\topt.port = options.proxy.port;\n\t\topt.host = options.proxy.hostname;\n\t\topt.path = uri.href;\n\t\topt.headers = uri.headers;\n\t\topt.method = uri.method;\n\t\topt.headers.host = uri.host;\n\t\tif (options.proxy._auth)\n\t\t\topt.headers['Proxy-Authorization'] = options.proxy._auth;\n\t} else\n\t\topt = uri;", "\tvar connection = uri.protocol === 'https:' ? Https : Http;\n\tvar req = opt.method === 'GET' ? connection.get(opt, request_response) : connection.request(opt, request_response);", "\treq.$options = options;\n\treq.$uri = uri;", "\tif (!options.callback) {\n\t\treq.on('error', NOOP);\n\t\treturn;\n\t}", "\treq.on('error', request_process_error);\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.timeoutid = setTimeout(request_process_timeout, options.timeout, req);", "\treq.on('response', request_assign_res);", "\tif (options.upload) {\n\t\toptions.first = true;\n\t\toptions.files.wait(function(file, next) {\n\t\t\trequest_writefile(req, options, file, next);\n\t\t}, function() {", "\t\t\tif (options.iserror)\n\t\t\t\treturn;", "\t\t\tif (options.body) {\n\t\t\t\tfor (var key in options.body) {\n\t\t\t\t\tvar value = options.body[key];\n\t\t\t\t\tif (value != null) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + key + '\"' + NEWLINE + NEWLINE + value);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\trequest_process_error.apply(req, e);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (options.first)\n\t\t\t\t\t\t\toptions.first = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\treq.end(NEWLINE + '--' + options.boundary + '--');\n\t\t});\n\t} else\n\t\treq.end(options.body);\n}", "function request_process_error(err) {\n\tvar options = this.$options;\n\toptions.iserror = true;\n\tif (options.callback && !options.done) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\toptions.canceled = true;\n\t\toptions.response.status = 0;\n\t\toptions.response.host = this.$uri.host;\n\t\toptions.callback(err, options.response);\n\t\toptions.callback = null;\n\t}\n}", "function request_process_timeout(req) {\n\tvar options = req.$options;\n\toptions.iserror = true;\n\tif (options.callback) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\treq.socket.destroy();\n\t\treq.socket.end();\n\t\treq.destroy();\n\t\toptions.response.status = 408;\n\t\toptions.response.host = req.$uri.host;\n\t\toptions.canceled = true;\n\t\toptions.callback(exports.httpstatus(408), options.response);\n\t\toptions.callback = null;\n\t}\n}", "function request_process_ok() {\n\tvar options = this.req.$options;\n\tif (options.timeoutid) {\n\t\tclearTimeout(options.timeoutid);\n\t\toptions.timeoutid = null;\n\t}\n}", "function request_assign_res(response) {\n\tresponse.req = this;\n}", "function request_writefile(req, options, file, next) {", "\tif (options.iserror) {\n\t\tnext();\n\t\treturn;\n\t}", "\tvar isbuffer = file.buffer instanceof Buffer;\n\tvar filename = (isbuffer ? file.name : exports.getName(file.filename));", "\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + file.name + '\"; filename=\"' + filename + '\"' + NEWLINE + 'Content-Type: ' + exports.getContentType(exports.getExtension(filename)) + NEWLINE + NEWLINE);", "\tif (options.first)\n\t\toptions.first = false;", "\tif (isbuffer) {\n\t\ttry {\n\t\t\treq.write(file.buffer);\n\t\t} catch (e) {\n\t\t\trequest_process_error.apply(req, e);\n\t\t}\n\t\tnext();\n\t} else {\n\t\tvar stream = Fs.createReadStream(file.filename);\n\t\tstream.once('close', next);\n\t\tstream.pipe(req, STREAMPIPE);\n\t}\n}", "function request_response(res) {", "\tvar options = this.$options;\n\tvar uri = this.$uri;", "\tres._buffer = null;\n\tres._bufferlength = 0;", "\t// We have redirect\n\tif (res.statusCode === 301 || res.statusCode === 302) {", "\t\tif (options.noredirect) {\n\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;\n\t\t\tif (options.callback) {\n\t\t\t\toptions.response.origin = options.origin;\n\t\t\t\toptions.response.status = res.statusCode;\n\t\t\t\toptions.response.headers = res.headers;\n\t\t\t\tif (options.custom) {\n\t\t\t\t\toptions.response.stream = res;\n\t\t\t\t\toptions.callback(null, options.response);\n\t\t\t\t} else {\n\t\t\t\t\toptions.response.host = uri.host;\n\t\t\t\t\toptions.response.headers = res.headers;\n\t\t\t\t\toptions.callback(null, options.response);\n\t\t\t\t}\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\tif (options.redirect > (options.redirects || 3)) {", "\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;\n\t\t\toptions.response.origin = options.origin;\n\t\t\toptions.response.headers = res.headers;", "\t\t\tif (options.callback) {\n\t\t\t\tif (options.custom) {\n\t\t\t\t\toptions.response.status = res.statusCode;\n\t\t\t\t\toptions.response.stream = res;\n\t\t\t\t\toptions.callback('Too many redirects', options.response);\n\t\t\t\t} else {\n\t\t\t\t\toptions.response.status = 0;\n\t\t\t\t\toptions.response.host = uri.host;\n\t\t\t\t\toptions.callback('Too many redirects', options.response);\n\t\t\t\t}\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\toptions.redirect++;", "\t\tvar loc = res.headers.location;\n\t\tvar proto = loc.substring(0, 6);", "\t\tif (proto !== 'http:/' && proto !== 'https:')\n\t\t\tloc = uri.protocol + '//' + uri.hostname + (uri.port && !SKIPPORTS[uri.port] ? (':' + uri.port) : '') + loc;", "\t\tvar tmp = Url.parse(loc);\n\t\ttmp.headers = uri.headers;", "\t\t// Transfers cookies\n\t\tif (!options.nocookies) {\n\t\t\tvar cookies = res.headers['set-cookie'];\n\t\t\tif (cookies) {", "\t\t\t\tif (options.$totalinit.cook && !options.$totalinit.cookies)\n\t\t\t\t\toptions.$totalinit.cookies = {};", "\t\t\t\tif (!options.cookies)\n\t\t\t\t\toptions.cookies = {};", "\t\t\t\tfor (var i = 0; i < cookies.length; i++) {\n\t\t\t\t\tvar cookie = cookies[i];\n\t\t\t\t\tvar index = cookie.indexOf(';');\n\t\t\t\t\tif (index !== -1){\n\t\t\t\t\t\tcookie = cookie.substring(0, index);\n\t\t\t\t\t\tindex = cookie.indexOf('=');\n\t\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\t\tvar key = decodeURIComponent(cookie.substring(0, index));\n\t\t\t\t\t\t\toptions.cookies[key] = decodeURIComponent(cookie.substring(index + 1));\n\t\t\t\t\t\t\tif (options.$totalinit.cookies)\n\t\t\t\t\t\t\t\toptions.$totalinit.cookies[key] = options.cookies[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tvar builder = '';\n\t\t\t\tfor (var m in options.cookies)\n\t\t\t\t\tbuilder += (builder ? '; ' : '') + encodeURIComponent(m) + '=' + encodeURIComponent(options.cookies[m]);", "\t\t\t\tif (tmp.headers.cookie)\n\t\t\t\t\ttmp.headers.cookie = builder;\n\t\t\t\telse\n\t\t\t\t\ttmp.headers.Cookie = builder;\n\t\t\t}\n\t\t}", "\t\t// tmp.agent = false;\n\t\ttmp.method = uri.method;", "\t\tres.req.removeAllListeners();\n\t\tres.req = null;", "\t\tif (options.proxy && tmp.protocol === 'https:') {\n\t\t\t// TLS?\n\t\t\toptions.proxy.tls = true;\n\t\t\toptions.uri = tmp;\n\t\t\toptions.uri.agent = new ProxyAgent(options);\n\t\t\toptions.uri.agent.request = Http.request;\n\t\t\toptions.uri.agent.createSocket = createSecureSocket;\n\t\t\toptions.uri.agent.defaultPort = 443;\n\t\t}", "\t\tif (!options.resolve) {\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn request_call(tmp, options);\n\t\t}", "\t\texports.resolve(tmp, function(err, u, param, origin) {\n\t\t\tif (!err) {\n\t\t\t\ttmp.host = u.host;\n\t\t\t\toptions.origin = origin;\n\t\t\t}\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\trequest_call(tmp, options);\n\t\t});", "\t\treturn;\n\t}", "\toptions.length = +res.headers['content-length'] || 0;", "\t// Shared cookies\n\tif (options.$totalinit.cook) {", "\t\tif (!options.$totalinit.cookies)\n\t\t\toptions.$totalinit.cookies = {};", "\t\tvar arr = (res.headers['set-cookie'] || '');", "\t\t// Only the one value\n\t\tif (arr && !(arr instanceof Array))\n\t\t\tarr = [arr];", "\t\tif (arr instanceof Array) {\n\t\t\tfor (var i = 0; i < arr.length; i++) {\n\t\t\t\tvar line = arr[i];\n\t\t\t\tvar end = line.indexOf(';');\n\t\t\t\tif (end === -1)\n\t\t\t\t\tend = line.length;\n\t\t\t\tline = line.substring(0, end);\n\t\t\t\tvar index = line.indexOf('=');\n\t\t\t\tif (index !== -1)\n\t\t\t\t\toptions.$totalinit.cookies[line.substring(0, index)] = decodeURIComponent(line.substring(index + 1));\n\t\t\t}\n\t\t}\n\t}", "\tif (res.statusCode === 204) {\n\t\toptions.done = true;\n\t\tif (options.custom) {\n\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.response.origin = options.origin;\n\t\t\toptions.response.status = res.statusCode;\n\t\t\toptions.response.headers = res.headers;\n\t\t\toptions.response.stream = res;\n\t\t\toptions.callback(null, options.response);\n\t\t\toptions.callback = null;\n\t\t} else\n\t\t\trequest_process_end.call(res);\n\t\treturn;\n\t}", "\toptions.timeoutid && res.once('data', request_process_ok);", "\tvar encoding = res.headers['content-encoding'] || '';\n\tif (encoding)\n\t\tencoding = encoding.split(',')[0];", "\tif (options.custom) {\n\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\toptions.response.origin = options.origin;\n\t\toptions.response.status = res.statusCode;\n\t\toptions.response.headers = res.headers;\n\t\toptions.response.stream = res;\n\t\toptions.callback && options.callback(null, options.response);\n\t\toptions.callback = null;\n\t} else {\n\t\tif (COMPRESS[encoding]) {\n\t\t\tvar zlib = encoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate();\n\t\t\tzlib._buffer = res.buffer;\n\t\t\tzlib.headers = res.headers;\n\t\t\tzlib.statusCode = res.statusCode;\n\t\t\tzlib.res = res;\n\t\t\tzlib.on('data', request_process_data);\n\t\t\tzlib.on('end', request_process_end);\n\t\t\tres.pipe(zlib);\n\t\t} else {\n\t\t\tres.on('data', request_process_data);\n\t\t\tres.on('end', request_process_end);\n\t\t}\n\t}", "\tres.resume();\n}", "function request_process_data(chunk) {\n\tvar self = this;\n\t// Is Zlib\n\tif (!self.req)\n\t\tself = self.res;\n\tvar options = self.req.$options;\n\tif (options.canceled || (options.limit && self._bufferlength > options.limit))\n\t\treturn;\n\tif (self._buffer) {\n\t\tCONCAT[0] = self._buffer;\n\t\tCONCAT[1] = chunk;\n\t\tself._buffer = Buffer.concat(CONCAT);\n\t} else\n\t\tself._buffer = chunk;\n\tself._bufferlength += chunk.length;\n\toptions.ondata && options.ondata(chunk, options.length ? (self._bufferlength / options.length) * 100 : 0);\n\toptions.onprogress && options.onprogress(options.length ? (self._bufferlength / options.length) * 100 : 0);\n}", "function request_process_end() {", "\tvar res = this;", "\t// Is Zlib\n\tif (!res.req)\n\t\tres = res.res;", "\tvar self = res;\n\tvar options = self.req.$options;\n\tvar uri = self.req.$uri;\n\tvar data;", "\toptions.socket && options.uri.agent.destroy();\n\toptions.timeoutid && clearTimeout(options.timeoutid);", "\tif (options.canceled)\n\t\treturn;", "\tvar ct = self.headers['content-type'];", "\tif (!ct || REG_TEXTAPPLICATION.test(ct)) {\n\t\tdata = self._buffer ? options.encoding === 'binary' ? self._buffer : self._buffer.toString(options.encoding) : '';\n\t\tif (options.opt.encrypt && typeof(data) === 'string')\n\t\t\tdata = exports.decrypt_data(data, options.opt.encrypt);\n\t} else\n\t\tdata = self._buffer;", "\toptions.canceled = true;\n\tself._buffer = undefined;", "\tif (options.callback) {\n\t\toptions.response.origin = options.origin;\n\t\toptions.response.headers = self.headers;\n\t\toptions.response.body = data;\n\t\toptions.response.status = self.statusCode;\n\t\toptions.response.host = uri.host || uri.socketPath;\n\t\toptions.response.cookies = options.cookies;\n\t\toptions.callback(null, options.response);\n\t\toptions.callback = null;\n\t}", "\tif (res.statusCode !== 204) {\n\t\tres.req && res.req.removeAllListeners();\n\t\tres.removeAllListeners();\n\t}\n}", "exports.btoa = function(str) {\n\treturn (str instanceof Buffer) ? str.toString('base64') : Buffer.from(str.toString(), 'utf8').toString('base64');\n};", "exports.atob = function(str) {\n\treturn Buffer.from(str, 'base64').toString('utf8');\n};", "/**\n * Trim string properties\n * @param {Object} obj\n * @return {Object}\n */\nexports.trim = function(obj, clean) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type === 'string') {\n\t\tobj = obj.trim();\n\t\treturn clean && !obj ? undefined : obj;\n\t}", "\tif (obj instanceof Array) {\n\t\tfor (var i = 0, length = obj.length; i < length; i++) {", "\t\t\tvar item = obj[i];\n\t\t\ttype = typeof(item);", "\t\t\tif (type === 'object') {\n\t\t\t\texports.trim(item, clean);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (type !== 'string')\n\t\t\t\tcontinue;", "\t\t\tobj[i] = item.trim();\n\t\t\tif (clean && !obj[i])\n\t\t\t\tobj[i] = undefined;\n\t\t}", "\t\treturn obj;\n\t}", "\tif (type !== 'object')\n\t\treturn obj;", "\tfor (var key in obj) {\n\t\tvar val = obj[key];\n\t\tvar type = typeof(val);\n\t\tif (type === 'object') {\n\t\t\texports.trim(val, clean);\n\t\t\tcontinue;\n\t\t} else if (type !== 'string')\n\t\t\tcontinue;\n\t\tobj[key] = val.trim();\n\t\tif (clean && !obj[key])\n\t\t\tobj[key] = undefined;\n\t}", "\treturn obj;\n};", "/**\n * Noop function\n * @return {Function} Empty function.\n */\nglobal.NOOP = function() {};", "/**\n * Read HTTP status\n * @param {Number} code HTTP code status.\n * @param {Boolean} addCode Add code number to HTTP status.\n * @return {String}\n */\nexports.httpstatus = function(code, addCode) {\n\tif (addCode === undefined)\n\t\taddCode = true;\n\treturn (addCode ? code + ': ' : '') + Http.STATUS_CODES[code];\n};", "/**\n * Extend object\n * @param {Object} target Target object.\n * @param {Object} source Source object.\n * @param {Boolean} rewrite Rewrite exists values (optional, default true).\n * @return {Object} Modified object.\n */\nexports.extend = function(target, source, rewrite) {", "\tif (!target || !source)\n\t\treturn target;", "\tif (typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tif (rewrite === undefined)\n\t\trewrite = true;", "\tfor (var key in source) {\n\t\tif (rewrite || target[key] === undefined)\n\t\t\ttarget[key] = exports.clone(source[key]);\n\t}", "\treturn target;\n};", "exports.extend_headers = function(first, second) {\n\tvar keys = Object.keys(first);\n\tvar headers = {};", "\tvar i = keys.length;\n\twhile (i--)\n\t\theaders[keys[i]] = first[keys[i]];", "\tkeys = Object.keys(second);\n\ti = keys.length;", "\twhile (i--)\n\t\theaders[keys[i]] = second[keys[i]];", "\treturn headers;\n};", "exports.extend_headers2 = function(first, second) {\n\tvar keys = Object.keys(second);\n\tvar i = keys.length;\n\twhile (i--)\n\t\tfirst[keys[i]] = second[keys[i]];\n\treturn first;\n};", "/**\n * Clones object\n * @param {Object} obj\n * @param {Object} skip Optional, can be only object e.g. { name: true, age: true }.\n * @param {Boolean} skipFunctions It doesn't clone functions, optional --> default false.\n * @return {Object}\n */\nglobal.CLONE = exports.clone = function(obj, skip, skipFunctions) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type !== 'object' || obj instanceof Date || obj instanceof Error)\n\t\treturn obj;", "\tvar length;\n\tvar o;", "\tif (obj instanceof Array) {", "\t\tlength = obj.length;\n\t\to = new Array(length);", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\ttype = typeof(obj[i]);\n\t\t\tif (type !== 'object' || obj[i] instanceof Date || obj[i] instanceof Error) {\n\t\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\t\tcontinue;\n\t\t\t\to[i] = obj[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\to[i] = exports.clone(obj[i], skip, skipFunctions);\n\t\t}", "\t\treturn o;\n\t}", "\to = {};", "\tfor (var m in obj) {", "\t\tif (skip && skip[m])\n\t\t\tcontinue;", "\t\tvar val = obj[m];", "\t\tif (val instanceof Buffer) {\n\t\t\tvar copy = Buffer.alloc(val.length);\n\t\t\tval.copy(copy);\n\t\t\to[m] = copy;\n\t\t\tcontinue;\n\t\t}", "\t\tvar type = typeof(val);\n\t\tif (type !== 'object' || val instanceof Date || val instanceof Error) {\n\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\tcontinue;\n\t\t\to[m] = val;\n\t\t\tcontinue;\n\t\t}", "\t\to[m] = exports.clone(obj[m], skip, skipFunctions);\n\t}", "\treturn o;\n};", "/**\n * Copy values from object to object\n * @param {Object} source Object source\n * @param {Object} target Object target (optional)\n * @return {Object} Modified object.\n */\nexports.copy = function(source, target) {", "\tif (target === undefined)\n\t\treturn exports.extend({}, source, true);", "\tif (!target || !source || typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tfor (var key in source) {\n\t\tif (target[key] !== undefined)\n\t\t\ttarget[key] = exports.clone(source[key]);\n\t}", "\treturn target;\n};", "/**\n * Reduces an object\n * @param {Object} source Source object.\n * @param {String Array or Object} prop Other properties than these ones will be removed.\n * @param {Boolean} reverse Reverse reducing (prop will be removed), default: false.\n * @return {Object}\n */\nexports.reduce = function(source, prop, reverse) {", "\tif (!(prop instanceof Array)) {\n\t\tif (typeof(prop) === 'object')\n\t\t\treturn exports.reduce(source, Object.keys(prop), reverse);\n\t}", "\tif (source instanceof Array) {\n\t\tvar arr = [];\n\t\tfor (var i = 0, length = source.length; i < length; i++)\n\t\t\tarr.push(exports.reduce(source[i], prop, reverse));\n\t\treturn arr;\n\t}", "\tvar output = {};", "\tfor (var o in source) {\n\t\tif (reverse) {\n\t\t\tif (prop.indexOf(o) === -1)\n\t\t\t\toutput[o] = source[o];\n\t\t} else {\n\t\t\tif (prop.indexOf(o) !== -1)\n\t\t\t\toutput[o] = source[o];\n\t\t}\n\t}", "\treturn output;\n};", "/**\n * Checks if is relative url\n * @param {String} url\n * @return {Boolean}\n */\nexports.isrelative = function(url) {\n\treturn !(url.substring(0, 2) === '//' || url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1);\n};", "/**\n * Streamer method\n * @param {String/Buffer} beg\n * @param {String/Buffer} end\n * @param {Function(value, index)} callback\n */\nexports.streamer = function(beg, end, callback, skip, stream, raw) {", "\tif (typeof(end) === 'function') {\n\t\tstream = skip;\n\t\tskip = callback;\n\t\tcallback = end;\n\t\tend = undefined;\n\t}", "\tif (typeof(skip) === 'object') {\n\t\tstream = skip;\n\t\tskip = 0;\n\t}", "\tvar indexer = 0;\n\tvar buffer = Buffer.alloc(0);\n\tvar canceled = false;\n\tvar fn;", "\tif (skip === undefined)\n\t\tskip = 0;", "\tif (!(beg instanceof Buffer))\n\t\tbeg = Buffer.from(beg, 'utf8');", "\tif (end && !(end instanceof Buffer))\n\t\tend = Buffer.from(end, 'utf8');", "\tif (!end) {\n\t\tvar length = beg.length;\n\t\tfn = function(chunk) {", "\t\t\tif (!chunk || canceled)\n\t\t\t\treturn;", "\t\t\tCONCAT[0] = buffer;\n\t\t\tCONCAT[1] = chunk;", "\t\t\tvar f = 0;", "\t\t\tif (buffer.length) {\n\t\t\t\tf = buffer.length - beg.length;\n\t\t\t\tif (f < 0)\n\t\t\t\t\tf = 0;\n\t\t\t}", "\t\t\tbuffer = Buffer.concat(CONCAT);", "\t\t\tvar index = buffer.indexOf(beg, f);\n\t\t\tif (index === -1)\n\t\t\t\treturn;", "\t\t\twhile (index !== -1) {", "\t\t\t\tif (skip)\n\t\t\t\t\tskip--;\n\t\t\t\telse {\n\t\t\t\t\tif (callback(raw ? buffer.slice(0, index + length) : buffer.toString('utf8', 0, index + length), indexer++) === false)\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t}", "\t\t\t\tif (canceled)\n\t\t\t\t\treturn;", "\t\t\t\tbuffer = buffer.slice(index + length);\n\t\t\t\tindex = buffer.indexOf(beg);\n\t\t\t\tif (index === -1)\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t};", "\t\tstream && stream.on('end', () => fn(beg));\n\t\treturn fn;\n\t}", "\tvar blength = beg.length;\n\tvar elength = end.length;\n\tvar bi = -1;\n\tvar ei = -1;\n\tvar is = false;", "\tfn = function(chunk) {", "\t\tif (!chunk || canceled)\n\t\t\treturn;", "\t\tCONCAT[0] = buffer;\n\t\tCONCAT[1] = chunk;\n\t\tbuffer = Buffer.concat(CONCAT);", "\t\tif (!is) {\n\t\t\tvar f = CONCAT[0].length - beg.length;\n\t\t\tif (f < 0)\n\t\t\t\tf = 0;\n\t\t\tbi = buffer.indexOf(beg, f);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t}", "\t\tif (is) {\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}", "\t\twhile (bi !== -1) {", "\t\t\tif (skip)\n\t\t\t\tskip--;\n\t\t\telse {\n\t\t\t\tif (callback(raw ? buffer.slice(bi, ei + elength) : buffer.toString('utf8', bi, ei + elength), indexer++) === false)\n\t\t\t\t\tcanceled = true;\n\t\t\t}", "\t\t\tif (canceled)\n\t\t\t\treturn;", "\t\t\tbuffer = buffer.slice(ei + elength);\n\t\t\tis = false;\n\t\t\tbi = buffer.indexOf(beg);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}\n\t};", "\tstream && stream.on('end', () => fn(end));\n\treturn fn;\n};", "exports.streamer2 = function(beg, end, callback, skip, stream) {\n\treturn exports.streamer(beg, end, callback, skip, stream, true);\n};", "/**\n * HTML encode string\n * @param {String} str\n * @return {String}\n */\nexports.encode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.encode();\n};", "/**\n * HTML decode string\n * @param {String} str\n * @return {String}\n */\nexports.decode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.decode();\n};", "/**\n * Checks if URL contains file extension.\n * @param {String} url\n * @return {Boolean}\n */\nexports.isStaticFile = function(url) {\n\tvar index = url.indexOf('.', url.length - 8);\n\treturn index !== -1;\n};", "/**\n * Converts Value to number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseInt = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseInt(def);\n};", "exports.parseBoolean = function(obj, def) {\n\tif (obj == null)\n\t\treturn def === undefined ? false : def;\n\tvar type = typeof(obj);\n\treturn type === 'boolean' ? obj : type === 'number' ? obj > 0 : (type !== 'string' ? obj.toString() : obj).parseBoolean(def);\n};", "/**\n * Converts Value to float number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseFloat = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseFloat(def);\n};", "/**\n * Check if the object is Date\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isDate = function(obj) {\n\treturn obj instanceof Date && !isNaN(obj.getTime()) ? true : false;\n};", "/**\n * Get ContentType from file extension.\n * @param {String} ext File extension.\n * @return {String}\n */\nexports.getContentType = function(ext) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);\n\treturn CONTENTTYPES[ext] || 'application/octet-stream';\n};", "/**\n * Get extension from filename\n * @param {String} filename\n * @return {String}\n */\nexports.getExtension = function(filename, raw) {\n\tvar end = filename.length;\n\tfor (var i = filename.length - 1; i > 0; i--) {\n\t\tvar c = filename[i];\n\t\tif (c === ' ' || c === '?')\n\t\t\tend = i;\n\t\telse if (c === '.') {\n\t\t\tc = filename.substring(i + 1, end);\n\t\t\treturn raw ? c : c.toLowerCase();\n\t\t}\n\t\telse if (c === '/' || c === '\\\\')\n\t\t\treturn '';\n\t}\n\treturn '';\n};", "/**\n * Get base name from path\n * @param {String} path\n * @return {String}\n */\nexports.getName = function(path) {\n\tvar l = path.length - 1;\n\tvar c = path[l];\n\tif (c === '/' || c === '\\\\')\n\t\tpath = path.substring(0, l);\n\tvar index = path.lastIndexOf('/');\n\tif (index !== -1)\n\t\treturn path.substring(index + 1);\n\tindex = path.lastIndexOf('\\\\');\n\treturn index === -1 ? path : path.substring(index + 1);\n};", "/**\n * Add a new content type to content types\n * @param {String} ext File extension.\n * @param {String} type Content type (example: application/json).\n */\nexports.setContentType = function(ext, type) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);", "\tif (ext.length > 8) {\n\t\tvar tmp = regexpSTATIC.toString().replace(/,\\d+\\}/, ',' + ext.length + '}').substring(1);\n\t\tregexpSTATIC = new RegExp(tmp.substring(0, tmp.length - 1));\n\t}", "\tCONTENTTYPES[ext] = type;\n\treturn true;\n};", "exports.normalize = function(path) {\n\tif (path[0] !== '/')\n\t\tpath = '/' + path;\n\tif (path[path.length - 1] !== '/')\n\t\tpath += '/';\n\treturn path;\n};", "exports.link = function() {\n\tvar builder = '';\n\tfor (var i = 0; i < arguments.length; i++) {", "\t\tvar url = arguments[i];\n\t\tvar between = '';", "\t\tif (builder) {\n\t\t\tvar c = builder[builder.length - 1];\n\t\t\tif (c === '/') {\n\t\t\t\tif (url[0] === '/')\n\t\t\t\t\turl = url.substring(1);\n\t\t\t} else {\n\t\t\t\tif (url[0] !== '/')\n\t\t\t\t\tbetween = '/';\n\t\t\t}\n\t\t} else\n\t\t\tbetween = '';", "\t\tbuilder += between + url;\n\t}\n\treturn builder;\n};", "exports.path = function(path, delimiter) {\n\tif (!path)\n\t\tpath = '';\n\tdelimiter = delimiter || '/';\n\treturn path[path.length - 1] === delimiter ? path : path + delimiter;\n};", "exports.join = function() {\n\tvar path = [''];", "\tfor (var i = 0; i < arguments.length; i++) {\n\t\tvar current = arguments[i];\n\t\tif (current) {\n\t\t\tif (current[0] === '/')\n\t\t\t\tcurrent = current.substring(1);\n\t\t\tvar l = current.length - 1;\n\t\t\tif (current[l] === '/')\n\t\t\t\tcurrent = current.substring(0, l);\n\t\t\tpath.push(current);\n\t\t}\n\t}", "\tpath = path.join('/');\n\treturn !isWindows ? path : path.indexOf(':') > -1 ? path.substring(1) : path;\n};", "/**\n * Prepares Windows path to UNIX like format\n * @internal\n * @param {String} path\n * @return {String}\n */\nexports.$normalize = function(path) {\n\treturn isWindows ? path.replace(regexpPATH, '/') : path;\n};", "const RANDOM_STRING = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');\nconst RANDOM_NUMBER = '0123456789';", "exports.random_string = function(max) {\n\tvar builder = '';\n\tfor (var i = 0; i < max; i++) {\n\t\tvar index = Math.floor(Math.random() * RANDOM_STRING.length);\n\t\tbuilder += RANDOM_STRING[index];\n\t}\n\treturn builder;\n};", "exports.random_number = function(max) {\n\tvar builder = '';\n\tfor (var i = 0; i < max; i++) {\n\t\tvar index = Math.floor(Math.random() * RANDOM_NUMBER.length);\n\t\tif (!i && !index)\n\t\t\tindex++;\n\t\tbuilder += RANDOM_NUMBER[index];\n\t}\n\treturn builder;\n};", "exports.random = function(max, min) {\n\tmax = (max || 100000);\n\tmin = (min || 0);\n\treturn Math.floor(Math.random() * (max - min + 1)) + min;\n};", "function rnd() {\n\treturn Math.floor(Math.random() * 65536).toString(36);\n}", "global.GUID = exports.GUID = function(max) {\n\tmax = max || 40;\n\tvar str = '';\n\tfor (var i = 0; i < (max / 3) + 1; i++)\n\t\tstr += rnd();\n\treturn str.substring(0, max);\n};", "function validate_builder_default(name, value, entity) {", "\tvar type = typeof(value);", "\tif (entity.type === 12)\n\t\treturn value != null && type === 'object' && !(value instanceof Array);", "\tif (entity.type === 11)\n\t\treturn type === 'number';", "\t// Enum + KeyValue + Custom (8+9+10)\n\tif (entity.type > 7)\n\t\treturn value !== undefined;", "\tswitch (entity.subtype) {\n\t\tcase 'uid':\n\t\t\treturn value.isUID();\n\t\tcase 'zip':\n\t\t\treturn value.isZIP();\n\t\tcase 'email':\n\t\t\treturn value.isEmail();\n\t\tcase 'json':\n\t\t\treturn value.isJSON();\n\t\tcase 'url':\n\t\t\treturn value.isURL();\n\t\tcase 'phone':\n\t\t\treturn value.isPhone();\n\t\tcase 'base64':\n\t\t\treturn value.isBase64(true);\n\t}", "\tif (type === 'number')\n\t\treturn value > 0;", "\tif (type === 'string' || value instanceof Array)\n\t\treturn value.length > 0;", "\tif (type === 'boolean')\n\t\treturn value === true;", "\tif (value == null)\n\t\treturn false;", "\tif (value instanceof Date)\n\t\treturn value.toString()[0] !== 'I'; // Invalid Date", "\treturn true;\n}", "exports.validate_builder = function(model, error, schema, path, index, $, pluspath) {", "\tvar current = path ? path + '.' : '';\n\tvar properties = $ ? ($.keys || schema.properties) : schema.properties;\n\tvar result;", "\tif (!pluspath)\n\t\tpluspath = '';", "\tif (model == null)\n\t\tmodel = {};", "\tfor (var i = 0; i < properties.length; i++) {", "\t\tvar name = properties[i];\n\t\tvar TYPE = schema.schema[name];\n\t\tif (!TYPE)\n\t\t\tcontinue;", "\t\tif (TYPE.can && !TYPE.can(model, model.$$workflow || EMPTYOBJECT))\n\t\t\tcontinue;", "\t\tvar value = model[name];\n\t\tvar type = typeof(value);\n\t\tvar prefix = schema.resourcePrefix ? (schema.resourcePrefix + name) : name;", "\t\tif (value === undefined) {\n\t\t\terror.push(pluspath + name, '@', current + name, undefined, prefix);\n\t\t\tcontinue;\n\t\t} else if (type === 'function')\n\t\t\tvalue = model[name]();", "\t\tif (TYPE.isArray) {\n\t\t\tif (TYPE.type === 7 && value instanceof Array && value.length) {\n\t\t\t\tvar nestedschema = GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema) {\n\t\t\t\t\tfor (var j = 0, jl = value.length; j < jl; j++)\n\t\t\t\t\t\texports.validate_builder(value[j], error, nestedschema, current + name + '[' + j + ']', j, undefined, pluspath);\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {", "\t\t\t\tif (!TYPE.required)\n\t\t\t\t\tcontinue;", "\t\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;\n\t\t\t\tif (result == null) {\n\t\t\t\t\tresult = value instanceof Array ? value.length > 0 : false;\n\t\t\t\t\tif (result == null || result === true)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, TYPE.invalid, current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean')\n\t\t\t\t\t!result && error.push(pluspath + name, TYPE.invalid, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (TYPE.type === 7) {", "\t\t\tif (!value && !TYPE.required)\n\t\t\t\tcontinue;", "\t\t\t// Another schema\n\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;", "\t\t\tif (result == null) {\n\t\t\t\tvar nestedschema = GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema)\n\t\t\t\t\texports.validate_builder(value, error, nestedschema, current + name, undefined, undefined, pluspath);\n\t\t\t\telse\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {\n\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, TYPE.invalid, current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean')\n\t\t\t\t\t!result && error.push(pluspath + name, TYPE.invalid, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (!TYPE.required)\n\t\t\tcontinue;", "\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;\n\t\tif (result == null) {\n\t\t\tresult = validate_builder_default(name, value, TYPE);\n\t\t\tif (result == null || result === true)\n\t\t\t\tcontinue;\n\t\t}", "\t\ttype = typeof(result);", "\t\tif (type === 'string') {\n\t\t\tif (result[0] === '@')\n\t\t\t\terror.push(pluspath + name, TYPE.invalid, current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\telse\n\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t} else if (type === 'boolean')\n\t\t\t!result && error.push(pluspath + name, TYPE.invalid, current + name, index, prefix);\n\t}", "\treturn error;\n};", "/**\n * Combine paths\n * @return {String}\n */\nexports.combine = function() {", "\tvar p = F.directory;", "\tfor (var i = 0, length = arguments.length; i < length; i++) {\n\t\tvar v = arguments[i];\n\t\tif (!v)\n\t\t\tcontinue;\n\t\tif (v[0] === '/')\n\t\t\tv = v.substring(1);", "\t\tif (v[0] === '~')\n\t\t\tp = v.substring(1);\n\t\telse\n\t\t\tp += (p[p.length - 1] !== '/' ? '/' : '') + v;\n\t}\n\treturn exports.$normalize(p);\n};", "/**\n * Simple XML parser\n * @param {String} xml\n * @return {Object}\n */\nexports.parseXML = function(xml, replace) {\n\treturn xml.parseXML(replace);\n};", "function jsonparser(key, value) {\n\treturn typeof(value) === 'string' && value.isJSONDate() ? new Date(value) : value;\n}", "/**\n * Get WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @param {Hexa} type\n * @return {Buffer}\n */\nexports.getWebSocketFrame = function(code, message, type, compress, mask) {", "\tif (mask)\n\t\tmask = ((Math.random() * 214748364) >> 0) + 1;", "\tvar messageBuffer = getWebSocketFrameMessageBytes(code, message);\n\tvar lengthBuffer = getWebSocketFrameLengthBytes(messageBuffer.length);\n\tvar lengthMask = mask ? 4 : 0;\n\tvar frameBuffer = Buffer.alloc(1 + lengthBuffer.length + messageBuffer.length + lengthMask);", "\tframeBuffer[0] = 0x80 | type;", "\tif (compress)\n\t\tframeBuffer[0] |= 0x40;", "\tlengthBuffer.copy(frameBuffer, 1, 0, lengthBuffer.length);", "\tif (mask) {\n\t\tvar offset = lengthBuffer.length + 1;\n\t\tframeBuffer[1] |= 0x80;\n\t\tframeBuffer.writeInt32BE(mask, offset);\n\t\tfor (var i = 0; i < messageBuffer.length; i++)\n\t\t\tmessageBuffer[i] = messageBuffer[i] ^ frameBuffer[offset + (i % 4)];\n\t}", "\tmessageBuffer.copy(frameBuffer, lengthBuffer.length + 1 + lengthMask, 0, messageBuffer.length);\n\treturn frameBuffer;\n};", "/**\n * Get bytes of WebSocket frame message\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @return {Buffer}\n */\nfunction getWebSocketFrameMessageBytes(code, message) {", "\tvar index = code ? 2 : 0;\n\tvar binary = message instanceof Int8Array || message instanceof Buffer;\n\tvar length = message.length;", "\tvar messageBuffer = Buffer.alloc(length + index);", "\tfor (var i = 0; i < length; i++) {\n\t\tif (binary)\n\t\t\tmessageBuffer[i + index] = message[i];\n\t\telse\n\t\t\tmessageBuffer[i + index] = message.charCodeAt(i);\n\t}", "\tif (code) {\n\t\tmessageBuffer[0] = code >> 8;\n\t\tmessageBuffer[1] = code;\n\t}", "\treturn messageBuffer;\n}", "/**\n * Get length of WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} length\n * @return {Number}\n */\nfunction getWebSocketFrameLengthBytes(length) {\n\tvar lengthBuffer = null;", "\tif (length <= 125) {\n\t\tlengthBuffer = Buffer.alloc(1);\n\t\tlengthBuffer[0] = length;\n\t\treturn lengthBuffer;\n\t}", "\tif (length <= 65535) {\n\t\tlengthBuffer = Buffer.alloc(3);\n\t\tlengthBuffer[0] = 126;\n\t\tlengthBuffer[1] = (length >> 8) & 255;\n\t\tlengthBuffer[2] = (length) & 255;\n\t\treturn lengthBuffer;\n\t}", "\tlengthBuffer = Buffer.alloc(9);", "\tlengthBuffer[0] = 127;\n\tlengthBuffer[1] = 0x00;\n\tlengthBuffer[2] = 0x00;\n\tlengthBuffer[3] = 0x00;\n\tlengthBuffer[4] = 0x00;\n\tlengthBuffer[5] = (length >> 24) & 255;\n\tlengthBuffer[6] = (length >> 16) & 255;\n\tlengthBuffer[7] = (length >> 8) & 255;\n\tlengthBuffer[8] = (length) & 255;", "\treturn lengthBuffer;\n}", "/**\n * GPS distance in KM\n * @param {Number} lat1\n * @param {Number} lon1\n * @param {Number} lat2\n * @param {Number} lon2\n * @return {Number}\n */\nexports.distance = function(lat1, lon1, lat2, lon2) {\n\tvar R = 6371;\n\tvar dLat = (lat2 - lat1).toRad();\n\tvar dLon = (lon2 - lon1).toRad();\n\tvar a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\tvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\treturn (R * c).floor(3);\n};", "function ls(path, callback, advanced, filter) {\n\tvar filelist = new FileList();\n\tvar tmp;", "\tfilelist.advanced = advanced;\n\tfilelist.onComplete = callback;", "\tif (typeof(filter) === 'string') {\n\t\ttmp = filter.toLowerCase();\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : filename.toLowerCase().indexOf(tmp) !== -1;\n\t\t};\n\t} else if (filter && filter.test) {\n\t\t// regexp\n\t\ttmp = filter;\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : tmp.test(filename);\n\t\t};\n\t} else\n\t\tfilelist.onFilter = filter || null;", "\tfilelist.walk(path);\n}", "/**\n * Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename, isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls = function(path, callback, filter) {\n\tls(path, callback, false, filter);\n};", "/**\n * Advanced Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename ,isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls2 = function(path, callback, filter) {\n\tls(path, callback, true, filter);\n};", "DP.setTimeZone = function(timezone) {", "\tvar dt = new Date(this.toLocaleString('en-US', { timeZone: timezone }));", "\tvar offset = dt + '';\n\tvar index = offset.indexOf('GMT');\n\tvar op = offset.substring(index + 3, index + 4);\n\tvar count = offset.substring(index + 4, index + 9);\n\tvar h = +count.substring(0, 2);\n\tvar m = +count.substring(2);", "\tif (op === '+') {\n\t\th && dt.setHours(dt.getHours() + h);\n\t\tm && dt.setMinutes(dt.getMinutes() + m);\n\t} else {\n\t\th && dt.setHours(dt.getHours() - h);\n\t\tm && dt.setMinutes(dt.getMinutes() - m);\n\t}", "\treturn dt;\n};", "/**\n * Date difference\n * @param {Date/Number/String} date Optional.\n * @param {String} type Date type: minutes, seconds, hours, days, months, years\n * @return {Number}\n */\nDP.diff = function(date, type) {", "\tif (arguments.length === 1) {\n\t\ttype = date;\n\t\tdate = Date.now();\n\t} else {\n\t\tvar to = typeof(date);\n\t\tif (to === 'string')\n\t\t\tdate = Date.parse(date);\n\t\telse if (exports.isDate(date))\n\t\t\tdate = date.getTime();\n\t}", "\tvar r = this.getTime() - date;", "\tswitch (type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\treturn Math.ceil(r / 1000);\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'minutes':\n\t\t\treturn Math.ceil((r / 1000) / 60);\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\treturn Math.ceil(((r / 1000) / 60) / 60);\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / 24);\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28));", "\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28 * 12));\n\t}", "\treturn NaN;\n};", "DP.add = function(type, value) {", "\tvar self = this;", "\tif (type.constructor === Number)\n\t\treturn new Date(self.getTime() + (type - type % 1));", "\tif (value === undefined) {\n\t\tvar arr = type.split(' ');\n\t\ttype = arr[1];\n\t\tvalue = exports.parseInt(arr[0]);\n\t}", "\tvar dt = new Date(self.getTime());", "\tswitch(type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'sec':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\tdt.setUTCSeconds(dt.getUTCSeconds() + value);\n\t\t\treturn dt;\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'min':\n\t\tcase 'minutes':\n\t\t\tdt.setUTCMinutes(dt.getUTCMinutes() + value);\n\t\t\treturn dt;\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\tdt.setUTCHours(dt.getUTCHours() + value);\n\t\t\treturn dt;\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + value);\n\t\t\treturn dt;\n\t\tcase 'w':\n\t\tcase 'ww':\n\t\tcase 'week':\n\t\tcase 'weeks':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + (value * 7));\n\t\t\treturn dt;\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\tdt.setUTCMonth(dt.getUTCMonth() + value);\n\t\t\treturn dt;\n\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\tdt.setUTCFullYear(dt.getUTCFullYear() + value);\n\t\t\treturn dt;\n\t}\n\treturn dt;\n};", "DP.extend = function(date) {\n\tvar dt = new Date(this);\n\tvar match = date.match(regexpDATE);", "\tif (!match)\n\t\treturn dt;", "\tfor (var i = 0, length = match.length; i < length; i++) {\n\t\tvar m = match[i];\n\t\tvar arr, tmp;", "\t\tif (m.indexOf(':') !== -1) {", "\t\t\tarr = m.split(':');\n\t\t\ttmp = +arr[0];\n\t\t\ttmp >= 0 && dt.setUTCHours(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMinutes(tmp);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCSeconds(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('-') !== -1) {\n\t\t\tarr = m.split('-');", "\t\t\ttmp = +arr[0];\n\t\t\ttmp && dt.setUTCFullYear(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCDate(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('.') !== -1) {\n\t\t\tarr = m.split('.');", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\t!isNaN(tmp) && dt.setUTCFullYear(tmp);\n\t\t\t}", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\t!isNaN(tmp) && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\ttmp = +arr[0];\n\t\t\t!isNaN(tmp) && dt.setUTCDate(tmp);", "\t\t\tcontinue;\n\t\t}\n\t}", "\treturn dt;\n};", "/**\n * Format datetime\n * @param {String} format\n * @return {String}\n */\nDP.format = function(format, resource) {", "\tif (!format)\n\t\treturn this.getUTCFullYear() + '-' + (this.getUTCMonth() + 1).toString().padLeft(2, '0') + '-' + this.getUTCDate().toString().padLeft(2, '0') + 'T' + this.getUTCHours().toString().padLeft(2, '0') + ':' + this.getUTCMinutes().toString().padLeft(2, '0') + ':' + this.getUTCSeconds().toString().padLeft(2, '0') + '.' + this.getUTCMilliseconds().toString().padLeft(3, '0') + 'Z';", "\tif (datetimeformat[format])\n\t\treturn datetimeformat[format](this, resource);", "\tvar key = format;\n\tvar half = false;", "\tif (format && format[0] === '!') {\n\t\thalf = true;\n\t\tformat = format.substring(1);\n\t}", "\tvar beg = '\\'+';\n\tvar end = '+\\'';\n\tvar before = [];", "\tvar ismm = false;\n\tvar isdd = false;\n\tvar isww = false;", "\tformat = format.replace(regexpDATEFORMAT, function(key) {\n\t\tswitch (key) {\n\t\t\tcase 'yyyy':\n\t\t\tcase 'YYYY':\n\t\t\t\treturn beg + 'd.getFullYear()' + end;\n\t\t\tcase 'yy':\n\t\t\tcase 'YY':\n\t\t\t\treturn beg + 'd.getFullYear().toString().substring(2)' + end;\n\t\t\tcase 'MMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, mm) || mm).substring(0, 3)' + end;\n\t\t\tcase 'MMMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, mm) || mm)' + end;\n\t\t\tcase 'MM':\n\t\t\t\treturn beg + '(d.getMonth() + 1).toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'M':\n\t\t\t\treturn beg + '(d.getMonth() + 1)' + end;\n\t\t\tcase 'ddd':\n\t\t\tcase 'DDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, dd) || dd).substring(0, 2).toUpperCase()' + end;\n\t\t\tcase 'dddd':\n\t\t\tcase 'DDDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, dd) || dd)' + end;\n\t\t\tcase 'dd':\n\t\t\tcase 'DD':\n\t\t\t\treturn beg + 'd.getDate().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'd':\n\t\t\tcase 'D':\n\t\t\t\treturn beg + 'd.getDate()' + end;\n\t\t\tcase 'HH':\n\t\t\tcase 'hh':\n\t\t\t\treturn beg + (half ? 'framework_utils.$pmam(d.getHours()).toString().padLeft(2, \\'0\\')' : 'd.getHours().toString().padLeft(2, \\'0\\')') + end;\n\t\t\tcase 'H':\n\t\t\tcase 'h':\n\t\t\t\treturn beg + (half ? 'framework_utils(d.getHours())' : 'd.getHours()') + end;\n\t\t\tcase 'mm':\n\t\t\t\treturn beg + 'd.getMinutes().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'm':\n\t\t\t\treturn beg + 'd.getMinutes()' + end;\n\t\t\tcase 'ss':\n\t\t\t\treturn beg + 'd.getSeconds().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 's':\n\t\t\t\treturn beg + 'd.getSeconds()' + end;\n\t\t\tcase 'w':\n\t\t\tcase 'ww':\n\t\t\t\tisww = true;\n\t\t\t\treturn beg + (key === 'ww' ? 'ww.toString().padLeft(2, \\'0\\')' : 'ww') + end;\n\t\t\tcase 'a':\n\t\t\t\tvar b = \"'PM':'AM'\";\n\t\t\t\treturn beg + '(d.getHours() >= 12 ? ' + b + ')' + end;\n\t\t}\n\t});", "\tismm && before.push('var mm = framework_utils.MONTHS[d.getMonth()];');\n\tisdd && before.push('var dd = framework_utils.DAYS[d.getDay()];');\n\tisww && before.push('var ww = new Date(+d);ww.setHours(0, 0, 0);ww.setDate(ww.getDate() + 4 - (ww.getDay() || 7));ww = Math.ceil((((ww - new Date(ww.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);');", "\tdatetimeformat[key] = new Function('d', 'resource', before.join('\\n') + 'return \\'' + format + '\\';');\n\treturn datetimeformat[key](this, resource);\n};", "exports.$pmam = function(value) {\n\treturn value >= 12 ? value - 12 : value;\n};", "DP.toUTC = function(ticks) {\n\tvar dt = this.getTime() + this.getTimezoneOffset() * 60000;\n\treturn ticks ? dt : new Date(dt);\n};", "// +v2.2.0 parses JSON dates as dates and this is the fallback for backward compatibility\nDP.parseDate = function() {\n\treturn this;\n};", "SP.isJSONDate = function() {\n\tvar l = this.length - 1;\n\treturn l > 22 && l < 30 && this[l] === 'Z' && this[10] === 'T' && this[4] === '-' && this[13] === ':' && this[16] === ':';\n};", "SP.ROOT = function(noremap) {", "\tvar str = this;", "\tstr = str.replace(REG_NOREMAP, function() {\n\t\tnoremap = true;\n\t\treturn '';\n\t}).replace(REG_ROOT, $urlmaker);", "\tif (!noremap && CONF.default_root)\n\t\tstr = str.replace(REG_REMAP, $urlremap).replace(REG_AJAX, $urlajax);", "\treturn str;\n};", "function $urlremap(text) {\n\tvar pos = text[0] === 'h' ? 6 : 5;\n\treturn REG_URLEXT.test(text) ? text : ((text[0] === 'h' ? 'href' : 'src') + '=\"' + CONF.default_root + (text[pos] === '/' ? text.substring(pos + 1) : text));\n}", "function $urlajax(text) {\n\treturn text.substring(0, text.length - 1) + CONF.default_root;\n}", "function $urlmaker(text) {\n\tvar c = text[4];\n\treturn CONF.default_root ? CONF.default_root : (c || '');\n}", "if (!SP.trim) {\n\tSP.trim = function() {\n\t\treturn this.replace(regexpTRIM, '');\n\t};\n}", "/**\n * Checks if the string starts with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.startsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.startsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(0, length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr(ignoreCase, length);\n\telse\n\t\ttmp = self.substring(0, length);", "\treturn tmp.length === length && tmp === text;\n};", "/**\n * Checks if the string ends with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.endsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.endsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(self.length - length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr((self.length - ignoreCase) - length, length);\n\telse\n\t\ttmp = self.substring(self.length - length);", "\treturn tmp.length === length && tmp === text;\n};", "SP.replacer = function(find, text) {\n\tvar self = this;\n\tvar beg = self.indexOf(find);\n\treturn beg === -1 ? self : (self.substring(0, beg) + text + self.substring(beg + find.length));\n};", "/**\n * Hash string\n * @param {String} type Hash type.\n * @param {String} salt Optional, salt.\n * @return {String}\n */\nSP.hash = function(type, salt) {\n\tvar str = salt ? this + salt : this;\n\tswitch (type) {\n\t\tcase 'md5':\n\t\t\treturn str.md5();\n\t\tcase 'sha1':\n\t\t\treturn str.sha1();\n\t\tcase 'sha256':\n\t\t\treturn str.sha256();\n\t\tcase 'sha512':\n\t\t\treturn str.sha512();\n\t\tcase 'crc32':\n\t\t\treturn str.crc32();\n\t\tcase 'crc32unsigned':\n\t\t\treturn str.crc32(true);\n\t\tdefault:\n\t\t\tvar val = string_hash(str);\n\t\t\treturn type === true ? val >>> 0 : val;\n\t}\n};", "global.HASH = function(value, type) {\n\treturn value.hash(type ? type : true);\n};", "SP.makeid = function() {\n\treturn this.hash(true).toString(36);\n};", "SP.crc32 = function(unsigned) {\n\tvar crc = -1;\n\tfor (var i = 0, length = this.length; i < length; i++)\n\t\tcrc = (crc >>> 8) ^ CRC32TABLE[(crc ^ this.charCodeAt(i)) & 0xFF];\n\tvar val = crc ^ (-1);\n\treturn unsigned ? val >>> 0 : val;\n};", "function string_hash(s, convert) {\n\tvar hash = 0;\n\tif (s.length === 0)\n\t\treturn convert ? '' : hash;\n\tfor (var i = 0, l = s.length; i < l; i++) {\n\t\tvar char = s.charCodeAt(i);\n\t\thash = ((hash << 5) - hash) + char;\n\t\thash |= 0;\n\t}\n\treturn hash;\n}", "SP.count = function(text) {\n\tvar index = 0;\n\tvar count = 0;\n\tdo {\n\t\tindex = this.indexOf(text, index + text.length);\n\t\tif (index > 0)\n\t\t\tcount++;\n\t} while (index > 0);\n\treturn count;\n};", "SP.parseComponent = function(tags) {", "\tvar html = this;\n\tvar beg = -1;\n\tvar end = -1;\n\tvar output = {};", "\tfor (var key in tags) {", "\t\tvar tagbeg = tags[key];\n\t\tvar tagindex = tagbeg.indexOf(' ');", "\t\tif (tagindex === -1)\n\t\t\ttagindex = tagbeg.length - 1;", "\t\tvar tagend = '</' + tagbeg.substring(1, tagindex) + '>';\n\t\tvar tagbeg2 = '<' + tagend.substring(2);", "\t\tbeg = html.indexOf(tagbeg);", "\t\tif (beg !== -1) {", "\t\t\tvar count = 0;\n\t\t\tend = -1;", "\t\t\tfor (var j = (beg + tagbeg.length); j < html.length; j++) {\n\t\t\t\tvar a = html.substring(j, j + tagbeg2.length);\n\t\t\t\tif (a === tagbeg2) {\n\t\t\t\t\tcount++;\n\t\t\t\t} else {\n\t\t\t\t\tif (html.substring(j, j + tagend.length) === tagend) {\n\t\t\t\t\t\tif (count) {\n\t\t\t\t\t\t\tcount--;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tend = j;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (end !== -1) {\n\t\t\t\tvar tmp = html.substring(html.indexOf('>', beg) + 1, end);\n\t\t\t\thtml = html.replace(html.substring(beg, end + tagend.length), '').trim();\n\t\t\t\toutput[key] = tmp.trim();\n\t\t\t}", "\t\t}\n\t}", "\treturn output;\n};", "SP.parseXML = function(replace) {", "\tvar xml = this;\n\tvar beg = -1;\n\tvar end = 0;\n\tvar tmp = 0;\n\tvar current = [];\n\tvar obj = {};\n\tvar from = -1;", "\twhile (true) {\n\t\tbeg = xml.indexOf('<![CDATA[', beg);\n\t\tif (beg === -1)\n\t\t\tbreak;\n\t\tend = xml.indexOf(']]>', beg + 9);\n\t\txml = xml.substring(0, beg) + xml.substring(beg + 9, end).trim().encode() + xml.substring(end + 3);\n\t\tbeg += 9;\n\t}", "\tbeg = -1;\n\tend = 0;", "\twhile (true) {", "\t\tbeg = xml.indexOf('<', beg + 1);\n\t\tif (beg === -1)\n\t\t\tbreak;", "\t\tend = xml.indexOf('>', beg + 1);\n\t\tif (end === -1)\n\t\t\tbreak;", "\t\tvar el = xml.substring(beg, end + 1);\n\t\tvar c = el[1];", "\t\tif (el.substring(0, 4) === '<!--') {\n\t\t\tbeg = end + 3;\n\t\t\tcontinue;\n\t\t}", "\t\tif (c === '?' || c === '/') {", "\t\t\tvar o = current.pop();", "\t\t\tif (from === -1 || o !== el.substring(2, el.length - 1))\n\t\t\t\tcontinue;", "\t\t\tvar path = (current.length ? current.join('.') + '.' : '') + o;\n\t\t\tvar value = xml.substring(from, beg).decode();", "\t\t\tif (replace)\n\t\t\t\tpath = path.replace(REG_XMLKEY, '_');", "\t\t\tif (obj[path] === undefined)\n\t\t\t\tobj[path] = value;\n\t\t\telse if (obj[path] instanceof Array)\n\t\t\t\tobj[path].push(value);\n\t\t\telse\n\t\t\t\tobj[path] = [obj[path], value];", "\t\t\tfrom = -1;\n\t\t\tcontinue;\n\t\t}", "\t\ttmp = el.indexOf(' ');\n\t\tvar hasAttributes = true;", "\t\tif (tmp === -1) {\n\t\t\ttmp = el.length - 1;\n\t\t\thasAttributes = false;\n\t\t}", "\t\tfrom = beg + el.length;", "\t\tvar isSingle = el[el.length - 2] === '/';\n\t\tvar name = el.substring(1, tmp);", "\t\tif (!isSingle)\n\t\t\tcurrent.push(name);", "\t\tif (!hasAttributes)\n\t\t\tcontinue;", "\t\tvar match = el.match(regexpXML);\n\t\tif (!match)\n\t\t\tcontinue;", "\t\tvar attr = {};\n\t\tvar length = match.length;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar index = match[i].indexOf('\"');\n\t\t\tattr[match[i].substring(0, index - 1)] = match[i].substring(index + 1, match[i].length - 1).decode();\n\t\t}", "\t\tvar k = current.join('.') + (isSingle ? '.' + name : '') + '[]';\n\t\tif (replace)\n\t\t\tk = k.replace(REG_XMLKEY, '_');\n\t\tobj[k] = attr;\n\t}", "\treturn obj;\n};", "SP.parseJSON = function(date) {\n\ttry {\n\t\treturn JSON.parse(this, date ? jsonparser : undefined);\n\t} catch (e) {}\n};", "function parseQueryArgumentsDecode(val) {\n\ttry {\n\t\treturn decodeURIComponent(val);\n\t} catch (e) {\n\t\treturn '';\n\t}\n}", "const QUERY_ALLOWED = { '45': 1, '95': 1, 46: 1, '91': 1, '93': 1 };", "SP.parseEncoded = function() {", "\tvar str = this + '&';\n\tvar obj = {};\n\tvar key = '';\n\tvar val = '';\n\tvar is = false;\n\tvar decodev = false;\n\tvar decodek = false;\n\tvar count = 0;\n\tvar pos = 0;", "\tfor (var i = 0; i < str.length; i++) {\n\t\tvar n = str.charCodeAt(i);", "\t\tif (n === 38) {", "\t\t\tif (key) {\n\t\t\t\tif (pos < i)\n\t\t\t\t\tval += str.substring(pos, i);", "\t\t\t\tif (decodev)\n\t\t\t\t\tval = parseQueryArgumentsDecode(val);", "\t\t\t\tif (decodek)\n\t\t\t\t\tkey = parseQueryArgumentsDecode(key);", "\t\t\t\tobj[key] = val;\n\t\t\t}", "\t\t\tif (key)\n\t\t\t\tkey = '';", "\t\t\tif (val)\n\t\t\t\tval = '';", "\t\t\tpos = i + 1;\n\t\t\tis = false;\n\t\t\tdecodek = false;\n\t\t\tdecodev = false;", "\t\t\tif ((count++) >= CONF.default_request_maxkeys)\n\t\t\t\tbreak;", "\t\t} else {", "\t\t\tif (n === 61) {\n\t\t\t\tif ((i - pos) > CONF.default_request_maxkey)\n\t\t\t\t\tkey = '';\n\t\t\t\telse {\n\t\t\t\t\tif (pos < i)\n\t\t\t\t\t\tkey += str.substring(pos, i);\n\t\t\t\t\tpos = i + 1;\n\t\t\t\t\tis = true;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (!is) {\n\t\t\t\tvar can = false;\n\t\t\t\tif (n > 47 && n < 58)\n\t\t\t\t\tcan = true;\n\t\t\t\telse if ((n > 64 && n < 91) || (n > 96 && n < 123))\n\t\t\t\t\tcan = true;\n\t\t\t\telse if (QUERY_ALLOWED[n])\n\t\t\t\t\tcan = true;\n\t\t\t\tif (!can)\n\t\t\t\t\tbreak;\n\t\t\t}", "\t\t\tif (n === 43) {\n\t\t\t\tif (is)\n\t\t\t\t\tval += str.substring(pos, i) + ' ';\n\t\t\t\telse\n\t\t\t\t\tkey += str.substring(pos, i) + ' ';\n\t\t\t\tpos = i + 1;\n\t\t\t}", "\t\t\tif (n === 37) {\n\t\t\t\tif (str.charCodeAt(i + 1) === 48 && str.charCodeAt(i + 2) === 48)\n\t\t\t\t\tpos = i + 3;\n\t\t\t\telse if (is) {\n\t\t\t\t\tif (!decodev)\n\t\t\t\t\t\tdecodev = true;\n\t\t\t\t} else {\n\t\t\t\t\tif (!decodev)\n\t\t\t\t\t\tdecodek = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\treturn obj;\n};", "SP.parseUA = function(structured) {", "\tvar ua = this;", "\tif (!ua)\n\t\treturn '';", "\tvar arr = ua.match(regexpUA);\n\tvar uid = '';", "\tif (arr) {", "\t\tvar data = {};", "\t\tfor (var i = 0; i < arr.length; i++) {", "\t\t\tif (arr[i] === 'like' && arr[i + 1] === 'Gecko') {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tvar key = arr[i].toLowerCase();\n\t\t\tif (key === 'like')\n\t\t\t\tbreak;", "\t\t\tswitch (key) {\n\t\t\t\tcase 'linux':\n\t\t\t\tcase 'windows':\n\t\t\t\tcase 'mac':\n\t\t\t\tcase 'symbian':\n\t\t\t\tcase 'symbos':\n\t\t\t\tcase 'tizen':\n\t\t\t\tcase 'android':\n\t\t\t\t\tdata[arr[i]] = 2;\n\t\t\t\t\tif (key === 'tizen' || key === 'android')\n\t\t\t\t\t\tdata.Mobile = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'webos':\n\t\t\t\t\tdata.WebOS = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'media':\n\t\t\t\tcase 'center':\n\t\t\t\tcase 'tv':\n\t\t\t\tcase 'smarttv':\n\t\t\t\tcase 'smart':\n\t\t\t\t\tdata[arr[i]] = 5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'iemobile':\n\t\t\t\tcase 'mobile':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'ipad':\n\t\t\t\tcase 'ipod':\n\t\t\t\tcase 'iphone':\n\t\t\t\t\tdata.iOS = 2;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tif (key === 'ipad')\n\t\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'phone':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tizenbrowser':\n\t\t\t\tcase 'blackberry':\n\t\t\t\tcase 'mini':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'samsungbrowser':\n\t\t\t\tcase 'chrome':\n\t\t\t\tcase 'firefox':\n\t\t\t\tcase 'msie':\n\t\t\t\tcase 'opera':\n\t\t\t\tcase 'brave':\n\t\t\t\tcase 'vivaldi':\n\t\t\t\tcase 'outlook':\n\t\t\t\tcase 'safari':\n\t\t\t\tcase 'mail':\n\t\t\t\tcase 'edge':\n\t\t\t\tcase 'maxthon':\n\t\t\t\tcase 'electron':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'trident':\n\t\t\t\t\tdata.MSIE = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'opr':\n\t\t\t\t\tdata.Opera = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tablet':\n\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (data.MSIE) {\n\t\t\tdata.IE = 1;\n\t\t\tdelete data.MSIE;\n\t\t}", "\t\tif (data.WebOS || data.Android)\n\t\t\tdelete data.Linux;", "\t\tif (data.IEMobile) {\n\t\t\tif (data.Android)\n\t\t\t\tdelete data.Android;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t} else if (data.MSIE) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Edge) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Opera || data.Electron) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Chrome) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.SamsungBrowser)\n\t\t\t\tdelete data.SamsungBrowser;\n\t\t} else if (data.SamsungBrowser) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t}", "\t\tif (structured) {\n\t\t\tvar output = { os: '', browser: '', device: 'desktop' };", "\t\t\tif (data.Tablet)\n\t\t\t\toutput.device = 'tablet';\n\t\t\telse if (data.Mobile)\n\t\t\t\toutput.device = 'mobile';", "\t\t\tfor (var key in data) {\n\t\t\t\tvar val = data[key];\n\t\t\t\tswitch (val) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\toutput.browser += (output.browser ? ' ' : '') + key;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\toutput.os += (output.os ? ' ' : '') + key;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\toutput.device = 'tv';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output;\n\t\t}", "\t\tuid = Object.keys(data).join(' ');\n\t}", "\treturn uid;\n};", "SP.parseCSV = function(delimiter) {", "\tif (!delimiter)\n\t\tdelimiter = ',';", "\tvar delimiterstring = '\"';\n\tvar t = this;\n\tvar scope;\n\tvar tmp = {};\n\tvar index = 1;\n\tvar data = [];\n\tvar current = 'a';", "\tfor (var i = 0; i < t.length; i++) {\n\t\tvar c = t[i];", "\t\tif (!scope) {", "\t\t\tif (c === '\\n' || c === '\\r') {\n\t\t\t\ttmp && data.push(tmp);\n\t\t\t\tindex = 1;\n\t\t\t\tcurrent = 'a';\n\t\t\t\ttmp = null;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (c === delimiter) {\n\t\t\t\tcurrent = String.fromCharCode(97 + index);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (c === delimiterstring) {\n\t\t\t// Check escaped quotes\n\t\t\tif (scope && t[i + 1] === delimiterstring) {\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tscope = c === scope ? '' : c;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (!tmp)\n\t\t\ttmp = {};", "\t\tif (tmp[current])\n\t\t\ttmp[current] += c;\n\t\telse\n\t\t\ttmp[current] = c;\n\t}", "\ttmp && data.push(tmp);\n\treturn data;\n};", "SP.parseTerminal = function(fields, fn, skip, take) {", "\tvar lines = this.split('\\n');", "\tif (typeof(fields) === 'function') {\n\t\ttake = skip;\n\t\tskip = fn;\n\t\tfn = fields;\n\t\tparseTerminal2(lines, fn, skip, take);\n\t\treturn this;\n\t}", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tvar headers = [];\n\tvar indexer = 0;\n\tvar line = lines[0];", "\tif (!line) {\n\t\tline = lines[1];\n\t\tskip++;\n\t}", "\tif (!line) {\n\t\tline = lines[2];\n\t\tskip++;\n\t}", "\tif (!line)\n\t\treturn this;", "\tvar fieldslength = fields.length;\n\tvar tmp;", "\tfor (var i = 0, length = fieldslength; i < length; i++) {\n\t\tvar field = fields[i];", "\t\tvar beg = -1;\n\t\tvar end = -1;\n\t\tvar type = typeof(field);", "\t\tif (type === 'object' && field.test) {\n\t\t\ttmp = line.match(field);\n\t\t\tif (tmp) {\n\t\t\t\tbeg = tmp.index;\n\t\t\t\tend = beg + tmp.toString().length;\n\t\t\t} else {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t}\n\t\t} else if (type === 'string') {\n\t\t\ttmp = line.indexOf(field);\n\t\t\tif (tmp === -1) {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t} else {\n\t\t\t\tbeg = tmp;\n\t\t\t\tend = line.indexOf(' ', beg + field.length);\n\t\t\t}\n\t\t}", "\t\theaders.push({ beg: beg, end: end });\n\t}", "\tfor (var i = skip + 1, length = skip + 1 + take; i < length; i++) {", "\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;", "\t\tvar arr = [];\n\t\tvar is = false;\n\t\tvar beg;", "\t\tfor (var j = 0; j < fieldslength; j++) {\n\t\t\tvar header = headers[j];\n\t\t\tif (header.beg !== -1) {\n\t\t\t\tis = true;\n\t\t\t\tbeg = 0;", "\t\t\t\tfor (var k = header.beg; k > -1; k--) {\n\t\t\t\t\tif (line[k] === ' ') {\n\t\t\t\t\t\tbeg = k + 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tarr.push(line.substring(beg, header.end === -1 ? undefined : header.end).trim());\n\t\t\t} else\n\t\t\t\tarr.push('');\n\t\t}", "\t\tis && fn(arr, indexer++, length, i);\n\t}", "\treturn this;\n};", "function parseTerminal2(lines, fn, skip, take) {\n\tvar indexer = 0;", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tfor (var i = skip, length = skip + take; i < length; i++) {\n\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;\n\t\tvar m = line.match(regexpTERMINAL);\n\t\tm && fn(m, indexer++, length, i);\n\t}\n}", "function parseDateFormat(format, val) {", "\tvar tmp = [];\n\tvar tmpformat = [];\n\tvar prev = '';\n\tvar prevformat = '';\n\tvar allowed = { y: 1, Y: 1, M: 1, m: 1, d: 1, D: 1, H: 1, s: 1, a: 1, w: 1 };", "\tfor (var i = 0; i < format.length; i++) {", "\t\tvar c = format[i];", "\t\tif (!allowed[c])\n\t\t\tcontinue;", "\t\tif (prev !== c) {\n\t\t\tprevformat && tmpformat.push(prevformat);\n\t\t\tprevformat = c;\n\t\t\tprev = c;\n\t\t} else\n\t\t\tprevformat += c;\n\t}", "\tprev = '';", "\tfor (var i = 0; i < val.length; i++) {\n\t\tvar code = val.charCodeAt(i);\n\t\tif (code >= 48 && code <= 57)\n\t\t\tprev += val[i];\n\t}", "\tprevformat && tmpformat.push(prevformat);", "\tvar f = 0;\n\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar l = tmpformat[i].length;\n\t\ttmp.push(prev.substring(f, f + l));\n\t\tf += l;\n\t}", "\tvar dt = {};", "\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar type = tmpformat[i];\n\t\tif (tmp[i])\n\t\t\tdt[type[0]] = +tmp[i];\n\t}", "\tvar h = dt.h || dt.H;", "\tif (h != null) {\n\t\tvar ampm = val.match(REG_TIME);\n\t\tif (ampm && ampm[0].toLowerCase() === 'pm')\n\t\t\th += 12;\n\t}", "\treturn new Date((dt.y || dt.Y) || 0, (dt.M || 1) - 1, dt.d || dt.D || 0, h || 0, dt.m || 0, dt.s || 0);\n}", "SP.parseDate = function(format) {", "\tif (format)\n\t\treturn parseDateFormat(format, this);", "\tvar self = this.trim();\n\tvar lc = self.charCodeAt(self.length - 1);", "\t// Classic date\n\tif (lc === 41)\n\t\treturn new Date(self);", "\t// JSON format\n\tif (lc === 90)\n\t\treturn new Date(Date.parse(self));", "\tvar arr = self.indexOf(' ') === -1 ? self.split('T') : self.split(' ');\n\tvar index = arr[0].indexOf(':');\n\tvar length = arr[0].length;", "\tif (index !== -1) {\n\t\tvar tmp = arr[1];\n\t\tarr[1] = arr[0];\n\t\tarr[0] = tmp;\n\t}", "\tif (arr[0] === undefined)\n\t\tarr[0] = '';", "\tvar noTime = arr[1] === undefined ? true : arr[1].length === 0;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = arr[0].charCodeAt(i);\n\t\tif (c === 45 || c === 46 || (c > 47 && c < 58))\n\t\t\tcontinue;\n\t\tif (noTime)\n\t\t\treturn new Date(self);\n\t}", "\tif (arr[1] === undefined)\n\t\tarr[1] = '00:00:00';", "\tvar firstDay = arr[0].indexOf('-') === -1;", "\tvar date = (arr[0] || '').split(firstDay ? '.' : '-');\n\tvar time = (arr[1] || '').split(':');\n\tvar parsed = [];", "\tif (date.length < 4 && time.length < 2)\n\t\treturn new Date(self);", "\tindex = (time[2] || '').indexOf('.');", "\t// milliseconds\n\tif (index !== -1) {\n\t\ttime[3] = time[2].substring(index + 1);\n\t\ttime[2] = time[2].substring(0, index);\n\t} else\n\t\ttime[3] = '0';", "\tparsed.push(+date[firstDay ? 2 : 0]); // year\n\tparsed.push(+date[1]); // month\n\tparsed.push(+date[firstDay ? 0 : 2]); // day\n\tparsed.push(+time[0]); // hours\n\tparsed.push(+time[1]); // minutes\n\tparsed.push(+time[2]); // seconds\n\tparsed.push(+time[3]); // miliseconds", "\tvar def = new Date();", "\tfor (var i = 0, length = parsed.length; i < length; i++) {\n\t\tif (isNaN(parsed[i]))\n\t\t\tparsed[i] = 0;", "\t\tvar value = parsed[i];\n\t\tif (value !== 0)\n\t\t\tcontinue;", "\t\tswitch (i) {\n\t\t\tcase 0:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getFullYear();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getMonth() + 1;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getDate();\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn new Date(parsed[0], parsed[1] - 1, parsed[2], parsed[3], parsed[4] - NOW.getTimezoneOffset(), parsed[5]);\n};", "SP.parseDateExpiration = function() {\n\tvar self = this;", "\tvar arr = self.split(' ');\n\tvar dt = new Date();\n\tvar length = arr.length;", "\tfor (var i = 0; i < length; i += 2) {\n\t\tvar num = arr[i].parseInt();\n\t\tif (num === 0)\n\t\t\tcontinue;\n\t\tvar type = arr[i + 1];\n\t\tif (type)\n\t\t\tdt = dt.add(type, num);\n\t}", "\treturn dt;\n};", "var configurereplace = function(text) {\n\tvar val = CONF[text.substring(1, text.length - 1)];\n\treturn val == null ? '' : val;\n};", "SP.env = function() {\n\treturn this.replace(regexpCONFIGURE, configurereplace);\n};", "/**\n * Parse configuration from a string\n * @param {Object} def\n * @onerr {Function} error handling\n * @return {Object}\n */\nSP.parseConfig = function(def, onerr) {", "\tif (typeof(def) === 'function') {\n\t\tonerr = def;\n\t\tdef = null;\n\t}", "\tvar arr = this.split('\\n');\n\tvar length = arr.length;\n\tvar obj = def ? exports.extend({}, def) : {};\n\tvar subtype;\n\tvar name;\n\tvar index;\n\tvar value;", "\tfor (var i = 0; i < length; i++) {", "\t\tvar str = arr[i];\n\t\tif (!str || str[0] === '#' || str.substring(0, 2) === '//')\n\t\t\tcontinue;", "\t\tindex = str.indexOf(':');\n\t\tif (index === -1) {\n\t\t\tindex = str.indexOf('\\t:');\n\t\t\tif (index === -1)\n\t\t\t\tcontinue;\n\t\t}", "\t\tname = str.substring(0, index).trim();\n\t\tvalue = str.substring(index + 2).trim();", "\t\tindex = name.indexOf('(');\n\t\tif (index !== -1) {\n\t\t\tsubtype = name.substring(index + 1, name.indexOf(')')).trim().toLowerCase();\n\t\t\tname = name.substring(0, index).trim();\n\t\t} else\n\t\t\tsubtype = '';", "\t\tswitch (subtype) {\n\t\t\tcase 'string':\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t\tcase 'number':\n\t\t\tcase 'float':\n\t\t\tcase 'double':\n\t\t\tcase 'currency':\n\t\t\t\tobj[name] = value.isNumber(true) ? value.parseFloat2() : value.parseInt2();\n\t\t\t\tbreak;\n\t\t\tcase 'boolean':\n\t\t\tcase 'bool':\n\t\t\t\tobj[name] = (/true|on|1|enabled/i).test(value);\n\t\t\t\tbreak;\n\t\t\tcase 'config':\n\t\t\t\tobj[name] = CONF[value];\n\t\t\t\tbreak;\n\t\t\tcase 'eval':\n\t\t\tcase 'object':\n\t\t\tcase 'array':\n\t\t\t\ttry {\n\t\t\t\t\tobj[name] = new Function('return ' + value)();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (onerr)\n\t\t\t\t\t\tonerr(e, arr[i]);\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow new Error('A value of \"{0}\" can\\'t be converted to \"{1}\": '.format(name, subtype) + e.toString());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'json':\n\t\t\t\tobj[name] = value.parseJSON(true);\n\t\t\t\tbreak;\n\t\t\tcase 'env':\n\t\t\tcase 'environment':\n\t\t\t\tobj[name] = process.env[value];\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\tcase 'time':\n\t\t\tcase 'datetime':\n\t\t\t\tobj[name] = value.parseDate();\n\t\t\t\tbreak;\n\t\t\tcase 'random':\n\t\t\t\tobj[name] = GUID((value || '0').parseInt() || 10);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn obj;\n};", "SP.format = function() {\n\tvar arg = arguments;\n\treturn this.replace(regexpSTRINGFORMAT, function(text) {\n\t\tvar value = arg[+text.substring(1, text.length - 1)];\n\t\treturn value == null ? '' : value;\n\t});\n};", "SP.encrypt_uid = function(key) {\n\treturn exports.encrypt_uid(this, key);\n};", "SP.decrypt_uid = function(key) {\n\treturn exports.decrypt_uid(this, key);\n};", "SP.encode = function() {\n\tvar output = '';\n\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i];\n\t\tswitch (c) {\n\t\t\tcase '<':\n\t\t\t\toutput += '&lt;';\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\toutput += '&gt;';\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\toutput += '&quot;';\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\toutput += '&apos;';\n\t\t\t\tbreak;\n\t\t\tcase '&':\n\t\t\t\toutput += '&amp;';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += c;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn output;\n};", "SP.decode = function() {\n\treturn this.replace(regexpDECODE, function(s) {\n\t\tif (s.charAt(1) !== '#')\n\t\t\treturn ALPHA_INDEX[s] || s;\n\t\tvar code = s[2].toLowerCase() === 'x' ? parseInt(s.substr(3), 16) : parseInt(s.substr(2));\n\t\treturn !code || code < -32768 || code > 65535 ? '' : String.fromCharCode(code);\n\t});\n};", "SP.arg = SP.args = function(obj, encode, def) {\n\tif (typeof(encode) === 'string')\n\t\tdef = encode;\n\treturn this.replace(regexpARG, function(text) {\n\t\t// Is double?\n\t\tvar l = text[1] === '{' ? 2 : 1;\n\t\tvar val = obj[text.substring(l, text.length - l).trim()];\n\t\tif (encode && encode === 'json')\n\t\t\treturn JSON.stringify(val);\n\t\treturn val == null ? (def == null ? text : def) : encode ? encode === 'html' ? (val + '').encode() : encodeURIComponent(val + '') : val;\n\t});\n};", "SP.max = function(length, chars) {\n\tvar str = this;\n\tif (chars == null)\n\t\tchars = '...';\n\treturn str.length > length ? str.substring(0, length - chars.length) + chars : str;\n};", "SP.isJSON = function() {\n\tvar self = this;\n\tif (self.length <= 1)\n\t\treturn false;", "\tvar l = self.length - 1;\n\tvar a;\n\tvar b;\n\tvar i = 0;", "\twhile (true) {\n\t\ta = self[i++];\n\t\tif (a === ' ' || a === '\\n' || a === '\\r' || a === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\twhile (true) {\n\t\tb = self[l--];\n\t\tif (b === ' ' || b === '\\n' || b === '\\r' || b === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\treturn (a === '\"' && b === '\"') || (a === '[' && b === ']') || (a === '{' && b === '}') || (a.charCodeAt(0) > 47 && b.charCodeAt(0) < 57);\n};", "SP.isURL = function() {\n\treturn this.length <= 7 ? false : DEF.validators.url.test(this);\n};", "SP.isZIP = function() {\n\treturn DEF.validators.zip.test(this);\n};", "SP.isEmail = function() {\n\treturn this.length <= 4 ? false : DEF.validators.email.test(this);\n};", "SP.isPhone = function() {\n\treturn this.length < 6 ? false : DEF.validators.phone.test(this);\n};", "SP.isBase64 = function(isdata) {", "\tvar str = this;\n\tvar count = str.length;", "\tif (isdata) {\n\t\tvar index = str.indexOf(';base64,');\n\t\tif (index !== -1)\n\t\t\tcount -= (index + 8);\n\t}", "\treturn count % 4 === 0 && (isdata ? regexpBASE64_2.test(str) : regexpBASE64.test(str));\n};", "SP.isUID = function() {\n\tvar str = this;", "\tif (str.length < 12 && str.length > 25)\n\t\treturn false;", "\tvar is = DEF.validators.uid.test(str);\n\tif (is) {", "\t\tvar sum;\n\t\tvar beg;\n\t\tvar end;\n\t\tvar e = str[str.length - 1];", "\t\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = +str[str.length - 3];\n\t\t\tend = str.length - 5;\n\t\t\tvar tmp = e === 'c' || e === 'd' ? (+str.substring(beg, end)) : parseInt(str.substring(beg, end), 16);\n\t\t\treturn sum === (tmp % 2 ? '1' : '0');\n\t\t} else if (e === 'a') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = 6;\n\t\t\tend = str.length - 4;\n\t\t} else {\n\t\t\tsum = str[str.length - 1];\n\t\t\tbeg = 10;\n\t\t\tend = str.length - 4;\n\t\t}", "\t\twhile (beg++ < end) {\n\t\t\tif (str[beg] !== '0') {\n\t\t\t\tif (((+str.substring(beg, end)) % 2 ? '1' : '0') === sum)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n};", "SP.parseUID = function() {\n\tvar self = this;\n\tvar obj = {};\n\tvar hash;\n\tvar e = self[self.length - 1];", "\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\tend = +self[self.length - 3];\n\t\tvar ticks = ((e === 'b' ? (+self.substring(0, end)) : parseInt(self.substring(0, end), e=== 'd' ? 36 : 16)) * 1000 * 60) + 1580511600000; // 1.1.2020\n\t\tobj.date = new Date(ticks);\n\t\tbeg = end;\n\t\tend = self.length - 5;\n\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else if (e === 'a') {\n\t\tvar ticks = ((+self.substring(0, 6)) * 1000 * 60) + 1548975600000; // old 1.1.2019\n\t\tobj.date = new Date(ticks);\n\t\tbeg = 7;\n\t\tend = self.length - 4;\n\t\thash = +self.substring(end + 2, end + 3);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else {\n\t\tvar y = self.substring(0, 2);\n\t\tvar M = self.substring(2, 4);\n\t\tvar d = self.substring(4, 6);\n\t\tvar H = self.substring(6, 8);\n\t\tvar m = self.substring(8, 10);", "\t\tobj.date = new Date(+('20' + y), (+M) - 1, +d, +H, +m, 0);", "\t\tvar beg = 0;\n\t\tvar end = 0;\n\t\tvar index = 10;", "\t\twhile (true) {", "\t\t\tvar c = self[index];", "\t\t\tif (!c)\n\t\t\t\tbreak;", "\t\t\tif (!beg && c !== '0')\n\t\t\t\tbeg = index;", "\t\t\tif (c.charCodeAt(0) > 96) {\n\t\t\t\tend = index;\n\t\t\t\tbreak;\n\t\t\t}", "\t\t\tindex++;\n\t\t}", "\t\tobj.century = self.substring(end + 4);", "\t\tif (obj.century) {\n\t\t\tobj.century = 20 + (+obj.century);\n\t\t\tobj.date.setYear(obj.date.getFullYear() + 100);\n\t\t} else\n\t\t\tobj.century = 21;", "\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.hash = self.substring(end, end + 3);\n\t}", "\tobj.index = +self.substring(beg, end);\n\tobj.valid = (obj.index % 2 ? 1 : 0) === hash;\n\treturn obj;\n};", "SP.parseENV = function() {", "\tvar arr = this.split(regexpLINES);\n\tvar obj = {};", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar line = arr[i];\n\t\tif (!line || line.substring(0, 2) === '//' || line[0] === '#')\n\t\t\tcontinue;", "\t\tvar index = line.indexOf('=');\n\t\tif (index === -1)\n\t\t\tcontinue;", "\t\tvar key = line.substring(0, index);\n\t\tvar val = line.substring(index + 1).replace(/\\\\n/g, '\\n');\n\t\tvar end = val.length - 1;", "\t\tif ((val[0] === '\"' && val[end] === '\"') || (val[0] === '\\'' && val[end] === '\\''))\n\t\t\tval = val.substring(1, end);\n\t\telse\n\t\t\tval = val.trim();", "\t\tobj[key] = val;\n\t}", "\treturn obj;\n};", "SP.parseInt = function(def) {\n\tvar str = this.trim();\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.parseInt2 = function(def) {\n\tvar num = this.match(regexpINTEGER);\n\treturn num ? +num[0] : (def === undefined ? 0 : def);\n};", "SP.parseFloat2 = function(def) {\n\tvar num = this.match(regexpFLOAT);\n\treturn num ? +num[0].toString().replace(/,/g, '.') : (def === undefined ? 0 : def);\n};", "SP.parseBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn self === 'true' || self === '1' || self === 'on';\n};", "SP.parseFloat = function(def) {\n\tvar str = this.trim();\n\tif (str.indexOf(',') !== -1)\n\t\tstr = str.replace(',', '.');\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.capitalize = function(first) {", "\tif (first)\n\t\treturn (this[0] || '').toUpperCase() + this.substring(1);", "\tvar builder = '';\n\tvar c;", "\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i - 1];\n\t\tif (!c || (c === ' ' || c === '\\t' || c === '\\n'))\n\t\t\tc = this[i].toUpperCase();\n\t\telse\n\t\t\tc = this[i];\n\t\tbuilder += c;\n\t}", "\treturn builder;\n};", "SP.toUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tvar c = this[i].charCodeAt(0);\n\t\tif(c > 126 || c < 32)\n\t\t\toutput += '\\\\u' + ('000' + c.toString(16)).substr(-4);\n\t\telse\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.fromUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tif (this[i] === '\\\\' && this[i + 1] === 'u') {\n\t\t\toutput += String.fromCharCode(parseInt(this[i + 2] + this[i + 3] + this[i + 4] + this[i + 5], 16));\n\t\t\ti += 5;\n\t\t} else\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.sha1 = function(salt) {\n\tvar hash = Crypto.createHash('sha1');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha256 = function(salt) {\n\tvar hash = Crypto.createHash('sha256');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha512 = function(salt) {\n\tvar hash = Crypto.createHash('sha512');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.md5 = function(salt) {\n\tvar hash = Crypto.createHash('md5');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.toSearch = function() {\n\tvar str = this.replace(regexpSEARCH, '').trim().toLowerCase().toASCII();\n\tvar buf = [];\n\tvar prev = '';\n\tfor (var i = 0, length = str.length; i < length; i++) {\n\t\tvar c = str[i];\n\t\tif (c === 'y')\n\t\t\tc = 'i';\n\t\tif (c === prev)\n\t\t\tcontinue;\n\t\tprev = c;\n\t\tbuf.push(c);\n\t}", "\treturn buf.join('');\n};", "SP.toKeywords = SP.keywords = function(forSearch, alternative, max_count, max_length, min_length) {\n\treturn exports.keywords(this, forSearch, alternative, max_count, max_length, min_length);\n};", "function checksum(val) {\n\tvar sum = 0;\n\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);\n\treturn sum;\n}", "SP.encrypt = function(key, isUnique, secret) {\n\tvar str = '0' + this;\n\tvar data_count = str.length;\n\tvar key_count = key.length;\n\tvar random = isUnique ? exports.random(120) + 40 : 65;\n\tvar count = data_count + (random % key_count);\n\tvar values = [];\n\tvar index = 0;", "\tvalues[0] = String.fromCharCode(random);", "\tvar counter = this.length + key.length;", "\tfor (var i = count - 1; i > 0; i--) {\n\t\tindex = str.charCodeAt(i % data_count);\n\t\tvalues[i] = String.fromCharCode(index ^ (key.charCodeAt(i % key_count) ^ random));\n\t}", "\tstr = Buffer.from(counter + '=' + values.join(''), ENCODING).toString('hex');\n\tvar sum = 0;", "\tfor (var i = 0; i < str.length; i++)\n\t\tsum += str.charCodeAt(i);", "\treturn (sum + checksum((secret || CONF.secret) + key)) + '-' + str;\n};", "SP.decrypt = function(key, secret) {", "\tvar index = this.indexOf('-');\n\tif (index === -1)\n\t\treturn null;", "\tvar cs = +this.substring(0, index);\n\tif (!cs || isNaN(cs))\n\t\treturn null;", "\tvar hash = this.substring(index + 1);\n\tvar sum = checksum((secret || CONF.secret) + key);\n\tfor (var i = 0; i < hash.length; i++)\n\t\tsum += hash.charCodeAt(i);", "\tif (sum !== cs)\n\t\treturn null;", "\tvar values = Buffer.from(hash, 'hex').toString(ENCODING);\n\tvar index = values.indexOf('=');\n\tif (index === -1)\n\t\treturn null;", "\tvar counter = +values.substring(0, index);\n\tif (isNaN(counter))\n\t\treturn null;", "\tvalues = values.substring(index + 1);", "\tvar count = values.length;\n\tvar random = values.charCodeAt(0);\n\tvar key_count = key.length;\n\tvar data_count = count - (random % key_count);\n\tvar decrypt_data = [];", "\tfor (var i = data_count - 1; i > 0; i--) {\n\t\tindex = values.charCodeAt(i) ^ (random ^ key.charCodeAt(i % key_count));\n\t\tdecrypt_data[i] = String.fromCharCode(index);\n\t}", "\tvar val = decrypt_data.join('');\n\treturn counter !== (val.length + key.length) ? null : val;\n};", "exports.encrypt_data = function(value, key, encode) {", "\tvar builder = [];\n\tvar index = 0;\n\tvar length = key.length;", "\tfor (var i = 0; i < value.length; i++) {", "\t\tif (SKIPBODYENCRYPTOR[value[i]]) {\n\t\t\tbuilder.push(value[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (index === length)\n\t\t\tindex = 0;", "\t\tvar a = value.charCodeAt(i) + 2;\n\t\tvar b = key.charCodeAt(index++);\n\t\tvar t = (a + b).toString(36);\n\t\tbuilder.push(t.length + t);\n\t}", "\tvar mask = Buffer.alloc(4);\n\tmask.writeInt32BE((Math.random() * 214748364) >> 0);", "\tvar buffer = Buffer.from(builder.join(''));\n\tfor (var i = 0; i < buffer.length; i++)\n\t\tbuffer[i] = buffer[i] ^ mask[i % 4];", "\tvar buf = Buffer.concat([mask, buffer]);\n\treturn encode === 'buffer' ? buf : buf.toString(encode || 'base64');\n};", "exports.decrypt_data = function(value, key, encode) {", "\ttry {\n\t\tvalue = value instanceof Buffer ? value : Buffer.from(value, encode || 'base64');\n\t} catch (e) {\n\t\treturn null;\n\t}", "\tvar index = 0;\n\tvar length = key.length;\n\tvar builder = [];\n\tvar mask = Buffer.alloc(4);\n\tvar buffer = Buffer.alloc(value.length - 4);\n\tmask.writeInt32BE(value.readInt32BE(0));", "\tfor (var i = 4; i < value.length; i++)\n\t\tbuffer[i - 4] = value[i] ^ mask[i % 4];", "\tvalue = buffer.toString('utf8');", "\tfor (var i = 0; i < value.length; i++) {", "\t\tvar c = value[i];", "\t\tif (SKIPBODYENCRYPTOR[c]) {\n\t\t\tbuilder.push(c);\n\t\t\tcontinue;\n\t\t}", "\t\tif (index === length)\n\t\t\tindex = 0;", "\t\tvar l = +value.charAt(i);\n\t\tvar code = parseInt(value.substring(i + 1, i + 1 + l), 36);\n\t\tvar b = key.charCodeAt(index++);\n\t\tbuilder.push(String.fromCharCode(code - b - 2));\n\t\ti += l;\n\t}", "\treturn builder.join('');\n};", "exports.encrypt_uid = function(val, key) {", "\tvar num = typeof(val) === 'number';\n\tvar sum = 0;", "\tif (!key)\n\t\tkey = CONF.secret;", "\tval = val + '';", "\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);", "\tfor (var i = 0; i < key.length; i++)\n\t\tsum += key.charCodeAt(i);", "\treturn (num ? 'n' : 'x') + (CONF.secret_uid + val + sum + key).crc32(true).toString(32) + 'x' + val;\n};", "exports.decrypt_uid = function(val, key) {\n\tvar num = val[0] === 'n';\n\tvar raw = val.substring(val.indexOf('x', 1) + 1);", "\tif (num)\n\t\traw = +raw;", "\treturn exports.encrypt_uid(raw, key) === val ? raw : null;\n};", "exports.encrypt_crypto = function(type, key, value) {\n\tif (!F.temporary.keys[key])\n\t\tF.temporary.keys[key] = Buffer.from(key);\n\tvar cipher = Crypto.createCipheriv(type, F.temporary.keys[key], CONF.default_crypto_iv);\n\tCONCAT[0] = cipher.update(value);\n\tCONCAT[1] = cipher.final();\n\treturn Buffer.concat(CONCAT);\n};", "exports.decrypt_crypto = function(type, key, value) {\n\tif (!F.temporary.keys[key])\n\t\tF.temporary.keys[key] = Buffer.from(key);\n\tvar decipher = Crypto.createDecipheriv(type, F.temporary.keys[key], CONF.default_crypto_iv);\n\ttry {\n\t\tCONCAT[0] = decipher.update(value);\n\t\tCONCAT[1] = decipher.final();\n\t\treturn Buffer.concat(CONCAT);\n\t} catch (e) {}\n};", "SP.base64ToFile = function(filename, callback) {\n\tvar self = this;\n\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;\n\tFs.writeFile(filename, self.substring(index), 'base64', callback || NOOP);\n\treturn this;\n};", "SP.base64ToBuffer = function() {\n\tvar self = this;", "\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;", "\treturn Buffer.from(self.substring(index), 'base64');\n};", "SP.base64ContentType = function() {\n\tvar self = this;\n\tvar index = self.indexOf(';');\n\treturn index === -1 ? '' : self.substring(5, index);\n};", "var toascii = c => DIACRITICSMAP[c] || c;", "SP.toASCII = function() {\n\treturn this.replace(regexpDiacritics, toascii);\n};", "SP.indent = function(max, c) {\n\tvar plus = '';\n\tif (c === undefined)\n\t\tc = ' ';\n\twhile (max--)\n\t\tplus += c;\n\treturn plus + this;\n};", "SP.isNumber = function(isDecimal) {", "\tvar self = this;\n\tvar length = self.length;", "\tif (!length)\n\t\treturn false;", "\tisDecimal = isDecimal || false;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar ascii = self.charCodeAt(i);", "\t\tif (isDecimal) {\n\t\t\tif (ascii === 44 || ascii === 46) {\n\t\t\t\tisDecimal = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ascii < 48 || ascii > 57)\n\t\t\treturn false;\n\t}", "\treturn true;\n};", "if (!SP.padLeft) {\n\tSP.padLeft = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself = c + self;\n\t\treturn self;\n\t};\n}", "\nif (!SP.padRight) {\n\tSP.padRight = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself += c;\n\t\treturn self;\n\t};\n}", "SP.insert = function(index, value) {\n\tvar str = this;\n\tvar a = str.substring(0, index);\n\tvar b = value.toString() + str.substring(index);\n\treturn a + b;\n};", "/**\n * Create a link from String\n * @param {Number} max A maximum length, default: 60 and optional.\n * @return {String}\n */\nSP.slug = function(max) {\n\tmax = max || 60;", "\tvar self = this.trim().toLowerCase().toASCII();\n\tvar builder = '';\n\tvar length = self.length;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = self[i];\n\t\tvar code = self.charCodeAt(i);", "\t\tif (code > 540){\n\t\t\tbuilder = '';\n\t\t\tbreak;\n\t\t}", "\t\tif (builder.length >= max)\n\t\t\tbreak;", "\t\tif (code > 31 && code < 48) {\n\t\t\tif (builder[builder.length - 1] !== '-')\n\t\t\t\tbuilder += '-';\n\t\t\tcontinue;\n\t\t}", "\t\tif ((code > 47 && code < 58) || (code > 94 && code < 123))\n\t\t\tbuilder += c;\n\t}", "\tif (builder.length > 1) {\n\t\tlength = builder.length - 1;\n\t\treturn builder[length] === '-' ? builder.substring(0, length) : builder;\n\t} else if (!length)\n\t\treturn '';", "\tlength = self.length;\n\tself = self.replace(/\\s/g, '');\n\tbuilder = self.crc32(true).toString(36) + '';\n\treturn self[0].charCodeAt(0).toString(32) + builder + self[self.length - 1].charCodeAt(0).toString(32) + length;\n};", "SP.pluralize = function(zero, one, few, other) {\n\treturn this.parseInt().pluralize(zero, one, few, other);\n};", "SP.isBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn (self === 'true' || self === 'false') ? true : false;\n};", "/**\n* Remove all Html Tags from a string\n* @return {string}\n*/\nSP.removeTags = function() {\n\treturn this.replace(regexpTags, '');\n};", "NP.between = function(condition, otherwise) {", "\tvar val = this;", "\tfor (var key in condition) {", "\t\tvar arr = key.split('-');", "\t\tvar a = arr[0] ? +arr[0] : null;\n\t\tvar b = arr[1] ? +arr[1] : null;", "\t\tif (a != null && b !== null) {\n\t\t\tif (val >= a && val <= b)\n\t\t\t\treturn condition[key];\n\t\t} else if (a != null) {\n\t\t\tif (val >= a)\n\t\t\t\treturn condition[key];\n\t\t} else if (b != null)\n\t\t\tif (val <= b)\n\t\t\t\treturn condition[key];\n\t}", "\treturn otherwise;\n};", "NP.floor = function(decimals) {\n\treturn Math.floor(this * Math.pow(10, decimals)) / Math.pow(10, decimals);\n};", "NP.fixed = function(decimals) {\n\treturn +this.toFixed(decimals);\n};", "NP.padLeft = function(max, c) {\n\treturn this.toString().padLeft(max, c || '0');\n};", "NP.padRight = function(max, c) {\n\treturn this.toString().padRight(max, c || '0');\n};", "NP.round = function(precision) {\n\tvar m = Math.pow(10, precision) || 1;\n\treturn Math.round(this * m) / m;\n};", "NP.currency = function(currency, a, b, c) {\n\tvar curr = DEF.currencies[currency || 'default'];\n\treturn curr ? curr(this, a, b, c) : this.format(2);\n};", "/**\n * Async decrements\n * @param {Function(index, next)} fn\n * @param {Function} callback\n * @return {Number}\n */\nNP.async = function(fn, callback) {\n\tvar number = this;\n\tif (number)\n\t\tfn(number--, () => setImmediate(() => number.async(fn, callback)));\n\telse\n\t\tcallback && callback();\n\treturn number;\n};", "/**\n * Format number\n * @param {Number} decimals Maximum decimal numbers\n * @param {String} separator Number separator, default ' '\n * @param {String} separatorDecimal Decimal separator, default '.' if number separator is ',' or ' '.\n * @return {String}\n */\nNP.format = function(decimals, separator, separatorDecimal) {", "\tvar self = this;\n\tvar num = self.toString();\n\tvar dec = '';\n\tvar output = '';\n\tvar minus = num[0] === '-' ? '-' : '';\n\tif (minus)\n\t\tnum = num.substring(1);", "\tvar index = num.indexOf('.');", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = separator;\n\t\tseparator = decimals;\n\t\tdecimals = tmp;\n\t}", "\tif (separator === undefined)\n\t\tseparator = ' ';", "\tif (index !== -1) {\n\t\tdec = num.substring(index + 1);\n\t\tnum = num.substring(0, index);\n\t}", "\tindex = -1;\n\tfor (var i = num.length - 1; i >= 0; i--) {\n\t\tindex++;\n\t\tif (index > 0 && index % 3 === 0)\n\t\t\toutput = separator + output;\n\t\toutput = num[i] + output;\n\t}", "\tif (decimals || dec.length) {\n\t\tif (dec.length > decimals)\n\t\t\tdec = dec.substring(0, decimals || 0);\n\t\telse\n\t\t\tdec = dec.padRight(decimals || 0, '0');\n\t}", "\tif (dec.length && separatorDecimal === undefined)\n\t\tseparatorDecimal = separator === '.' ? ',' : '.';", "\treturn minus + output + (dec.length ? separatorDecimal + dec : '');\n};", "NP.add = function(value, decimals) {", "\tif (value == null)\n\t\treturn this;", "\tif (typeof(value) === 'number')\n\t\treturn this + value;", "\tvar first = value.charCodeAt(0);\n\tvar is = false;", "\tif (first < 48 || first > 57) {\n\t\tis = true;\n\t\tvalue = value.substring(1);\n\t}", "\tvar length = value.length;\n\tvar num;", "\tif (value[length - 1] === '%') {\n\t\tvalue = value.substring(0, length - 1);\n\t\tif (is) {\n\t\t\tvar val = value.parseFloat();\n\t\t\tswitch (first) {\n\t\t\t\tcase 42:\n\t\t\t\t\tnum = this * ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 43:\n\t\t\t\t\tnum = this + ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 45:\n\t\t\t\t\tnum = this - ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 47:\n\t\t\t\t\tnum = this / ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t} else {\n\t\t\tnum = (this / 100) * value.parseFloat();\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t}", "\t} else\n\t\tnum = value.parseFloat();", "\tswitch (first) {\n\t\tcase 42:\n\t\t\tnum = this * num;\n\t\t\tbreak;\n\t\tcase 43:\n\t\t\tnum = this + num;\n\t\t\tbreak;\n\t\tcase 45:\n\t\t\tnum = this - num;\n\t\t\tbreak;\n\t\tcase 47:\n\t\t\tnum = this / num;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tnum = this;\n\t\t\tbreak;\n\t}", "\tif (decimals !== undefined)\n\t\treturn num.floor(decimals);", "\treturn num;\n};", "NP.pluralize = function(zero, one, few, other) {", "\tvar num = this;\n\tvar value = '';", "\tif (num == 0)\n\t\tvalue = zero || '';\n\telse if (num == 1)\n\t\tvalue = one || '';\n\telse if (num > 1 && num < 5)\n\t\tvalue = few || '';\n\telse\n\t\tvalue = other;", "\tvar beg = value.indexOf('#');\n\tif (beg === -1)\n\t\treturn value;", "\tvar end = value.lastIndexOf('#');\n\tvar format = value.substring(beg, end + 1);\n\treturn num.format(format) + value.replace(format, '');\n};", "NP.hex = function(length) {\n\tvar str = this.toString(16).toUpperCase();\n\twhile(str.length < length)\n\t\tstr = '0' + str;\n\treturn str;\n};", "NP.VAT = function(percentage, decimals, includedVAT) {\n\tvar num = this;\n\tvar type = typeof(decimals);", "\tif (type === 'boolean') {\n\t\tvar tmp = includedVAT;\n\t\tincludedVAT = decimals;\n\t\tdecimals = tmp;\n\t\ttype = typeof(decimals);\n\t}", "\tif (type === 'undefined')\n\t\tdecimals = 2;", "\treturn !percentage || !num ? num.round(decimals) : includedVAT ? (num / ((percentage / 100) + 1)).round(decimals) : (num * ((percentage / 100) + 1)).round(decimals);\n};", "NP.discount = function(percentage, decimals) {\n\tvar num = this;\n\tif (decimals === undefined)\n\t\tdecimals = 2;\n\treturn !num || !percentage ? num : (num - (num / 100) * percentage).floor(decimals);\n};", "NP.parseDate = function(plus) {\n\treturn new Date(this + (plus || 0));\n};", "if (!NP.toRad) {\n\tNP.toRad = function () {\n\t\treturn this * Math.PI / 180;\n\t};\n}", "NP.filesize = function(decimals, type) {", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = type;\n\t\ttype = decimals;\n\t\tdecimals = tmp;\n\t}", "\tvar value;", "\t// this === bytes\n\tswitch (type) {\n\t\tcase 'bytes':\n\t\t\tvalue = this;\n\t\t\tbreak;\n\t\tcase 'KB':\n\t\t\tvalue = this / 1024;\n\t\t\tbreak;\n\t\tcase 'MB':\n\t\t\tvalue = filesizehelper(this, 2);\n\t\t\tbreak;\n\t\tcase 'GB':\n\t\t\tvalue = filesizehelper(this, 3);\n\t\t\tbreak;\n\t\tcase 'TB':\n\t\t\tvalue = filesizehelper(this, 4);\n\t\t\tbreak;\n\t\tdefault:", "\t\t\ttype = 'bytes';\n\t\t\tvalue = this;", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'KB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'MB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'GB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'TB';\n\t\t\t}", "\t\t\tbreak;\n\t}", "\ttype = ' ' + type;\n\treturn (decimals === undefined ? value.format(2).replace('.00', '') : value.format(decimals)) + type;\n};", "function filesizehelper(number, count) {\n\twhile (count--) {\n\t\tnumber = number / 1024;\n\t\tif (number.toFixed(3) === '0.000')\n\t\t\treturn 0;\n\t}\n\treturn number;\n}", "var AP = Array.prototype;", "/**\n * Take items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.take = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tfor (var i = 0; i < self.length; i++) {\n\t\tarr.push(self[i]);\n\t\tif (arr.length >= count)\n\t\t\treturn arr;\n\t}\n\treturn arr;\n};", "/**\n * First item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.first = function(def) {\n\tvar item = this[0];\n\treturn item === undefined ? def : item;\n};", "/**\n * Create object from Array\n * @param {String} name Optional, property name.\n * @return {Object}\n */\nAP.toObject = function(name) {", "\tvar self = this;\n\tvar obj = {};", "\tfor (var i = 0; i < self.length; i++) {\n\t\tvar item = self[i];\n\t\tif (name)\n\t\t\tobj[item[name]] = item;\n\t\telse\n\t\t\tobj[item] = true;\n\t}", "\treturn obj;\n};", "/**\n * Last item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.last = function(def) {\n\tvar item = this[this.length - 1];\n\treturn item === undefined ? def : item;\n};", "AP.quicksort = function(sort) {", "\tvar self = this;\n\tif (self.length < 2)\n\t\treturn self;", "\t// Backward compatibility\n\tif (!sort) {\n\t\tself.sort(COMPARER);\n\t\treturn self;\n\t}", "\t// Backward compatibility\n\tif (sort === true) {\n\t\tself.sort(COMPARER_DESC);\n\t\treturn self;\n\t}", "\tif (arguments[1] === true || arguments[1] === 2)\n\t\tsort += '_desc';", "\tshellsort(self, exports.sortcomparer(sort));\n\treturn self;\n};", "exports.sortcomparer = function(sort) {", "\tvar key = 'sort_' + sort;\n\tvar meta = F.temporary.other[key];", "\tif (!meta) {\n\t\tmeta = [];\n\t\tsort = sort.replace(/\\s/g, '').split(',');\n\t\tfor (var i = 0; i < sort.length; i++) {\n\t\t\tvar tmp = sort[i].split((/_(desc|asc)/));\n\t\t\tvar obj = { name: tmp[0], type: null, desc: tmp[1] === 'desc' };\n\t\t\tif (tmp[0].indexOf('.') !== -1)\n\t\t\t\tobj.read = new Function('val', 'return val.' + tmp[0].replace(/\\./g, '?.'));\n\t\t\tmeta.push(obj);\n\t\t}\n\t\tF.temporary.other[key] = meta;\n\t}", "\treturn function(a, b) {\n\t\tfor (var i = 0; i < meta.length; i++) {\n\t\t\tvar col = meta[i];\n\t\t\tvar va = col.read ? col.read(a) : a[col.name];\n\t\t\tvar vb = col.read ? col.read(b) : b[col.name];", "\t\t\tif (!col.type) {\n\t\t\t\tif (va != null)\n\t\t\t\t\tcol.type = va instanceof Date ? 4 : typeof(va);\n\t\t\t\telse if (vb != null)\n\t\t\t\t\tcol.type = vb instanceof Date ? 4: typeof(vb);\n\t\t\t\tswitch (col.type) {\n\t\t\t\t\tcase 'string':\n\t\t\t\t\t\tcol.type = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'number':\n\t\t\t\t\t\tcol.type = 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'boolean':\n\t\t\t\t\t\tcol.type = 3;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'object':\n\t\t\t\t\t\tcol.type = 5;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (col.type) {\n\t\t\t\tswitch (col.type) {", "\t\t\t\t\tcase 1:\n\t\t\t\t\t\ttmp = col.desc ? COMPARER_DESC(va, vb) : COMPARER(va, vb);\n\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;\n\t\t\t\t\t\tbreak;", "\t\t\t\t\tcase 2:\n\t\t\t\t\t\ttmp = va > vb ? (col.desc ? -1 : 1) : va < vb ? (col.desc ? 1 : -1) : 0;\n\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;\n\t\t\t\t\t\tbreak;", "\t\t\t\t\tcase 3:\n\t\t\t\t\t\ttmp = va === true && vb === false ? (col.desc ? -1 : 1) : va === false && vb === true ? (col.desc ? 1 : -1) : 0;\n\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;\n\t\t\t\t\t\tbreak;", "\t\t\t\t\tcase 4:", "\t\t\t\t\t\tif (!va && !vb)\n\t\t\t\t\t\t\tbreak;", "\t\t\t\t\t\tif (va && !vb)\n\t\t\t\t\t\t\treturn col.desc ? -1 : 1;", "\t\t\t\t\t\tif (!va && vb)\n\t\t\t\t\t\t\treturn col.desc ? 1 : -1;", "\t\t\t\t\t\tif (!va.getTime)\n\t\t\t\t\t\t\tva = new Date(va);", "\t\t\t\t\t\tif (!vb.getTime)\n\t\t\t\t\t\t\tvb = new Date(vb);", "\t\t\t\t\t\ttmp = va > vb ? (col.desc ? -1 : 1) : va < vb ? (col.desc ? 1 : -1) : 0;", "\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;", "\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\treturn 0;\n\t\t}", "\t\treturn 0;\n\t};\n};", "AP.trim = function() {\n\tvar self = this;\n\tvar output = [];\n\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tif (typeof(self[i]) === 'string')\n\t\t\tself[i] = self[i].trim();\n\t\tself[i] && output.push(self[i]);\n\t}\n\treturn output;\n};", "/**\n * Skip items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.skip = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tvar length = self.length;\n\tfor (var i = 0; i < length; i++)\n\t\ti >= count && arr.push(self[i]);\n\treturn arr;\n};", "/**\n * Find items in Array\n * @param {Function(item, index) or String/Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.findAll = function(cb, value) {", "\tvar self = this;\n\tvar selected = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tcb.call(self, self[i], i) && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] === value && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] === cb && selected.push(self[i]);\n\t}", "\treturn selected;\n};", "AP.findValue = function(cb, value, path, def) {\n\tvar index = this.findIndex(cb, value);\n\tif (index !== -1) {\n\t\tvar item = this[index][path];\n\t\treturn item == null ? def : item;\n\t}\n\treturn def;\n};", "AP.findItem = function(cb, value) {\n\tvar self = this;\n\tvar index = self.findIndex(cb, value);\n\tif (index === -1)\n\t\treturn null;\n\treturn self[index];\n};", "AP.findIndex = function(cb, value) {", "\tvar self = this;\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tif (cb.call(self, self[i], i))\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tif (self[i] && self[i][cb] === value)\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (self[i] === cb)\n\t\t\treturn i;\n\t}", "\treturn -1;\n};", "/**\n * Remove items from Array\n * @param {Function(item, index) or Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.remove = function(cb, value) {", "\tvar self = this;\n\tvar arr = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\t!cb.call(self, self[i], i) && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] !== value && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] !== cb && arr.push(self[i]);\n\t}\n\treturn arr;\n};", "AP.wait = function(onItem, callback, thread, tmp) {", "\tvar self = this;\n\tvar init = false;", "\t// INIT\n\tif (!tmp) {", "\t\tif (typeof(callback) !== 'function') {\n\t\t\tthread = callback;\n\t\t\tcallback = null;\n\t\t}", "\t\ttmp = {};\n\t\ttmp.pending = 0;\n\t\ttmp.index = 0;\n\t\ttmp.thread = thread;", "\t\t// thread === Boolean then array has to be removed item by item", "\t\tinit = true;\n\t}", "\tvar item = thread === true ? self.shift() : self[tmp.index++];\n\tif (item === undefined) {\n\t\tif (!tmp.pending) {\n\t\t\tcallback && callback();\n\t\t\ttmp.cancel = true;\n\t\t}\n\t\treturn self;\n\t}", "\ttmp.pending++;\n\tonItem.call(self, item, () => setImmediate(next_wait, self, onItem, callback, thread, tmp), tmp.index);", "\tif (!init || tmp.thread === 1)\n\t\treturn self;", "\tfor (var i = 1; i < tmp.thread; i++)\n\t\tself.wait(onItem, callback, 1, tmp);", "\treturn self;\n};", "function next_wait(self, onItem, callback, thread, tmp) {\n\ttmp.pending--;\n\tself.wait(onItem, callback, thread, tmp);\n}", "/**\n * Creates a function async list\n * @param {Function} callback Optional\n * @return {Array}\n */\nAP.async = function(thread, callback, pending) {", "\tvar self = this;", "\tif (typeof(thread) === 'function') {\n\t\tcallback = thread;\n\t\tthread = 1;\n\t} else if (thread === undefined)\n\t\tthread = 1;", "\tif (pending === undefined)\n\t\tpending = 0;", "\tvar item = self.shift();\n\tif (item === undefined) {\n\t\tif (!pending) {\n\t\t\tpending = undefined;\n\t\t\tcallback && callback();\n\t\t}\n\t\treturn self;\n\t}", "\tfor (var i = 0; i < thread; i++) {", "\t\tif (i)\n\t\t\titem = self.shift();", "\t\tpending++;\n\t\titem(function() {\n\t\t\tsetImmediate(function() {\n\t\t\t\tpending--;\n\t\t\t\tself.async(1, callback, pending);\n\t\t\t});\n\t\t});\n\t}", "\treturn self;\n};", "// Fisher-Yates shuffle\nAP.random = function(item) {\n\tif (item)\n\t\treturn this[exports.random(this.length - 1)];\n\tfor (var i = this.length - 1; i > 0; i--) {\n\t\tvar j = Math.floor(Math.random() * (i + 1));\n\t\tvar temp = this[i];\n\t\tthis[i] = this[j];\n\t\tthis[j] = temp;\n\t}\n\treturn this;\n};", "AP.limit = function(max, fn, callback, index) {", "\tif (index === undefined)\n\t\tindex = 0;", "\tvar current = [];\n\tvar self = this;\n\tvar length = index + max;", "\tfor (var i = index; i < length; i++) {\n\t\tvar item = self[i];", "\t\tif (item !== undefined) {\n\t\t\tcurrent.push(item);\n\t\t\tcontinue;\n\t\t}", "\t\tif (!current.length) {\n\t\t\tcallback && callback();\n\t\t\treturn self;\n\t\t}", "\t\tfn(current, () => callback && callback(), index, index + max);\n\t\treturn self;\n\t}", "\tif (!current.length) {\n\t\tcallback && callback();\n\t\treturn self;\n\t}", "\tfn(current, function() {\n\t\tif (length < self.length)\n\t\t\tself.limit(max, fn, callback, length);\n\t\telse\n\t\t\tcallback && callback();\n\t}, index, index + max);", "\treturn self;\n};", "ArrayBuffer.prototype.toBuffer = function() {\n\tvar buf = new Buffer(this.byteLength);\n\tvar view = new Uint8Array(this);\n\tfor (var i = 0; i < buf.length; ++i)\n\t\tbuf[i] = view[i];\n\treturn buf;\n};", "function FileList() {\n\tthis.pending = [];\n\tthis.pendingDirectory = [];\n\tthis.directory = [];\n\tthis.file = [];\n\tthis.onComplete = null;\n\tthis.onFilter = null;\n\tthis.advanced = false;\n}", "const FLP = FileList.prototype;", "FLP.reset = function() {\n\tthis.file.length = 0;\n\tthis.directory.length = 0;\n\tthis.pendingDirectory.length = 0;\n\treturn this;\n};", "FLP.walk = function(directory) {", "\tvar self = this;", "\tif (directory instanceof Array) {\n\t\tvar length = directory.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pendingDirectory.push(directory[i]);\n\t\tself.next();\n\t\treturn;\n\t}", "\tFs.readdir(directory, function(err, arr) {\n\t\tif (err)\n\t\t\treturn self.next();\n\t\tvar length = arr.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pending.push(Path.join(directory, arr[i]));\n\t\tself.next();\n\t});\n};", "FLP.stat = function(path) {\n\tvar self = this;", "\tFs.stat(path, function(err, stats) {", "\t\tif (err)\n\t\t\treturn self.next();", "\t\tif (stats.isDirectory()) {\n\t\t\tpath = self.clean(path);\n\t\t\tif (!self.onFilter || self.onFilter(path, true)) {\n\t\t\t\tself.directory.push(path);\n\t\t\t\tself.pendingDirectory.push(path);\n\t\t\t}\n\t\t} else if (!self.onFilter || self.onFilter(path, false))\n\t\t\tself.file.push(self.advanced ? { filename: path, stats: stats } : path);", "\t\tself.next();\n\t});\n};", "FLP.clean = function(path) {\n\treturn path[path.length - 1] === Path.sep ? path : path + Path.sep;\n};", "FLP.next = function() {\n\tvar self = this;", "\tif (self.pending.length) {\n\t\tvar item = self.pending.shift();\n\t\tself.stat(item);\n\t\treturn;\n\t}", "\tif (self.pendingDirectory.length) {\n\t\tvar directory = self.pendingDirectory.shift();\n\t\tself.walk(directory);\n\t\treturn;\n\t}", "\tself.onComplete(self.file, self.directory);\n};\n", "exports.sync = function(fn, owner) {\n\treturn function() {", "\t\tvar args = [].slice.call(arguments);\n\t\tvar params;\n\t\tvar callback;\n\t\tvar executed = false;\n\t\tvar self = owner || this;", "\t\targs.push(function() {\n\t\t\tparams = arguments;\n\t\t\tif (!executed && callback) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t});", "\t\tfn.apply(self, args);", "\t\treturn function(cb) {\n\t\t\tcallback = cb;\n\t\t\tif (!executed && params) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t};\n\t};\n};", "exports.sync2 = function(fn, owner) {\n\treturn (function() {", "\t\tvar params;\n\t\tvar callback;\n\t\tvar executed = false;\n\t\tvar self = owner || this;\n\t\tvar args = [].slice.call(arguments);", "\t\targs.push(function() {\n\t\t\tparams = arguments;\n\t\t\tif (!executed && callback) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t});", "\t\tfn.apply(self, args);", "\t\treturn function(cb) {\n\t\t\tcallback = cb;\n\t\t\tif (!executed && params) {\n\t\t\t\texecuted = true;\n\t\t\t\tcallback.apply(self, params);\n\t\t\t}\n\t\t};\n\t})();\n};\n", "exports.async = function(fn, isApply) {\n\tvar context = this;\n\treturn function(complete) {", "\t\tvar self = this;\n\t\tvar argv;", "\t\tif (arguments.length) {", "\t\t\tif (isApply) {\n\t\t\t\t// index.js/Subscribe.prototype.doExecute\n\t\t\t\targv = arguments[1];\n\t\t\t} else {\n\t\t\t\targv = [];\n\t\t\t\tfor (var i = 1; i < arguments.length; i++)\n\t\t\t\t\targv.push(arguments[i]);\n\t\t\t}\n\t\t} else\n\t\t\targv = new Array(0);", "\t\tvar generator = fn.apply(context, argv);\n\t\tnext(null);", "\t\tfunction next(err, result) {", "\t\t\tvar g, type;", "\t\t\ttry\n\t\t\t{\n\t\t\t\tvar can = err ? false : true;\n\t\t\t\tswitch (can) {\n\t\t\t\t\tcase true:\n\t\t\t\t\t\tg = generator.next(result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase false:\n\t\t\t\t\t\tg = generator.throw(err);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}", "\t\t\t} catch (e) {", "\t\t\t\tif (!complete)\n\t\t\t\t\treturn;", "\t\t\t\ttype = typeof(complete);", "\t\t\t\tif (type === 'object' && complete.isController) {\n\t\t\t\t\tif (e instanceof ErrorBuilder)\n\t\t\t\t\t\tcomplete.content(e);\n\t\t\t\t\telse\n\t\t\t\t\t\tcomplete.view500(e);\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\ttype === 'function' && setImmediate(() => complete(e));\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tif (g.done) {\n\t\t\t\ttypeof(complete) === 'function' && complete(null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tvar promise = g.value instanceof Promise;", "\t\t\tif (typeof(g.value) !== 'function' && !promise) {\n\t\t\t\tnext.call(self, null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\ttry\n\t\t\t{\n\t\t\t\tif (promise) {\n\t\t\t\t\tg.value.then((value) => next.call(self, null, value));\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\tg.value.call(self, function() {\n\t\t\t\t\tnext.apply(self, arguments);\n\t\t\t\t});", "\t\t\t} catch (e) {\n\t\t\t\tsetImmediate(() => next.call(self, e));\n\t\t\t}\n\t\t}", "\t\treturn generator.value;\n\t};\n};", "// MIT\n// Written by Jozef Gula\n// Optimized by Peter Sirka\nconst CACHE_GML1 = [null, null, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];\nconst CACHE_GML2 = [null, null, null, null, null, null, null, null];\nexports.getMessageLength = function(data, isLE) {", "\tvar length = data[1] & 0x7f;", "\tif (length === 126) {\n\t\tif (data.length < 4)\n\t\t\treturn -1;\n\t\tCACHE_GML1[0] = data[3];\n\t\tCACHE_GML1[1] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML1, 0, isLE);\n\t}", "\tif (length === 127) {\n\t\tif (data.Length < 10)\n\t\t\treturn -1;\n\t\tCACHE_GML2[0] = data[9];\n\t\tCACHE_GML2[1] = data[8];\n\t\tCACHE_GML2[2] = data[7];\n\t\tCACHE_GML2[3] = data[6];\n\t\tCACHE_GML2[4] = data[5];\n\t\tCACHE_GML2[5] = data[4];\n\t\tCACHE_GML2[6] = data[3];\n\t\tCACHE_GML2[7] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML2, 0, isLE);\n\t}", "\treturn length;\n};", "// MIT\n// Written by Jozef Gula\nfunction converBytesToInt64(data, startIndex, isLE) {\n\treturn isLE ? (data[startIndex] | (data[startIndex + 1] << 0x08) | (data[startIndex + 2] << 0x10) | (data[startIndex + 3] << 0x18) | (data[startIndex + 4] << 0x20) | (data[startIndex + 5] << 0x28) | (data[startIndex + 6] << 0x30) | (data[startIndex + 7] << 0x38)) : ((data[startIndex + 7] << 0x20) | (data[startIndex + 6] << 0x28) | (data[startIndex + 5] << 0x30) | (data[startIndex + 4] << 0x38) | (data[startIndex + 3]) | (data[startIndex + 2] << 0x08) | (data[startIndex + 1] << 0x10) | (data[startIndex] << 0x18));\n}", "exports.queuecache = {};", "function queue_next(name) {", "\tvar item = exports.queuecache[name];\n\tif (!item)\n\t\treturn;", "\titem.running--;", "\tif (item.running < 0)\n\t\titem.running = 0;", "\tif (item.pending.length) {\n\t\tvar fn = item.pending.shift();\n\t\tif (fn) {\n\t\t\titem.running++;\n\t\t\tsetImmediate(queue_next_callback, fn, name);\n\t\t} else\n\t\t\titem.running = 0;\n\t}\n}", "function queue_next_callback(fn, name) {\n\tfn(() => queue_next(name));\n}", "exports.json2replacer = function(key, value) {\n\tif (value != null)\n\t\treturn value;\n};", "/**\n * Queue list\n * @param {String} name\n * @param {Number} max Maximum stack.\n * @param {Function(next)} fn\n */\nexports.queue = function(name, max, fn) {", "\tif (!fn)\n\t\treturn false;", "\tif (!max) {\n\t\tfn(NOOP);\n\t\treturn true;\n\t}", "\tif (!exports.queuecache[name])\n\t\texports.queuecache[name] = { limit: max, running: 0, pending: [] };", "\tvar item = exports.queuecache[name];\n\tif (item.running >= item.limit) {\n\t\titem.pending.push(fn);\n\t\treturn false;\n\t}", "\titem.running++;\n\tsetImmediate(queue_next_callback, fn, name);\n\treturn true;\n};", "exports.minify_css = function(val) {\n\treturn Internal.compile_css(val);\n};", "exports.minify_js = function(val) {\n\treturn Internal.compile_javascript(val);\n};", "exports.minify_html = function(val) {\n\treturn Internal.compile_html(val);\n};", "exports.parseTheme = function(value) {\n\tif (value[0] !== '=')\n\t\treturn '';\n\tvar index = value.indexOf('/', 2);\n\tif (index === -1)\n\t\treturn '';\n\tvalue = value.substring(1, index);\n\treturn value === '?' ? CONF.default_theme : value;\n};", "\nexports.set = function(obj, path, value) {\n\tvar cachekey = 'S+' + path;", "\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj, value);", "\tvar arr = parsepath(path);\n\tvar builder = [];", "\tfor (var i = 0; i < arr.length - 1; i++) {\n\t\tvar type = arr[i + 1] ? (REGISARR.test(arr[i + 1]) ? '[]' : '{}') : '{}';\n\t\tvar p = 'w' + (arr[i][0] === '[' ? '' : '.') + arr[i];\n\t\tbuilder.push('if(typeof(' + p + ')!==\\'object\\'||' + p + '==null)' + p + '=' + type + ';');\n\t}", "\tvar v = arr[arr.length - 1];\n\tvar ispush = v.lastIndexOf('[]') !== -1;\n\tvar a = builder.join(';') + ';var v=typeof(a)===\\'function\\'?a(U.get(b)):a;w' + (v[0] === '[' ? '' : '.') + (ispush ? v.replace(REGREPLACEARR, '.push(v)') : (v + '=v')) + ';return v';", "\tif ((/__proto__|constructor|prototype|eval/).test(a))\n\t\tthrow new Error('Potential vulnerability');", "\tvar fn = new Function('w', 'a', 'b', a);\n\tF.temporary.other[cachekey] = fn;\n\tfn(obj, value, path);\n};", "exports.get = function(obj, path) {", "\tvar cachekey = 'G=' + path;", "\tif (F.temporary.other[cachekey])\n\t\treturn F.temporary.other[cachekey](obj);", "\tvar arr = parsepath(path);\n\tvar builder = [];", "\tfor (var i = 0, length = arr.length - 1; i < length; i++)\n\t\tbuilder.push('if(!w' + (!arr[i] || arr[i][0] === '[' ? '' : '.') + arr[i] + ')return');", "\tvar v = arr[arr.length - 1];\n\tvar fn = (new Function('w', builder.join(';') + ';return w' + (v[0] === '[' ? '' : '.') + v));\n\tF.temporary.other[cachekey] = fn;\n\treturn fn(obj);\n};", "function parsepath(path) {", "\tvar arr = path.split('.');\n\tvar builder = [];\n\tvar all = [];", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar p = arr[i];\n\t\tvar index = p.indexOf('[');\n\t\tif (index === -1) {\n\t\t\tif (p.indexOf('-') === -1) {\n\t\t\t\tall.push(p);\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t} else {\n\t\t\t\tvar a = all.splice(all.length - 1);\n\t\t\t\tall.push(a + '[\\'' + p + '\\']');\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t}\n\t\t} else {\n\t\t\tif (p.indexOf('-') === -1) {\n\t\t\t\tall.push(p.substring(0, index));\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t\tall.splice(all.length - 1);\n\t\t\t\tall.push(p);\n\t\t\t\tbuilder.push(all.join('.'));\n\t\t\t} else {\n\t\t\t\tall.push('[\\'' + p.substring(0, index) + '\\']');\n\t\t\t\tbuilder.push(all.join(''));\n\t\t\t\tall.push(p.substring(index));\n\t\t\t\tbuilder.push(all.join(''));\n\t\t\t}\n\t\t}\n\t}", "\treturn builder;\n}", "global.sync = exports.sync;\nglobal.sync2 = exports.sync2;", "\n// =============================================\n// SHELL SORT IMPLEMENTATION OF ALGORITHM\n// =============================================", "function _shellInsertionSort(list, length, gapSize, fn) {\n\tvar temp, i, j;\n\tfor (i = gapSize; i < length; i += gapSize ) {\n\t\tj = i;\n\t\twhile(j > 0 && fn(list[j - gapSize], list[j]) === 1) {\n\t\t\ttemp = list[j];\n\t\t\tlist[j] = list[j - gapSize];\n\t\t\tlist[j - gapSize] = temp;\n\t\t\tj -= gapSize;\n\t\t}\n\t}\n}", "function shellsort(arr, fn) {\n\tvar length = arr.length;\n\tvar gapSize = Math.floor(length / 2);\n\twhile(gapSize) {\n\t\t_shellInsertionSort(arr, length, gapSize, fn);\n\t\tgapSize = Math.floor(gapSize / 2);\n\t}\n\treturn arr;\n}", "function EventEmitter2(obj) {\n\tif (obj) {\n\t\t!obj.emit && EventEmitter2.extend(obj);\n\t\treturn obj;\n\t} else\n\t\tthis.$events = {};\n}", "const EE2P = EventEmitter2.prototype;", "EE2P.emit = function(name, a, b, c, d, e, f, g) {", "\tif (!this.$events)\n\t\treturn this;", "\tvar evt = this.$events[name];\n\tif (evt) {\n\t\tvar clean = false;\n\t\tfor (var i = 0, length = evt.length; i < length; i++) {\n\t\t\tif (evt[i].$once)\n\t\t\t\tclean = true;\n\t\t\tevt[i].call(this, a, b, c, d, e, f, g);\n\t\t}\n\t\tif (clean) {\n\t\t\tevt = evt.remove(n => n.$once);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.on = function(name, fn) {\n\tif (!this.$events)\n\t\tthis.$events = {};\n\tif (this.$events[name])\n\t\tthis.$events[name].push(fn);\n\telse\n\t\tthis.$events[name] = [fn];\n\treturn this;\n};", "EE2P.once = function(name, fn) {\n\tfn.$once = true;\n\treturn this.on(name, fn);\n};", "EE2P.removeListener = function(name, fn) {\n\tif (this.$events) {\n\t\tvar evt = this.$events[name];\n\t\tif (evt) {\n\t\t\tevt = evt.remove(n => n === fn);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.removeAllListeners = function(name) {\n\tif (this.$events) {\n\t\tif (name === true)\n\t\t\tthis.$events = EMPTYOBJECT;\n\t\telse if (name)\n\t\t\tthis.$events[name] = undefined;\n\t\telse\n\t\t\tthis.$events = {};\n\t}\n\treturn this;\n};", "EventEmitter2.extend = function(obj) {\n\tobj.emit = EE2P.emit;\n\tobj.on = EE2P.on;\n\tobj.once = EE2P.once;\n\tobj.removeListener = EE2P.removeListener;\n\tobj.removeAllListeners = EE2P.removeAllListeners;\n};", "exports.EventEmitter2 = EventEmitter2;", "function Chunker(name, max) {\n\tthis.name = name;\n\tthis.max = max || 50;\n\tthis.index = 0;\n\tthis.filename = '{0}-'.format(name);\n\tthis.stack = [];\n\tthis.flushing = 0;\n\tthis.pages = 0;\n\tthis.count = 0;\n\tthis.percentage = 0;\n\tthis.autoremove = true;\n\tthis.compress = true;\n\tthis.filename = PATH.temp(this.filename);\n}", "const CHP = Chunker.prototype;", "CHP.append = CHP.write = function(obj) {\n\tvar self = this;", "\tself.stack.push(obj);", "\tvar tmp = self.stack.length;", "\tif (tmp >= self.max) {", "\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.end = function() {\n\tvar self = this;\n\tvar tmp = self.stack.length;\n\tif (tmp) {\n\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.each = function(onItem, onEnd, indexer) {", "\tvar self = this;", "\tif (indexer == null) {\n\t\tself.percentage = 0;\n\t\tindexer = 0;\n\t}", "\tif (indexer >= self.index)\n\t\treturn onEnd && onEnd();", "\tself.read(indexer++, function(err, items) {\n\t\tself.percentage = Math.ceil((indexer / self.pages) * 100);\n\t\tonItem(items, () => self.each(onItem, onEnd, indexer), indexer - 1);\n\t});", "\treturn self;\n};", "CHP.read = function(index, callback) {\n\tvar self = this;", "\tif (self.flushing) {\n\t\tself.flushing_timeout = setTimeout(() => self.read(index, callback), 300);\n\t\treturn;\n\t}", "\tvar filename = self.filename + index + '.chunker';", "\tFs.readFile(filename, function(err, data) {", "\t\tif (err) {\n\t\t\tcallback(null, EMPTYARRAY);\n\t\t\treturn;\n\t\t}", "\t\tif (self.compress) {\n\t\t\tZlib.inflate(data, function(err, data) {\n\t\t\t\tif (err) {\n\t\t\t\t\tcallback(null, EMPTYARRAY);\n\t\t\t\t} else {\n\t\t\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t}\n\t});", "\treturn self;\n};", "CHP.clear = function() {\n\tvar files = [];\n\tfor (var i = 0; i < this.index; i++)\n\t\tfiles.push(this.filename + i + '.chunker');\n\tfiles.wait((filename, next) => Fs.unlink(filename, next));\n\treturn this;\n};", "CHP.destroy = function() {\n\tthis.clear();\n\tthis.indexer = 0;\n\tthis.flushing = 0;\n\tclearTimeout(this.flushing_timeout);\n\tthis.stack = null;\n\treturn this;\n};", "exports.chunker = function(name, max) {\n\treturn new Chunker(name, max);\n};", "exports.Chunker = Chunker;", "exports.ObjectToArray = function(obj) {\n\tif (obj == null)\n\t\treturn EMPTYARRAY;\n\tvar output = [];\n\tfor (var key in obj)\n\t\toutput.push({ key: key, value: obj[key]});\n\treturn output;\n};", "exports.createBufferSize = (size) => Buffer.alloc(size || 0);\nexports.createBuffer = (val, type) => Buffer.from(val || '', type);", "function Callback(count, callback) {\n\tthis.pending = count;\n\tthis.$callback = callback;\n}\nconst CP = Callback.prototype;", "CP.done = function(callback) {\n\tthis.$callback = callback;\n\treturn this;\n};", "CP.next = function() {\n\tvar self = this;\n\tself.pending--;\n\tif (!self.pending && self.$callback) {\n\t\tself.$callback();\n\t\tself.$callback = null;\n\t}\n\treturn self;\n};", "global.Callback = Callback;", "exports.Callback = function(count, callback) {\n\treturn new Callback(count, callback);\n};", "function Reader() {\n\tvar t = this;\n\t// t.tmp;\n\tt.$add = function(builder) {\n\t\tvar b = require('./textdb-builder').make();\n\t\tbuilder.options.filter = builder.options.filter && builder.options.filter.length ? builder.options.filter.join('&&') : 'true';\n\t\tb.assign(builder.options);", "\t\tif (builder.$)\n\t\t\tb.$resolve = builder.$resolve;\n\t\telse\n\t\t\tb.$callback = builder.$callback;", "\t\tif (t.reader)\n\t\t\tt.reader.add(b);\n\t\telse {\n\t\t\tt.reader = require('./textdb-reader').make();\n\t\t\tt.reader.add(b);\n\t\t\tt.reader.prepare();\n\t\t}\n\t};", "\tt.push = function(data) {\n\t\tif (t.reader) {\n\t\t\tif (data)\n\t\t\t\tt.reader.compare(data instanceof Array ? data : [data]);\n\t\t\telse\n\t\t\t\tt.reader.done();\n\t\t} else\n\t\t\tsetImmediate(t.push, data);\n\t};", "}", "const RP = Reader.prototype;", "RP.done = function() {\n\tvar self = this;\n\tself.reader.done();\n\treturn self;\n};", "RP.reset = function() {\n\tvar self = this;\n\tself.reader.reset();\n\treturn self;\n};", "RP.find = function() {\n\tvar self = this;\n\tvar builder = require('./textdb-wrapper').makebuilder();\n\tbuilder.command = 'find';\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "function listing(builder, items, response) {\n\tvar skip = builder.options.skip || 0;\n\tvar take = builder.options.take || 0;\n\treturn { page: skip && take ? ((skip / take) + 1) : 1, pages: response.count && take ? Math.ceil(response.count / take) : response.count ? 1 : 0, limit: take, count: response.count, items: items || [] };\n}", "RP.list = function() {\n\tvar self = this;\n\tvar builder = require('./textdb-wrapper').makebuilder();\n\tbuilder.command = 'find';\n\tbuilder.parent = {};\n\tbuilder.$callback = function(err, response, meta) {\n\t\tif (builder.parent.$) {\n\t\t\tif (err)\n\t\t\t\tbuilder.parent.$.invalid(err);\n\t\t\telse\n\t\t\t\tbuilder.parent.$resolve(response);\n\t\t} else if (builder.parent.$callback)\n\t\t\tbuilder.parent.$callback(err, listing(builder, response, meta), meta);\n\t};\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "RP.read = function() {\n\tvar self = this;\n\tvar builder = require('./textdb-wrapper').makebuilder();\n\tbuilder.command = 'find';\n\tbuilder.options.take = 1;\n\tbuilder.options.first = 1;\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "RP.count = function() {\n\tvar builder = this.find();\n\tbuilder.options.scalar = 'arg.count++';\n\tbuilder.options.scalararg = { count: 0 };\n\treturn builder;\n};", "RP.scalar = function(type, key, key2) {\n\tvar builder = this.find();", "\tif (key == null) {\n\t\tkey = type;\n\t\ttype = '*';\n\t}", "\tswitch (type) {\n\t\tcase 'group':\n\t\t\tbuilder.options.scalar = key2 ? 'if (doc.{0}!=null){tmp.val=doc.{0};arg[tmp.val]=(arg[tmp.val]||0)+(doc.{1}||0)}'.format(key, key2) : 'if (doc.{0}!=null){tmp.val=doc.{0};arg[tmp.val]=(arg[tmp.val]||0)+1}'.format(key);\n\t\t\tbuilder.options.scalararg = {};\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t// min, max, sum, count\n\t\t\tif (key2) {\n\t\t\t\tbuilder.options.scalar = 'var k=doc.' + key + '+\\'\\';if (arg[k]){tmp.bk=doc.' + key2 + '||0;' + (type === 'max' ? 'if(tmp.bk>arg[k])arg[k]=tmp.bk' : type === 'min' ? 'if(tmp.bk<arg[k])arg[k]=tmp.bk' : 'arg[k]+=tmp.bk') + '}else{arg[k]=doc.' + key2 + '||0}';\n\t\t\t} else {\n\t\t\t\tbuilder.options.scalar = 'if (doc.{0}!=null){tmp.val=doc.{0};arg.count+=1;arg.min=arg.min==null?tmp.val:arg.min>tmp.val?tmp.val:arg.min;arg.max=arg.max==null?tmp.val:arg.max<tmp.val?tmp.val:arg.max;if(!(tmp.val instanceof Date))arg.sum+=tmp.val}'.format(key);\n\t\t\t\tbuilder.options.scalararg = { count: 0, sum: 0 };\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn builder;\n};", "RP.stats = function(groupfield, datefield, key, type) {\n\tvar builder = this.find();\n\tbuilder.options.scalar = 'if (doc.{0}!=null&&doc.{2}!=null&&doc.{1} instanceof Date){tmp.val=doc.{2};tmp.group=doc.{0};tmp.date=doc.{1}.format(\\'{3}\\');if(!arg[tmp.group])arg[tmp.group]={};if(!arg[tmp.group][tmp.date])arg[tmp.group][tmp.date]={min:null,max:null,count:0};tmp.cur=arg[tmp.group][tmp.date];tmp.cur.count++;if(tmp.cur.max==null){tmp.cur.max=tmp.val}else if(tmp.cur.max<tmp.val){tmp.cur.max=tmp.val}if(tmp.cur.min==null){tmp.cur.min=tmp.val}else if(tmp.cur.min>tmp.val){tmp.cur.min=tmp.val}}'.format(groupfield, datefield, key, type === 'hourly' ? 'yyyyMMddHH' : type === 'monthly' ? 'yyyyMM' : type === 'yearly' ? 'yyyy' : 'yyyyMMdd');\n\tbuilder.options.scalararg = {};\n\treturn builder;\n};", "exports.reader = function(items) {\n\tvar instance = new Reader();\n\tif (items) {\n\t\tinstance.push(items);\n\t\tinstance.push(null);\n\t}\n\treturn instance;\n};", "global.WAIT = function(fnValid, fnCallback, timeout, interval) {", "\tif (fnValid() === true)\n\t\treturn fnCallback(null, true);", "\tvar id_timeout = null;\n\tvar id_interval = setInterval(function() {", "\t\tif (fnValid() === true) {\n\t\t\tclearInterval(id_interval);\n\t\t\tclearTimeout(id_timeout);\n\t\t\tfnCallback && fnCallback(null, true);\n\t\t}", "\t}, interval || 500);", "\tid_timeout = setTimeout(function() {\n\t\tclearInterval(id_interval);\n\t\tfnCallback && fnCallback(new Error('Timeout.'), false);\n\t}, timeout || 5000);\n};", "// Author: Peter Širka\n// License: MIT\nfunction MultipartParser(multipart, stream, callback) {", "\tif (UPLOADINDEXER > 9999999999)\n\t\tUPLOADINDEXER = 1;", "\tvar self = this;", "\tself.buffer = null;\n\tself.header = Buffer.from(multipart, 'ascii');\n\tself.length = self.header.length;\n\tself.tmp = PATH.temp((F.clusterid || '') + 'upload_');", "\t// 0: nothing\n\t// 1: head\n\t// 2: data\n\t// 3: file\n\tself.step = 0;", "\t// Meta data\n\tself.sizes = { total: 0, files: 0, data: 0, parts: 0 };\n\tself.limits = { total: 0, files: 0, data: 0, parts: 0 };\n\tself.current = {};\n\tself.body = {};\n\tself.files = [];\n\tself.size = 0;", "\tself.ondata = function(chunk) {\n\t\tself.size += chunk.length;\n\t\tif (self.buffer) {\n\t\t\tCONCAT[0] = self.buffer;\n\t\t\tCONCAT[1] = chunk;\n\t\t\tself.buffer = Buffer.concat(CONCAT);\n\t\t\tself.parse(1);\n\t\t} else {\n\t\t\tself.buffer = chunk;\n\t\t\tself.parse(0);\n\t\t}\n\t};", "\tself.onend = function() {\n\t\tself.isend = true;\n\t\tself.checkready();\n\t};", "\tself.onclose = () => self.free('3: Request closed');\n\tself.callback = callback;\n\tself.stream = stream;\n\tself.stream.on('data', self.ondata);\n\tself.stream.on('end', self.onend);\n\t// self.stream.on('close', self.onclose);\n\tself.stream.on('abort', self.onclose);\n}", "MultipartParser.prototype.free = function(err) {\n\tvar self = this;", "\tif (!self.stream)\n\t\treturn;", "\tself.stream.removeListener('data', self.ondata);\n\tself.stream.removeListener('end', self.onend);\n\t// self.stream.removeListener('close', self.onclose);\n\tself.stream.removeListener('abort', self.onclose);\n\tself.current.stream && self.current.stream.end();\n\tself.stream = null;\n\tself.buffer = null;\n\tself.callback && self.callback(err, self);\n};", "MultipartParser.prototype.parse = function(type) {\n\tvar self = this;\n\tswitch (self.step) {\n\t\tcase 0: // no data, tries to parse meta\n\t\t\tself.parse_meta(type);\n\t\t\tbreak;\n\t\tcase 1: // part found\n\t\t\tself.parse_head();\n\t\t\tbreak;\n\t\tcase 2: // part data\n\t\t\tself.parse_data();\n\t\t\tbreak;\n\t\tcase 3: // part file\n\t\t\tself.parse_file();\n\t\t\tbreak;\n\t}\n};", "MultipartParser.prototype.parse_meta = function(type) {", "\tvar self = this;", "\tvar fromindex = type === 1 ? (self.buffer.length - self.header.length) : 0;\n\tif (fromindex < 0)\n\t\tfromindex = 0;", "\tvar index = type === 2 ? 0 : self.buffer.indexOf(self.header, fromindex);", "\tif (index === -1)\n\t\treturn;", "\t// Is end?\n\tif (self.buffer[index + self.length - 1] === 45) {\n\t\tself.current.stream && self.current.stream.end();\n\t\tself.current.stream = null;\n\t\treturn;\n\t}", "\tself.sizes.parts++;", "\tif (self.limits.parts && self.sizes.parts > self.limits.parts) {\n\t\tself.kill('1: Count of parts is too large');\n\t\treturn;\n\t}", "\tself.buffer = self.buffer.slice(self.length + 2);\n\tself.step = 1;\n\tself.parse();", "};", "MultipartParser.prototype.kill = function(err) {\n\tthis.free(err);\n};", "var multipartfileready = function() {\n\tthis.$mpfile.ready = true;\n\tthis.$mpfile = null;\n\tthis.$mpinstance.checkready();\n\tthis.$mpinstance = null;\n};", "MultipartParser.prototype.checkready = function() {", "\tvar self = this;", "\tif (!self.stream || !self.isend)\n\t\treturn;", "\tfor (var i = 0; i < self.files.length; i++) {\n\t\tif (!self.files[i].ready)\n\t\t\treturn;\n\t}", "\tself.free();\n};", "MultipartParser.prototype.parse_head = function() {", "\tvar self = this;\n\tvar index = self.buffer.indexOf(HEADEREND);", "\tif (index === -1)\n\t\treturn;", "\tvar header = self.buffer.slice(0, index).toString('utf8').trim();\n\tif (header.substring(0, HEADERCHECK.length).toLowerCase() !== HEADERCHECK) {\n\t\tself.kill('7:');\n\t\treturn;\n\t}", "\theader = header.substring(HEADERCHECK.length).trim();", "\tvar beg = header.indexOf('filename=\"');\n\tvar isfile = beg !== -1;", "\tself.current.filename = isfile ? header.substring(beg + 10, header.indexOf('\"', beg + 10)).trim() : null;", "\tif (isfile && !self.current.filename)\n\t\treturn;", "\tbeg = header.indexOf('name=\"');\n\tif (beg === -1) {\n\t\tself.kill('2: Invalid part header');\n\t\treturn;\n\t}", "\tself.current.name = header.substring(beg + 6, header.indexOf('\"', beg + 6));\n\tself.current.size = 0;", "\tif (isfile) {", "\t\tif (REG_EMPTYBUFFER_TEST.test(self.current.filename))\n\t\t\tself.current.filename = self.current.filename.replace(REG_EMPTYBUFFER, '');", "\t\tvar type = header.match(/content-type:\\s.*?((\\r\\n)|$)/i);\n\t\tif (type) {\n\t\t\tself.current.type = type[0].substring(14);\n\t\t\tself.current.width = 0;\n\t\t\tself.current.height = 0;\n\t\t\tswitch (self.current.type) {\n\t\t\t\tcase 'image/svg+xml':\n\t\t\t\tcase 'image/svg':\n\t\t\t\t\tself.current.measure = 'measureSVG';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/jpeg':\n\t\t\t\tcase 'image/jpg':\n\t\t\t\t\tself.current.measure = 'measureJPG';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/png':\n\t\t\t\t\tself.current.measure = 'measurePNG';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/gif':\n\t\t\t\t\tself.current.measure = 'measureGIF';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tself.current.measure = null;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (self.current.stream) {\n\t\t\tself.current.stream.end();\n\t\t\tself.current.stream = null;\n\t\t}", "\t\tif (!type) {\n\t\t\tself.kill('2: Invalid part header');\n\t\t\treturn;\n\t\t}", "\t\tself.current.path = self.tmp + (UPLOADINDEXER++) + '.bin';\n\t\tself.current.stream = Fs.createWriteStream(self.current.path);\n\t\tvar file = { path: self.current.path, name: self.current.name, filename: self.current.filename, size: 0, type: self.current.type, width: 0, height: 0 };\n\t\tself.current.file = file;\n\t\tself.current.stream.$mpfile = file;\n\t\tself.current.stream.$mpinstance = self;\n\t\tself.current.stream.on('close', multipartfileready);\n\t} else\n\t\tself.current.file = null;", "\tself.buffer = self.buffer.slice(index + HEADEREND.length);\n\tself.step = isfile ? 3 : 2;\n\tself.current.size = 0;\n\tself.parse();\n};", "MultipartParser.prototype.parse_file = function() {", "\tvar self = this;\n\tvar index = self.buffer.indexOf(self.header);\n\tvar tmp;", "\tif (self.current.measure) {\n\t\ttmp = framework_image[self.current.measure](self.buffer);\n\t\tif (tmp) {\n\t\t\tself.current.file.width = tmp.width;\n\t\t\tself.current.file.height = tmp.height;\n\t\t}\n\t\tself.current.measure = null;\n\t}", "\tif (index !== -1) {", "\t\tself.current.size += index - 4;\n\t\tself.current.file.size += index - 4;\n\t\tself.sizes.total += index - 4;\n\t\tself.sizes.files += index - 4;", "\t\tif (self.limits.files && self.sizes.files > self.limits.files) {\n\t\t\tself.kill('4: File body is too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && self.sizes.total > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t\tvar data = self.buffer.slice(0, index - 4);\n\t\tself.current.stream.end(data);\n\t\tself.current.stream = null;\n\t\tself.files.push(self.current.file);\n\t\tself.buffer = self.buffer.slice(index);\n\t\tself.current.file = null;\n\t\tself.step = 0;\n\t\tself.parse(2);", "\t} else {", "\t\tvar length = self.buffer.length;", "\t\tself.current.size += length;\n\t\tself.current.file.size += length;\n\t\tself.sizes.total += length;\n\t\tself.sizes.files += length;", "\t\tif (self.limits.files && self.sizes.files > self.limits.files) {\n\t\t\tself.kill('4: File body is too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && self.sizes.total > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t\tself.current.stream.write(self.buffer);\n\t\tself.buffer = null;\n\t}\n};", "MultipartParser.prototype.parse_data = function() {\n\tvar self = this;\n\tvar index = self.buffer.indexOf(self.header);", "\tif (index !== -1) {", "\t\tself.sizes.total += index - 2;\n\t\tself.sizes.data += index - 2;", "\t\tif (self.limits.data && self.sizes.data > self.limits.data) {\n\t\t\tself.kill('5: Data are too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && self.sizes.total > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t\tvar val = self.buffer.slice(0, index - 4).toString('utf8');", "\t\tif (REG_EMPTYBUFFER_TEST.test(val))\n\t\t\tval = val.replace(REG_EMPTYBUFFER, '');", "\t\tself.body[self.current.name] = val;\n\t\tself.buffer = self.buffer.slice(index);\n\t\tself.step = 0;\n\t\tself.parse(true);", "\t} else {", "\t\tself.current.size += self.buffer.length;", "\t\tif (self.limits.data && self.current.size > self.limits.data) {\n\t\t\tself.kill('5: Data are too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && (self.sizes.total + self.current.size) > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t}\n};", "var measuring = {};", "function showtime(name) {", "\tvar arr = measuring[name];\n\tvar min = null;\n\tvar max = null;\n\tvar sum = 0;", "\tfor (var i = 0; i < arr.length; i++) {", "\t\tvar val = arr[i];", "\t\tif (min == null || min > val)\n\t\t\tmin = val;", "\t\tif (max == null || max < val)\n\t\t\tmax = val;", "\t\tsum += val;\n\t}", "\tconsole.log(name, 'avg:', (sum / arr.length).floor(2), 'max:', max, 'min:', min);\n}", "exports.measure = function(name, timeout) {\n\tvar key = '_' + name;\n\tif (measuring[key]) {\n\t\tvar diff = Date.now() - measuring[key];\n\t\tif (!measuring[name])\n\t\t\tmeasuring[name] = [];\n\t\tmeasuring[name].push(diff);\n\t\tmeasuring[key] = 0;\n\t} else\n\t\tmeasuring[key] = Date.now();\n\tsetTimeout(showtime, timeout || 1000, name);\n};", "exports.multipartparser = function(multipart, stream, callback) {\n\treturn new MultipartParser(multipart, stream, callback);\n};", "var QUERIFYMETHODS = { GET: 1, POST: 1, DELETE: 1, PUT: 1, PATCH: 1, API: 1 };", "global.QUERIFY = function(url, obj) {", "\tif (typeof(url) !== 'string') {\n\t\tobj = url;\n\t\turl = '';\n\t}", "\tif (!obj)\n\t\treturn url;", "\tvar arg = [];\n\tvar keys = Object.keys(obj);", "\tfor (var i = 0; i < keys.length; i++) {", "\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\t\tif (val != null) {", "\t\t\tif (val instanceof Date)\n\t\t\t\tval = val.toISOString();\n\t\t\telse if (val instanceof Array)\n\t\t\t\tval = val.join(',');", "\t\t\tval = val + '';\n\t\t\tval && arg.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));\n\t\t}\n\t}", "\tif (url) {\n\t\tvar arr = url.split(' ');\n\t\tvar index = QUERIFYMETHODS[arr[0]] ? 1 : 0;\n\t\tarr[index] += (arr[index].indexOf('?') === -1 ? '?' : '&') + arg.join('&');\n\t\treturn arr.join(' ');\n\t}", "\treturn '?' + arg.join('&');\n};", "exports.connect = function(opt, callback) {", "\t// opt.secure {Boolean}\n\t// opt.host\n\t// opt.port\n\t// opt.timeout", "\tvar opt = CLONE(opt);\n\tvar tls = opt.tls;\n\tvar meta = {};\n\tvar timeout;", "\tmeta.opt = opt;\n\tmeta.tls = tls;", "\tdelete opt.tls;", "\tvar close = function() {", "\t\tif (meta.socket1) {\n\t\t\tmeta.socket1.removeAllListeners();\n\t\t\tmeta.socket1.end();\n\t\t\tmeta.socket1.destroy();\n\t\t\tmeta.socket1 = null;\n\t\t}", "\t\tif (meta.socket2) {\n\t\t\tmeta.socket2.removeAllListeners();\n\t\t\tmeta.socket2.end();\n\t\t\tmeta.socket2.destroy();\n\t\t\tmeta.socket2 = null;\n\t\t}", "\t};", "\tvar error = function(err) {\n\t\tcallback && callback(err);\n\t\tcallback = null;\n\t\tclose();\n\t};", "\tif (opt.timeout)\n\t\ttimeout = setTimeout(() => error(new Error('Timeout')), opt.timeout);", "\tmeta.destroy = meta.close = close;\n\tmeta.write = function(data) {\n\t\tmeta.socket.write(data);\n\t};", "\tmeta.ondata = function(fn) {\n\t\tmeta.socket.on('data', fn);\n\t};", "\tmeta.onend = function(fn) {\n\t\tmeta.socket.on('destroy', fn);\n\t};", "\tvar done = function() {", "\t\tif (!callback)\n\t\t\treturn;", "\t\tif (opt.tls) {\n\t\t\tif (!meta.socket2) {\n\t\t\t\ttls.socket = meta.socket1;\n\t\t\t\tmeta.socket2 = Tls.connect(tls, done);\n\t\t\t\tmeta.socket2.on('error', error);\n\t\t\t\tmeta.socket2.on('clientError', error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}", "\t\tmeta.socket = meta.socket2 || meta.socket1;\n\t\ttimeout && clearTimeout(timeout);\n\t\ttimeout = null;\n\t\tcallback && callback(null, meta);\n\t\tcallback = null;\n\t};", "\tif (opt.secure)\n\t\tmeta.socket1 = Tls.connect(opt, done);\n\telse\n\t\tmeta.socket1 = Net.createConnection(opt.port, opt.host, done);", "\tmeta.socket1.on('error', error);\n\tmeta.socket1.on('clientError', error);\n};", "String.prototype.toJSONSchema = function(name, url) {", "\tvar obj = {};\n\tvar p = (url || CONF.url || 'https://schemas.totaljs.com/');", "\tif (p[p.length - 1] !== '/')\n\t\tp += '/';", "\tobj.$id = p + (name || (HASH(this) + '')) + '.json';\n\tobj.$schema = 'https://json-schema.org/draft/2020-12/schema';\n\tobj.type = 'object';\n\tobj.properties = {};", "\tvar prop = this.split(',');\n\tvar required = [];", "\tfor (var i = 0; i < prop.length; i++) {", "\t\tvar arr = prop[i].split(':');\n\t\tvar tmp;", "\t\tif (arr[0][0] === '!' || arr[0][0] === '*') {\n\t\t\t// required\n\t\t\tarr[0] = arr[0].substring(1);\n\t\t\trequired.push(arr[0]);\n\t\t}", "\t\tvar type = arr[1].toLowerCase().trim();\n\t\tvar size = 0;\n\t\tvar isarr = type[0] === '[';\n\t\tif (isarr)\n\t\t\ttype = type.substring(1, type.length - 1);", "\t\tvar index = type.indexOf('(');\n\t\tif (index !== -1) {\n\t\t\tsize = +type.substring(index + 1, type.length - 1).trim();\n\t\t\ttype = type.substring(0, index);\n\t\t}", "\t\tswitch (type) {\n\t\t\tcase 'string':\n\t\t\tcase 'uid':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'string' };\n\t\t\t\t\tif (size)\n\t\t\t\t\t\ttmp.items.maxLength = size;\n\t\t\t\t} else {\n\t\t\t\t\ttmp.type = 'string';\n\t\t\t\t\tif (size)\n\t\t\t\t\t\ttmp.maxLength = size;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'number':\n\t\t\tcase 'number2':\n\t\t\tcase 'float':\n\t\t\tcase 'decimal':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'number' };\n\t\t\t\t} else {\n\t\t\t\t\ttmp.type = 'number';\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'bool':\n\t\t\tcase 'boolean':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'boolean' };\n\t\t\t\t} else\n\t\t\t\t\ttmp.type = 'boolean';\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'date' };\n\t\t\t\t} else\n\t\t\t\t\ttmp.type = 'date';\n\t\t\t\tbreak;\n\t\t}\n\t\tif (tmp)\n\t\t\tobj.properties[arr[0].trim()] = tmp;\n\t}", "\tif (required.length)\n\t\tobj.required = required;", "\treturn obj;\n};", "!global.F && require('./index');" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 5563], "buggy_code_start_loc": [5, 5206], "filenames": ["changelog.txt", "utils.js"], "fixing_code_end_loc": [10, 5418], "fixing_code_start_loc": [6, 5205], "message": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total4:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "47233194-DF6F-400D-A2BB-E5B07141E828", "versionEndExcluding": "0.0.43", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions."}, {"lang": "es", "value": "El paquete total4 versiones anteriores a 0.0.43, son vulnerables a una ejecuci\u00f3n de c\u00f3digo arbitrario por medio de las funciones U.set() y U.get()"}], "evaluatorComment": null, "id": "CVE-2021-23390", "lastModified": "2021-07-14T17:38:45.477", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-07-12T16:15:09.030", "references": [{"source": "report@snyk.io", "tags": ["Broken Link"], "url": "https://github.com/totaljs/framework4/blob/master/utils.js%23L5430-L5455"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTAL4-1130527"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, "type": "CWE-94"}
39
Determine whether the {function_name} code is vulnerable or not.
[ "'use strict';", "const Dns = require('dns');\nconst Url = require('url');\nconst Http = require('http');\nconst Https = require('https');\nconst Path = require('path');\nconst Fs = require('fs');\nconst Crypto = require('crypto');\nconst Zlib = require('zlib');\nconst Tls = require('tls');\nconst Net = require('net');\nconst KeepAlive = new Http.Agent({ keepAlive: true, timeout: 60000 });\nconst KeepAliveHttps = new Https.Agent({ keepAlive: true, timeout: 60000 });\nconst SKIPBODYENCRYPTOR = { ':': 1, '\"': 1, '[': 1, ']': 1, '\\'': 1, '_': 1, '{': 1, '}': 1, '&': 1, '=': 1, '+': 1, '-': 1, '\\\\': 1, '/': 1, ',': 1 };\nconst REG_EMPTYBUFFER = /\\0|%00|\\\\u0000/g;\nconst REG_EMPTYBUFFER_TEST = /\\0|%00|\\\\u0000/;", "const COMPRESS = { gzip: 1, deflate: 1 };\nconst CONCAT = [null, null];\nconst SKIPPORTS = { '80': 1, '443': 1 };", "const COMPARER = function(a, b) {\n\tif (!a && b)\n\t\treturn -1;\n\tif (a && !b)\n\t\treturn 1;\n\tif (a === b)\n\t\treturn 0;\n\treturn global.Intl.Collator().compare(a, b);\n};", "const COMPARER_DESC = function(a, b) {", "\tif (!a && b)\n\t\treturn 1;", "\tif (a && !b)\n\t\treturn -1;", "\tif (a === b)\n\t\treturn 0;", "\tvar val = global.Intl.Collator().compare(a, b);\n\treturn val ? val * -1 : 0;\n};", "if (!global.framework_utils)\n\tglobal.framework_utils = exports;", "const Internal = require('./internal');\nvar regexpSTATIC = /\\.\\w{2,8}($|\\?)+/;\nconst regexpTRIM = /^[\\s]+|[\\s]+$/g;\nconst regexpDATE = /(\\d{1,2}\\.\\d{1,2}\\.\\d{4})|(\\d{4}-\\d{1,2}-\\d{1,2})|(\\d{1,2}:\\d{1,2}(:\\d{1,2})?)/g;\nconst regexpDATEFORMAT = /YYYY|yyyy|YY|yy|MMMM|MMM|MM|M|dddd|DDDD|DDD|ddd|DD|dd|D|d|HH|H|hh|h|mm|m|ss|s|a|ww|w/g;\nconst regexpSTRINGFORMAT = /\\{\\d+\\}/g;\nconst regexpPATH = /\\\\/g;\nconst regexpTags = /<\\/?[^>]+(>|$)/g;\nconst regexpDiacritics = /[^\\u0000-\\u007e]/g;\nconst regexpUA = /[a-z]+/gi;\nconst regexpXML = /\\w+=\".*?\"/g;\nconst regexpDECODE = /&#?[a-z0-9]+;/g;\nconst regexpARG = /\\{{1,2}[a-z0-9_.-\\s]+\\}{1,2}/gi;\nconst regexpINTEGER = /(^-|\\s-)?[0-9]+/g;\nconst regexpFLOAT = /(^-|\\s-)?[0-9.,]+/g;\nconst regexpSEARCH = /[^a-zA-ZÑ-žÁ-Ž\\d\\s:]/g;\nconst regexpTERMINAL = /[\\w\\S]+/g;\nconst regexpCONFIGURE = /\\[\\w+\\]/g;\nconst regexpY = /y/g;\nconst regexpN = /\\n/g;\nconst regexpCHARS = /\\W|_/g;\nconst regexpCHINA = /[\\u3400-\\u9FBF]/;\nconst regexpLINES = /\\n|\\r|\\r\\n/;\nconst regexpBASE64 = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;\nconst regexpBASE64_2 = /^|,([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/;\nconst ENCODING = 'utf8';\nconst NEWLINE = '\\r\\n';\nconst isWindows = require('os').platform().substring(0, 3).toLowerCase() === 'win';\nconst DIACRITICSMAP = {};\nconst ALPHA_INDEX = { '&lt': '<', '&gt': '>', '&quot': '\"', '&apos': '\\'', '&amp': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"', '&apos;': '\\'', '&amp;': '&' };\nconst STREAMPIPE = { end: false };\nconst CT = 'Content-Type';\nconst CRC32TABLE = '00000000,77073096,EE0E612C,990951BA,076DC419,706AF48F,E963A535,9E6495A3,0EDB8832,79DCB8A4,E0D5E91E,97D2D988,09B64C2B,7EB17CBD,E7B82D07,90BF1D91,1DB71064,6AB020F2,F3B97148,84BE41DE,1ADAD47D,6DDDE4EB,F4D4B551,83D385C7,136C9856,646BA8C0,FD62F97A,8A65C9EC,14015C4F,63066CD9,FA0F3D63,8D080DF5,3B6E20C8,4C69105E,D56041E4,A2677172,3C03E4D1,4B04D447,D20D85FD,A50AB56B,35B5A8FA,42B2986C,DBBBC9D6,ACBCF940,32D86CE3,45DF5C75,DCD60DCF,ABD13D59,26D930AC,51DE003A,C8D75180,BFD06116,21B4F4B5,56B3C423,CFBA9599,B8BDA50F,2802B89E,5F058808,C60CD9B2,B10BE924,2F6F7C87,58684C11,C1611DAB,B6662D3D,76DC4190,01DB7106,98D220BC,EFD5102A,71B18589,06B6B51F,9FBFE4A5,E8B8D433,7807C9A2,0F00F934,9609A88E,E10E9818,7F6A0DBB,086D3D2D,91646C97,E6635C01,6B6B51F4,1C6C6162,856530D8,F262004E,6C0695ED,1B01A57B,8208F4C1,F50FC457,65B0D9C6,12B7E950,8BBEB8EA,FCB9887C,62DD1DDF,15DA2D49,8CD37CF3,FBD44C65,4DB26158,3AB551CE,A3BC0074,D4BB30E2,4ADFA541,3DD895D7,A4D1C46D,D3D6F4FB,4369E96A,346ED9FC,AD678846,DA60B8D0,44042D73,33031DE5,AA0A4C5F,DD0D7CC9,5005713C,270241AA,BE0B1010,C90C2086,5768B525,206F85B3,B966D409,CE61E49F,5EDEF90E,29D9C998,B0D09822,C7D7A8B4,59B33D17,2EB40D81,B7BD5C3B,C0BA6CAD,EDB88320,9ABFB3B6,03B6E20C,74B1D29A,EAD54739,9DD277AF,04DB2615,73DC1683,E3630B12,94643B84,0D6D6A3E,7A6A5AA8,E40ECF0B,9309FF9D,0A00AE27,7D079EB1,F00F9344,8708A3D2,1E01F268,6906C2FE,F762575D,806567CB,196C3671,6E6B06E7,FED41B76,89D32BE0,10DA7A5A,67DD4ACC,F9B9DF6F,8EBEEFF9,17B7BE43,60B08ED5,D6D6A3E8,A1D1937E,38D8C2C4,4FDFF252,D1BB67F1,A6BC5767,3FB506DD,48B2364B,D80D2BDA,AF0A1B4C,36034AF6,41047A60,DF60EFC3,A867DF55,316E8EEF,4669BE79,CB61B38C,BC66831A,256FD2A0,5268E236,CC0C7795,BB0B4703,220216B9,5505262F,C5BA3BBE,B2BD0B28,2BB45A92,5CB36A04,C2D7FFA7,B5D0CF31,2CD99E8B,5BDEAE1D,9B64C2B0,EC63F226,756AA39C,026D930A,9C0906A9,EB0E363F,72076785,05005713,95BF4A82,E2B87A14,7BB12BAE,0CB61B38,92D28E9B,E5D5BE0D,7CDCEFB7,0BDBDF21,86D3D2D4,F1D4E242,68DDB3F8,1FDA836E,81BE16CD,F6B9265B,6FB077E1,18B74777,88085AE6,FF0F6A70,66063BCA,11010B5C,8F659EFF,F862AE69,616BFFD3,166CCF45,A00AE278,D70DD2EE,4E048354,3903B3C2,A7672661,D06016F7,4969474D,3E6E77DB,AED16A4A,D9D65ADC,40DF0B66,37D83BF0,A9BCAE53,DEBB9EC5,47B2CF7F,30B5FFE9,BDBDF21C,CABAC28A,53B39330,24B4A3A6,BAD03605,CDD70693,54DE5729,23D967BF,B3667A2E,C4614AB8,5D681B02,2A6F2B94,B40BBE37,C30C8EA1,5A05DF1B,2D02EF8D'.split(',').map(s => parseInt(s, 16));\nconst REGISARR = /\\[\\d+\\]|\\[\\]$/;\nconst REGREPLACEARR = /\\[\\]/g;\nconst PROXYBLACKLIST = { 'localhost': 1, '127.0.0.1': 1, '0.0.0.0': 1 };\nconst PROXYOPTIONS = { headers: {}, method: 'CONNECT', agent: false };\nconst PROXYTLS = { headers: {}};\nconst PROXYOPTIONSHTTP = {};\nconst REG_ROOT = /@\\{#\\}(\\/)?/g;\nconst REG_NOREMAP = /@\\{noremap\\}(\\n)?/g;\nconst REG_REMAP = /href=\".*?\"|src=\".*?\"/gi;\nconst REG_AJAX = /('|\")+(!)?(GET|POST|PUT|DELETE|PATCH)\\s(\\(.*?\\)\\s)?\\//g;\nconst REG_URLEXT = /(https|http|wss|ws|file):\\/\\/|\\/\\/[a-z0-9]|[a-z]:/i;\nconst REG_TEXTAPPLICATION = /text|application/i;\nconst REG_TIME = /am|pm/i;\nconst REG_XMLKEY = /\\[|\\]|:|\\.|_/g;\nconst HEADEREND = Buffer.from('\\r\\n\\r\\n', 'ascii');\nconst HEADERCHECK = 'Content-Disposition: form-data;'.toLowerCase();", "exports.MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nexports.DAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];", "var DIACRITICS=[{b:' ',c:'\\u00a0'},{b:'0',c:'\\u07c0'},{b:'A',c:'\\u24b6\\uff21\\u00c0\\u00c1\\u00c2\\u1ea6\\u1ea4\\u1eaa\\u1ea8\\u00c3\\u0100\\u0102\\u1eb0\\u1eae\\u1eb4\\u1eb2\\u0226\\u01e0\\u00c4\\u01de\\u1ea2\\u00c5\\u01fa\\u01cd\\u0200\\u0202\\u1ea0\\u1eac\\u1eb6\\u1e00\\u0104\\u023a\\u2c6f'},{b:'AA',c:'\\ua732'},{b:'AE',c:'\\u00c6\\u01fc\\u01e2'},{b:'AO',c:'\\ua734'},{b:'AU',c:'\\ua736'},{b:'AV',c:'\\ua738\\ua73a'},{b:'AY',c:'\\ua73c'},{b:'B',c:'\\u24b7\\uff22\\u1e02\\u1e04\\u1e06\\u0243\\u0181'},{b:'C',c:'\\u24b8\\uff23\\ua73e\\u1e08\\u0106C\\u0108\\u010a\\u010c\\u00c7\\u0187\\u023b'},{b:'D',c:'\\u24b9\\uff24\\u1e0a\\u010e\\u1e0c\\u1e10\\u1e12\\u1e0e\\u0110\\u018a\\u0189\\u1d05\\ua779'},{b:'Dh',c:'\\u00d0'},{b:'DZ',c:'\\u01f1\\u01c4'},{b:'Dz',c:'\\u01f2\\u01c5'},{b:'E',c:'\\u025b\\u24ba\\uff25\\u00c8\\u00c9\\u00ca\\u1ec0\\u1ebe\\u1ec4\\u1ec2\\u1ebc\\u0112\\u1e14\\u1e16\\u0114\\u0116\\u00cb\\u1eba\\u011a\\u0204\\u0206\\u1eb8\\u1ec6\\u0228\\u1e1c\\u0118\\u1e18\\u1e1a\\u0190\\u018e\\u1d07'},{b:'F',c:'\\ua77c\\u24bb\\uff26\\u1e1e\\u0191\\ua77b'}, {b:'G',c:'\\u24bc\\uff27\\u01f4\\u011c\\u1e20\\u011e\\u0120\\u01e6\\u0122\\u01e4\\u0193\\ua7a0\\ua77d\\ua77e\\u0262'},{b:'H',c:'\\u24bd\\uff28\\u0124\\u1e22\\u1e26\\u021e\\u1e24\\u1e28\\u1e2a\\u0126\\u2c67\\u2c75\\ua78d'},{b:'I',c:'\\u24be\\uff29\\u00cc\\u00cd\\u00ce\\u0128\\u012a\\u012c\\u0130\\u00cf\\u1e2e\\u1ec8\\u01cf\\u0208\\u020a\\u1eca\\u012e\\u1e2c\\u0197'},{b:'J',c:'\\u24bf\\uff2a\\u0134\\u0248\\u0237'},{b:'K',c:'\\u24c0\\uff2b\\u1e30\\u01e8\\u1e32\\u0136\\u1e34\\u0198\\u2c69\\ua740\\ua742\\ua744\\ua7a2'},{b:'L',c:'\\u24c1\\uff2c\\u013f\\u0139\\u013d\\u1e36\\u1e38\\u013b\\u1e3c\\u1e3a\\u0141\\u023d\\u2c62\\u2c60\\ua748\\ua746\\ua780'}, {b:'LJ',c:'\\u01c7'},{b:'Lj',c:'\\u01c8'},{b:'M',c:'\\u24c2\\uff2d\\u1e3e\\u1e40\\u1e42\\u2c6e\\u019c\\u03fb'},{b:'N',c:'\\ua7a4\\u0220\\u24c3\\uff2e\\u01f8\\u0143\\u00d1\\u1e44\\u0147\\u1e46\\u0145\\u1e4a\\u1e48\\u019d\\ua790\\u1d0e'},{b:'NJ',c:'\\u01ca'},{b:'Nj',c:'\\u01cb'},{b:'O',c:'\\u24c4\\uff2f\\u00d2\\u00d3\\u00d4\\u1ed2\\u1ed0\\u1ed6\\u1ed4\\u00d5\\u1e4c\\u022c\\u1e4e\\u014c\\u1e50\\u1e52\\u014e\\u022e\\u0230\\u00d6\\u022a\\u1ece\\u0150\\u01d1\\u020c\\u020e\\u01a0\\u1edc\\u1eda\\u1ee0\\u1ede\\u1ee2\\u1ecc\\u1ed8\\u01ea\\u01ec\\u00d8\\u01fe\\u0186\\u019f\\ua74a\\ua74c'}, {b:'OE',c:'\\u0152'},{b:'OI',c:'\\u01a2'},{b:'OO',c:'\\ua74e'},{b:'OU',c:'\\u0222'},{b:'P',c:'\\u24c5\\uff30\\u1e54\\u1e56\\u01a4\\u2c63\\ua750\\ua752\\ua754'},{b:'Q',c:'\\u24c6\\uff31\\ua756\\ua758\\u024a'},{b:'R',c:'\\u24c7\\uff32\\u0154\\u1e58\\u0158\\u0210\\u0212\\u1e5a\\u1e5c\\u0156\\u1e5e\\u024c\\u2c64\\ua75a\\ua7a6\\ua782'},{b:'S',c:'\\u24c8\\uff33\\u1e9e\\u015a\\u1e64\\u015c\\u1e60\\u0160\\u1e66\\u1e62\\u1e68\\u0218\\u015e\\u2c7e\\ua7a8\\ua784'},{b:'T',c:'\\u24c9\\uff34\\u1e6a\\u0164\\u1e6c\\u021a\\u0162\\u1e70\\u1e6e\\u0166\\u01ac\\u01ae\\u023e\\ua786'}, {b:'Th',c:'\\u00de'},{b:'TZ',c:'\\ua728'},{b:'U',c:'\\u24ca\\uff35\\u00d9\\u00da\\u00db\\u0168\\u1e78\\u016a\\u1e7a\\u016c\\u00dc\\u01db\\u01d7\\u01d5\\u01d9\\u1ee6\\u016e\\u0170\\u01d3\\u0214\\u0216\\u01af\\u1eea\\u1ee8\\u1eee\\u1eec\\u1ef0\\u1ee4\\u1e72\\u0172\\u1e76\\u1e74\\u0244'},{b:'V',c:'\\u24cb\\uff36\\u1e7c\\u1e7e\\u01b2\\ua75e\\u0245'},{b:'VY',c:'\\ua760'},{b:'W',c:'\\u24cc\\uff37\\u1e80\\u1e82\\u0174\\u1e86\\u1e84\\u1e88\\u2c72'},{b:'X',c:'\\u24cd\\uff38\\u1e8a\\u1e8c'},{b:'Y',c:'\\u24ce\\uff39\\u1ef2\\u00dd\\u0176\\u1ef8\\u0232\\u1e8e\\u0178\\u1ef6\\u1ef4\\u01b3\\u024e\\u1efe'}, {b:'Z',c:'\\u24cf\\uff3a\\u0179\\u1e90\\u017b\\u017d\\u1e92\\u1e94\\u01b5\\u0224\\u2c7f\\u2c6b\\ua762'},{b:'a',c:'\\u24d0\\uff41\\u1e9a\\u00e0\\u00e1\\u00e2\\u1ea7\\u1ea5\\u1eab\\u1ea9\\u00e3\\u0101\\u0103\\u1eb1\\u1eaf\\u1eb5\\u1eb3\\u0227\\u01e1\\u00e4\\u01df\\u1ea3\\u00e5\\u01fb\\u01ce\\u0201\\u0203\\u1ea1\\u1ead\\u1eb7\\u1e01\\u0105\\u2c65\\u0250\\u0251'},{b:'aa',c:'\\ua733'},{b:'ae',c:'\\u00e6\\u01fd\\u01e3'},{b:'ao',c:'\\ua735'},{b:'au',c:'\\ua737'},{b:'av',c:'\\ua739\\ua73b'},{b:'ay',c:'\\ua73d'}, {b:'b',c:'\\u24d1\\uff42\\u1e03\\u1e05\\u1e07\\u0180\\u0183\\u0253\\u0182'},{b:'c',c:'\\uff43\\u24d2\\u0107\\u0109\\u010b\\u010d\\u00e7\\u1e09\\u0188\\u023c\\ua73f\\u2184'},{b:'d',c:'\\u24d3\\uff44\\u1e0b\\u010f\\u1e0d\\u1e11\\u1e13\\u1e0f\\u0111\\u018c\\u0256\\u0257\\u018b\\u13e7\\u0501\\ua7aa'},{b:'dh',c:'\\u00f0'},{b:'dz',c:'\\u01f3\\u01c6'},{b:'e',c:'\\u24d4\\uff45\\u00e8\\u00e9\\u00ea\\u1ec1\\u1ebf\\u1ec5\\u1ec3\\u1ebd\\u0113\\u1e15\\u1e17\\u0115\\u0117\\u00eb\\u1ebb\\u011b\\u0205\\u0207\\u1eb9\\u1ec7\\u0229\\u1e1d\\u0119\\u1e19\\u1e1b\\u0247\\u01dd'}, {b:'f',c:'\\u24d5\\uff46\\u1e1f\\u0192'},{b:'ff',c:'\\ufb00'},{b:'fi',c:'\\ufb01'},{b:'fl',c:'\\ufb02'},{b:'ffi',c:'\\ufb03'},{b:'ffl',c:'\\ufb04'},{b:'g',c:'\\u24d6\\uff47\\u01f5\\u011d\\u1e21\\u011f\\u0121\\u01e7\\u0123\\u01e5\\u0260\\ua7a1\\ua77f\\u1d79'},{b:'h',c:'\\u24d7\\uff48\\u0125\\u1e23\\u1e27\\u021f\\u1e25\\u1e29\\u1e2b\\u1e96\\u0127\\u2c68\\u2c76\\u0265'},{b:'hv',c:'\\u0195'},{b:'i',c:'\\u24d8\\uff49\\u00ec\\u00ed\\u00ee\\u0129\\u012b\\u012d\\u00ef\\u1e2f\\u1ec9\\u01d0\\u0209\\u020b\\u1ecb\\u012f\\u1e2d\\u0268\\u0131'}, {b:'j',c:'\\u24d9\\uff4a\\u0135\\u01f0\\u0249'},{b:'k',c:'\\u24da\\uff4b\\u1e31\\u01e9\\u1e33\\u0137\\u1e35\\u0199\\u2c6a\\ua741\\ua743\\ua745\\ua7a3'},{b:'l',c:'\\u24db\\uff4c\\u0140\\u013a\\u013e\\u1e37\\u1e39\\u013c\\u1e3d\\u1e3b\\u017f\\u0142\\u019a\\u026b\\u2c61\\ua749\\ua781\\ua747\\u026d'},{b:'lj',c:'\\u01c9'},{b:'m',c:'\\u24dc\\uff4d\\u1e3f\\u1e41\\u1e43\\u0271\\u026f'},{b:'n',c:'\\u24dd\\uff4e\\u01f9\\u0144\\u00f1\\u1e45\\u0148\\u1e47\\u0146\\u1e4b\\u1e49\\u019e\\u0272\\u0149\\ua791\\ua7a5\\u043b\\u0509'},{b:'nj', c:'\\u01cc'},{b:'o',c:'\\u24de\\uff4f\\u00f2\\u00f3\\u00f4\\u1ed3\\u1ed1\\u1ed7\\u1ed5\\u00f5\\u1e4d\\u022d\\u1e4f\\u014d\\u1e51\\u1e53\\u014f\\u022f\\u0231\\u00f6\\u022b\\u1ecf\\u0151\\u01d2\\u020d\\u020f\\u01a1\\u1edd\\u1edb\\u1ee1\\u1edf\\u1ee3\\u1ecd\\u1ed9\\u01eb\\u01ed\\u00f8\\u01ff\\ua74b\\ua74d\\u0275\\u0254\\u1d11'},{b:'oe',c:'\\u0153'},{b:'oi',c:'\\u01a3'},{b:'oo',c:'\\ua74f'},{b:'ou',c:'\\u0223'},{b:'p',c:'\\u24df\\uff50\\u1e55\\u1e57\\u01a5\\u1d7d\\ua751\\ua753\\ua755\\u03c1'},{b:'q',c:'\\u24e0\\uff51\\u024b\\ua757\\ua759'}, {b:'r',c:'\\u24e1\\uff52\\u0155\\u1e59\\u0159\\u0211\\u0213\\u1e5b\\u1e5d\\u0157\\u1e5f\\u024d\\u027d\\ua75b\\ua7a7\\ua783'},{b:'s',c:'\\u24e2\\uff53\\u015b\\u1e65\\u015d\\u1e61\\u0161\\u1e67\\u1e63\\u1e69\\u0219\\u015f\\u023f\\ua7a9\\ua785\\u1e9b\\u0282'},{b:'ss',c:'\\u00df'},{b:'t',c:'\\u24e3\\uff54\\u1e6b\\u1e97\\u0165\\u1e6d\\u021b\\u0163\\u1e71\\u1e6f\\u0167\\u01ad\\u0288\\u2c66\\ua787'},{b:'th',c:'\\u00fe'},{b:'tz',c:'\\ua729'},{b:'u',c:'\\u24e4\\uff55\\u00f9\\u00fa\\u00fb\\u0169\\u1e79\\u016b\\u1e7b\\u016d\\u00fc\\u01dc\\u01d8\\u01d6\\u01da\\u1ee7\\u016f\\u0171\\u01d4\\u0215\\u0217\\u01b0\\u1eeb\\u1ee9\\u1eef\\u1eed\\u1ef1\\u1ee5\\u1e73\\u0173\\u1e77\\u1e75\\u0289'}, {b:'v',c:'\\u24e5\\uff56\\u1e7d\\u1e7f\\u028b\\ua75f\\u028c'},{b:'vy',c:'\\ua761'},{b:'w',c:'\\u24e6\\uff57\\u1e81\\u1e83\\u0175\\u1e87\\u1e85\\u1e98\\u1e89\\u2c73'},{b:'x',c:'\\u24e7\\uff58\\u1e8b\\u1e8d'},{b:'y',c:'\\u24e8\\uff59\\u1ef3\\u00fd\\u0177\\u1ef9\\u0233\\u1e8f\\u00ff\\u1ef7\\u1e99\\u1ef5\\u01b4\\u024f\\u1eff'},{b:'z',c:'\\u24e9\\uff5a\\u017a\\u1e91\\u017c\\u017e\\u1e93\\u1e95\\u01b6\\u0225\\u0240\\u2c6c\\ua763'}];\nvar UPLOADINDEXER = 1;", "for (var i=0; i <DIACRITICS.length; i+=1)\n\tfor (var chars=DIACRITICS[i].c,j=0;j<chars.length;j+=1)\n\t\tDIACRITICSMAP[chars[j]]=DIACRITICS[i].b;", "const DP = Date.prototype;\nconst SP = String.prototype;\nconst NP = Number.prototype;", "DIACRITICS = null;", "var CONTENTTYPES = {\n\taac: 'audio/aac',\n\tai: 'application/postscript',\n\tappcache: 'text/cache-manifest',\n\tavi: 'video/avi',\n\tbin: 'application/octet-stream',\n\tbmp: 'image/bmp',\n\tcoffee: 'text/coffeescript',\n\tcss: 'text/css',\n\tcsv: 'text/csv',\n\tdoc: 'application/msword',\n\tdocx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n\tdtd: 'application/xml-dtd',\n\teps: 'application/postscript',\n\texe: 'application/octet-stream',\n\tflac: 'audio/x-flac',\n\tgeojson: 'application/json',\n\tgif: 'image/gif',\n\tgzip: 'application/x-gzip',\n\theic: 'image/heic',\n\theif: 'image/heif',\n\thtm: 'text/html',\n\thtml: 'text/html',\n\tico: 'image/x-icon',\n\tics: 'text/calendar',\n\tifb: 'text/calendar',\n\tjpe: 'image/jpeg',\n\tjpeg: 'image/jpeg',\n\tjpg: 'image/jpeg',\n\tjs: 'text/javascript',\n\tjson: 'application/json',\n\tjsx: 'text/jsx',\n\tless: 'text/css',\n\tm4a: 'audio/mp4a-latm',\n\tm4v: 'video/x-m4v',\n\tmanifest: 'text/cache-manifest',\n\tmd: 'text/x-markdown',\n\tmid: 'audio/midi',\n\tmidi: 'audio/midi',\n\tmjs: 'text/javascript',\n\tmov: 'video/quicktime',\n\tmp3: 'audio/mpeg',\n\tmp4: 'video/mp4',\n\tmpe: 'video/mpeg',\n\tmpeg: 'video/mpeg',\n\tmpg: 'video/mpeg',\n\tmpga: 'audio/mpeg',\n\tmtl: 'text/plain',\n\tmv4: 'video/mv4',\n\tobj: 'text/plain',\n\togg: 'application/ogg',\n\togv: 'video/ogg',\n\tpackage: 'text/plain',\n\tpdf: 'application/pdf',\n\tpng: 'image/png',\n\tppt: 'application/vnd.ms-powerpoint',\n\tpptx: 'application/vnd.ms-powerpoint',\n\tps: 'application/postscript',\n\trar: 'application/x-rar-compressed',\n\trtf: 'text/rtf',\n\tsass: 'text/css',\n\tscss: 'text/css',\n\tsh: 'application/x-sh',\n\tstl: 'application/sla',\n\tsvg: 'image/svg+xml',\n\tswf: 'application/x-shockwave-flash',\n\ttar: 'application/x-tar',\n\ttif: 'image/tiff',\n\ttiff: 'image/tiff',\n\ttxt: 'text/plain',\n\tsql: 'text/plain',\n\twav: 'audio/x-wav',\n\twebm: 'video/webm',\n\twebp: 'image/webp',\n\twoff: 'application/font-woff',\n\twoff2: 'application/font-woff2',\n\txht: 'application/xhtml+xml',\n\txhtml: 'application/xhtml+xml',\n\txls: 'application/vnd.ms-excel',\n\txlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n\txml: 'application/xml',\n\txpm: 'image/x-xpixmap',\n\txsl: 'application/xml',\n\txslt: 'application/xslt+xml',\n\tzip: 'application/zip'\n};", "var dnscache = {};\nvar datetimeformat = {};", "global.DIFFARR = exports.diffarr = function(prop, db, form) {", "\tvar an = [];\n\tvar au = [];\n\tvar ar = [];\n\tvar is, oa, ob;", "\tfor (var i = 0; i < db.length; i++) {\n\t\toa = db[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < form.length; j++) {\n\t\t\tob = form[j];\n\t\t\tif (oa[prop] == ob[prop]) {\n\t\t\t\tau.push({ db: oa, form: ob });\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tar.push(oa[prop]);\n\t}", "\tfor (var i = 0; i < form.length; i++) {\n\t\tob = form[i];\n\t\tis = false;\n\t\tfor (var j = 0; j < db.length; j++) {\n\t\t\toa = db[j];\n\t\t\tif (ob[prop] == oa[prop]) {\n\t\t\t\tis = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!is)\n\t\t\tan.push(ob);\n\t}", "\tvar obj = {};\n\tobj.add = an;\n\tobj.upd = au;\n\tobj.rem = ar;\n\treturn obj;\n};", "exports.toURLEncode = function(value) {\n\tvar builder = [];", "\tfor (var key in value) {\n\t\tvar val = value[key];", "\t\tif (val == null || val === '')\n\t\t\tcontinue;", "\t\tvar type = typeof(val);\n\t\tswitch (type) {\n\t\t\tcase 'string':\n\t\t\t\tbuilder.push(key + '=' + encodeURIComponent(val));\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\t\tbuilder.push(key + '=' + encodeURIComponent(val.format('utc')));\n\t\t\t\tbreak;\n\t\t\tcase 'boolean':\n\t\t\tcase 'number':\n\t\t\t\tbuilder.push(key + '=' + val);\n\t\t\t\tbreak;\n\t\t\tcase 'object':\n\t\t\t\tif (val instanceof Array)\n\t\t\t\t\tbuilder.push(key + '=' + encodeURIComponent(val.join(',')));\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn builder.length ? builder.join('&') : '';\n};", "exports.resolve = function(url, callback, param) {", "\tvar uri;", "\ttry {\n\t\turi = Url.parse(url);\n\t} catch (e) {\n\t\tcallback(e);\n\t\treturn;\n\t}", "\tvar cache = dnscache[uri.host];", "\tif (!callback)\n\t\treturn cache;", "\tif (cache) {\n\t\turi.host = cache[0];\n\t\tcallback(null, uri, param, cache);\n\t\treturn;\n\t}", "\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (e)\n\t\t\tsetImmediate(dnsresolve_callback, uri, callback, param);\n\t\telse {\n\t\t\tdnscache[uri.host] = addresses;\n\t\t\turi.host = addresses[0];\n\t\t\tcallback(null, uri, param, addresses);\n\t\t}\n\t});\n};", "function dnsresolve_callback(uri, callback, param) {\n\tDns.resolve4(uri.hostname, function(e, addresses) {\n\t\tif (addresses && addresses.length) {\n\t\t\tdnscache[uri.host] = addresses;\n\t\t\turi.host = addresses[0];\n\t\t}\n\t\tcallback(e, uri, param, addresses);\n\t});\n}", "setImmediate(function() {\n\tglobal.F && NEWCOMMAND('clear_dnscache', function() {\n\t\tdnscache = {};\n\t});\n});", "exports.keywords = function(content, forSearch, alternative, max_count, max_length, min_length) {", "\tif (forSearch === undefined)\n\t\tforSearch = true;", "\tmin_length = min_length || 2;\n\tmax_count = max_count || 200;\n\tmax_length = max_length || 20;", "\tvar words = [];", "\tif (content instanceof Array) {\n\t\tfor (var i = 0, length = content.length; i < length; i++) {\n\t\t\tif (!content[i])\n\t\t\t\tcontinue;\n\t\t\tvar tmp = (forSearch ? content[i].toASCII().toLowerCase().replace(regexpY, 'i') : content[i].toLowerCase()).replace(regexpN, ' ').split(' ');\n\t\t\tif (!tmp || !tmp.length)\n\t\t\t\tcontinue;\n\t\t\tfor (var j = 0, jl = tmp.length; j < jl; j++)\n\t\t\t\twords.push(tmp[j]);\n\t\t}\n\t} else\n\t\twords = (forSearch ? content.toASCII().toLowerCase().replace(regexpY, 'i') : content.toLowerCase()).replace(regexpN, ' ').split(' ');", "\tif (!words)\n\t\twords = [];", "\tvar dic = {};\n\tvar counter = 0;", "\tfor (var i = 0, length = words.length; i < length; i++) {", "\t\tvar word = words[i].trim().replace(regexpCHARS, keywordscleaner);", "\t\tif (regexpCHINA.test(word)) {", "\t\t\tvar tmpw = word.split('', max_count);", "\t\t\tfor (var j = 0; j < tmpw.length; j++) {\n\t\t\t\tword = tmpw[j];\n\t\t\t\tif (dic[word])\n\t\t\t\t\tdic[word]++;\n\t\t\t\telse\n\t\t\t\t\tdic[word] = 1;\n\t\t\t\tcounter++;\n\t\t\t}", "\t\t\tif (counter >= max_count)\n\t\t\t\tbreak;", "\t\t\tcontinue;\n\t\t}", "\t\tif (word.length < min_length)\n\t\t\tcontinue;", "\t\tif (counter >= max_count)\n\t\t\tbreak;", "\t\t// Gets 80% length of word\n\t\tif (alternative) {\n\t\t\tvar size = (word.length / 100) * 80;\n\t\t\tif (size > min_length + 1)\n\t\t\t\tword = word.substring(0, size);\n\t\t}", "\t\tif (word.length < min_length || word.length > max_length)\n\t\t\tcontinue;", "\t\tif (dic[word])\n\t\t\tdic[word]++;\n\t\telse\n\t\t\tdic[word] = 1;", "\t\tcounter++;\n\t}", "\tvar keys = Object.keys(dic);", "\tkeys.sort(function(a, b) {\n\t\tvar countA = dic[a];\n\t\tvar countB = dic[b];\n\t\treturn countA > countB ? -1 : countA < countB ? 1 : 0;\n\t});", "\treturn keys;\n};", "function keywordscleaner(c) {\n\treturn c.charCodeAt(0) < 200 ? '' : c;\n}", "function parseProxy(p) {\n\tvar key = 'proxy_' + p;\n\tif (F.temporary.other[key])\n\t\treturn F.temporary.other[key];", "\tif (p.indexOf('://') === -1)\n\t\tp = 'http://' + p;", "\tvar obj = Url.parse(p);", "\tif (obj.auth)\n\t\tobj._auth = 'Basic ' + Buffer.from(obj.auth).toString('base64');", "\tobj.port = +obj.port;", "\tif (p.indexOf('https:') !== -1) {\n\t\tobj.rejectUnauthorized = false;\n\t\tobj.requestCert = true;\n\t}", "\treturn F.temporary.other[key] = obj;\n}", "global.REQUEST = function(opt, callback) {", "\tvar options = { length: 0, timeout: opt.timeout || CONF.default_restbuilder_timeout, encoding: opt.encoding || ENCODING, callback: opt.callback || NOOP, post: true, redirect: 0 };\n\tvar proxy;", "\tif (callback)\n\t\topt.callback = callback;", "\tif (global.F)\n\t\tglobal.F.stats.performance.external++;", "\tif (opt.headers)\n\t\topt.headers = exports.extend({}, opt.headers);\n\telse\n\t\topt.headers = {};", "\tif (!opt.method)\n\t\topt.method = 'GET';", "\toptions.$totalinit = opt;", "\t// opt.encrypt {String}\n\t// opt.limit in kB\n\t// opt.key {Buffer}\n\t// opt.cert {Buffer}\n\t// opt.onprogress(percentage)\n\t// opt.ondata(chunk, percentage)", "\tif (opt.ondata)\n\t\toptions.ondata = opt.ondata;", "\tif (opt.onprogress)\n\t\toptions.onprogress = opt.onprogress;", "\tif (opt.proxy)\n\t\tproxy = parseProxy(opt.proxy);", "\tif (opt.xhr)\n\t\topt.headers['X-Requested-With'] = 'XMLHttpRequest';", "\toptions.response = opt.response ? opt.response : {};\n\toptions.response.body = '';\n\toptions.iserror = false;", "\tif (opt.resolve || opt.dnscache)\n\t\toptions.resolve = true;", "\tif (opt.custom)\n\t\toptions.custom = true;", "\tif (opt.noredirect)\n\t\toptions.noredirect = true;", "\tif (opt.keepalive)\n\t\toptions.keepalive = true;", "\tif (opt.type) {\n\t\tswitch (opt.type) {\n\t\t\tcase 'plain':\n\t\t\t\topt.headers[CT] = 'text/plain';\n\t\t\t\tbreak;\n\t\t\tcase 'html':\n\t\t\t\topt.headers[CT] = 'text/html';\n\t\t\t\tbreak;\n\t\t\tcase 'raw':\n\t\t\t\topt.headers[CT] = 'application/octet-stream';\n\t\t\t\tbreak;\n\t\t\tcase 'json':\n\t\t\t\topt.headers[CT] = 'application/json';\n\t\t\t\tbreak;\n\t\t\tcase 'urlencoded':\n\t\t\t\topt.headers[CT] = 'application/x-www-form-urlencoded';\n\t\t\t\tbreak;\n\t\t\tcase 'xml':\n\t\t\t\topt.headers[CT] = 'text/xml';\n\t\t\t\tbreak;\n\t\t}\n\t}", "\tif (opt.files) {\n\t\toptions.boundary = '----TOTALFILE_' + Math.random().toString(36).substring(3);\n\t\topt.headers[CT] = 'multipart/form-data; boundary=' + options.boundary;\n\t\toptions.files = opt.files;\n\t\toptions.upload = true;", "\t\t// Must be object { key: value }\n\t\tif (opt.body)\n\t\t\toptions.body = opt.body;", "\t} else {\n\t\tif (opt.body) {\n\t\t\tif (!(opt.body instanceof Buffer)) {\n\t\t\t\tif (opt.encrypt) {\n\t\t\t\t\topt.body = exports.encrypt_data(opt.body, opt.encrypt);\n\t\t\t\t\topt.headers['X-Encryption'] = 'a';\n\t\t\t\t}\n\t\t\t\topt.body = Buffer.from(opt.body, ENCODING);\n\t\t\t}\n\t\t\topt.headers['Content-Length'] = opt.body.length;\n\t\t}\n\t\toptions.body = opt.body;\n\t}", "\tif (opt.cookies) {\n\t\tvar builder = '';\n\t\tfor (var m in opt.cookies)\n\t\t\tbuilder += (builder ? '; ' : '') + m + '=' + opt.cookies[m];\n\t\tif (builder)\n\t\t\topt.headers.Cookie = builder;\n\t}", "\tif (opt.query) {\n\t\tif (typeof(opt.query) !== 'string')\n\t\t\topt.query = U.toURLEncode(opt.query);\n\t\tif (opt.url) {\n\t\t\tif (opt.url.lastIndexOf('?') === -1)\n\t\t\t\topt.url += '?' + opt.query;\n\t\t\telse\n\t\t\t\topt.url += '&' + opt.query;\n\t\t} else if (opt.unixsocket.path) {\n\t\t\tif (opt.unixsocket.path.lastIndexOf('?') === -1)\n\t\t\t\topt.unixsocket.path += '?' + opt.query;\n\t\t\telse\n\t\t\t\topt.unixsocket.path += '&' + opt.query;\n\t\t}\n\t}", "\tvar uri = opt.unixsocket ? { socketPath: opt.unixsocket.socket, path: opt.unixsocket.path } : Url.parse(opt.url);", "\tif ((opt.unixsocket && !uri.socketPath) || (!opt.unixsocket && (!uri.hostname || !uri.host))) {\n\t\toptions.response.canceled = true;\n\t\topt.callback && opt.callback('Invalid hostname', options.response);\n\t\treturn;\n\t}", "\turi.method = opt.method;\n\turi.headers = opt.headers;", "\tif (options.insecure) {\n\t\turi.rejectUnauthorized = false;\n\t\turi.requestCert = true;\n\t}", "\toptions.uri = uri;\n\toptions.opt = opt;", "\tif (opt.key)\n\t\turi.key = opt.key;", "\tif (opt.cert)\n\t\turi.cert = opt.cert;", "\tif (opt.dhparam)\n\t\turi.dhparam = opt.dhparam;", "\tif (options.resolve && (opt.unixsocket || (uri.hostname === 'localhost' || uri.hostname.charCodeAt(0) < 64)))\n\t\toptions.resolve = false;", "\tif (!opt.unixsocket && CONF.default_proxy && !proxy && !PROXYBLACKLIST[uri.hostname])\n\t\tproxy = parseProxy(CONF.default_proxy);", "\tif (!opt.unixsocket && proxy && (uri.hostname === 'localhost' || uri.hostname === '127.0.0.1'))\n\t\tproxy = null;", "\toptions.proxy = proxy;", "\tif (proxy && uri.protocol === 'https:') {\n\t\tproxy.tls = true;\n\t\turi.agent = new ProxyAgent(options);\n\t\turi.agent.request = Http.request;\n\t\turi.agent.createSocket = createSecureSocket;\n\t\turi.agent.defaultPort = 443;\n\t}", "\tif (options.keepalive && !options.proxy) {\n\t\tif (uri.protocol === 'https:') {\n\t\t\tif (!uri.port)\n\t\t\t\turi.port = 443;\n\t\t\turi.agent = KeepAliveHttps;\n\t\t} else\n\t\t\turi.agent = KeepAlive;\n\t} else\n\t\turi.agent = null;", "\tif (proxy)\n\t\trequest_call(uri, options);\n\telse if (options.resolve)\n\t\texports.resolve(opt.url, request_resolve, options);\n\telse\n\t\trequest_call(uri, options);\n};", "function request_resolve(err, uri, options, origin) {\n\tif (!err) {\n\t\toptions.uri.host = uri.host;\n\t\toptions.origin = origin;\n\t}\n\trequest_call(options.uri, options);\n}", "function ProxyAgent(options) {\n\tvar self = this;\n\tself.options = options;\n\tself.maxSockets = Http.Agent.defaultMaxSockets;\n\tself.requests = [];\n}", "const PAP = ProxyAgent.prototype;", "PAP.createConnection = function(pending) {\n\tvar self = this;\n\tself.createSocket(pending, function(socket) {\n\t\tpending.request.onSocket(socket);\n\t});\n};", "PAP.createSocket = function(options, callback) {", "\tvar self = this;\n\tvar proxy = self.options.proxy;\n\tvar uri = self.options.uri;", "\tPROXYOPTIONS.host = proxy.hostname;\n\tPROXYOPTIONS.port = proxy.port;\n\tPROXYOPTIONS.path = PROXYOPTIONS.headers.host = uri.hostname + ':' + (uri.port || '443');", "\tif (proxy._auth)\n\t\tPROXYOPTIONS.headers['Proxy-Authorization'] = proxy._auth;", "\tvar req = self.request(PROXYOPTIONS);\n\treq.setTimeout(10000);\n\treq.on('response', proxyagent_response);\n\treq.on('connect', function(res, socket) {", "\t\tif (res.statusCode === 200) {\n\t\t\tsocket.$req = req;\n\t\t\tcallback(socket);\n\t\t} else {\n\t\t\tvar err = new Error('Proxy could not be established (maybe a problem in auth), code: ' + res.statusCode);\n\t\t\terr.code = 'ECONNRESET';\n\t\t\treq.destroy && req.destroy();\n\t\t\treq = null;\n\t\t\tself.requests = null;\n\t\t\tself.options = null;\n\t\t}", "\t});", "\treq.on('error', function(err) {\n\t\tvar e = new Error('Request Proxy \"proxy {0} --> target {1}\": {2}'.format(PROXYOPTIONS.host + ':' + proxy.port, PROXYOPTIONS.path, err.toString()));\n\t\te.code = err.code;\n\t\treq.destroy && req.destroy();\n\t\treq = null;\n\t\tself.requests = null;\n\t\tself.options = null;\n\t});", "\treq.end();\n};", "function proxyagent_response(res) {\n\tres.upgrade = true;\n}", "PAP.addRequest = function(req, options) {\n\tthis.createConnection({ host: options.host, port: options.port, request: req });\n};", "function createSecureSocket(options, callback) {\n\tvar self = this;\n\tPAP.createSocket.call(self, options, function(socket) {\n\t\tPROXYTLS.servername = self.options.uri.hostname;\n\t\tPROXYTLS.headers = self.options.uri.headers;\n\t\tPROXYTLS.socket = socket;\n\t\tvar tls = Tls.connect(0, PROXYTLS);\n\t\tcallback(tls);\n\t});\n}", "function request_call(uri, options) {", "\tvar opt;", "\tif (options.proxy && !options.proxy.tls) {\n\t\topt = PROXYOPTIONSHTTP;\n\t\topt.port = options.proxy.port;\n\t\topt.host = options.proxy.hostname;\n\t\topt.path = uri.href;\n\t\topt.headers = uri.headers;\n\t\topt.method = uri.method;\n\t\topt.headers.host = uri.host;\n\t\tif (options.proxy._auth)\n\t\t\topt.headers['Proxy-Authorization'] = options.proxy._auth;\n\t} else\n\t\topt = uri;", "\tvar connection = uri.protocol === 'https:' ? Https : Http;\n\tvar req = opt.method === 'GET' ? connection.get(opt, request_response) : connection.request(opt, request_response);", "\treq.$options = options;\n\treq.$uri = uri;", "\tif (!options.callback) {\n\t\treq.on('error', NOOP);\n\t\treturn;\n\t}", "\treq.on('error', request_process_error);\n\toptions.timeoutid && clearTimeout(options.timeoutid);\n\toptions.timeoutid = setTimeout(request_process_timeout, options.timeout, req);", "\treq.on('response', request_assign_res);", "\tif (options.upload) {\n\t\toptions.first = true;\n\t\toptions.files.wait(function(file, next) {\n\t\t\trequest_writefile(req, options, file, next);\n\t\t}, function() {", "\t\t\tif (options.iserror)\n\t\t\t\treturn;", "\t\t\tif (options.body) {\n\t\t\t\tfor (var key in options.body) {\n\t\t\t\t\tvar value = options.body[key];\n\t\t\t\t\tif (value != null) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + key + '\"' + NEWLINE + NEWLINE + value);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\trequest_process_error.apply(req, e);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (options.first)\n\t\t\t\t\t\t\toptions.first = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\treq.end(NEWLINE + '--' + options.boundary + '--');\n\t\t});\n\t} else\n\t\treq.end(options.body);\n}", "function request_process_error(err) {\n\tvar options = this.$options;\n\toptions.iserror = true;\n\tif (options.callback && !options.done) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\toptions.canceled = true;\n\t\toptions.response.status = 0;\n\t\toptions.response.host = this.$uri.host;\n\t\toptions.callback(err, options.response);\n\t\toptions.callback = null;\n\t}\n}", "function request_process_timeout(req) {\n\tvar options = req.$options;\n\toptions.iserror = true;\n\tif (options.callback) {\n\t\tif (options.timeoutid) {\n\t\t\tclearTimeout(options.timeoutid);\n\t\t\toptions.timeoutid = null;\n\t\t}\n\t\treq.socket.destroy();\n\t\treq.socket.end();\n\t\treq.destroy();\n\t\toptions.response.status = 408;\n\t\toptions.response.host = req.$uri.host;\n\t\toptions.canceled = true;\n\t\toptions.callback(exports.httpstatus(408), options.response);\n\t\toptions.callback = null;\n\t}\n}", "function request_process_ok() {\n\tvar options = this.req.$options;\n\tif (options.timeoutid) {\n\t\tclearTimeout(options.timeoutid);\n\t\toptions.timeoutid = null;\n\t}\n}", "function request_assign_res(response) {\n\tresponse.req = this;\n}", "function request_writefile(req, options, file, next) {", "\tif (options.iserror) {\n\t\tnext();\n\t\treturn;\n\t}", "\tvar isbuffer = file.buffer instanceof Buffer;\n\tvar filename = (isbuffer ? file.name : exports.getName(file.filename));", "\treq.write((options.first ? '' : NEWLINE) + '--' + options.boundary + NEWLINE + 'Content-Disposition: form-data; name=\"' + file.name + '\"; filename=\"' + filename + '\"' + NEWLINE + 'Content-Type: ' + exports.getContentType(exports.getExtension(filename)) + NEWLINE + NEWLINE);", "\tif (options.first)\n\t\toptions.first = false;", "\tif (isbuffer) {\n\t\ttry {\n\t\t\treq.write(file.buffer);\n\t\t} catch (e) {\n\t\t\trequest_process_error.apply(req, e);\n\t\t}\n\t\tnext();\n\t} else {\n\t\tvar stream = Fs.createReadStream(file.filename);\n\t\tstream.once('close', next);\n\t\tstream.pipe(req, STREAMPIPE);\n\t}\n}", "function request_response(res) {", "\tvar options = this.$options;\n\tvar uri = this.$uri;", "\tres._buffer = null;\n\tres._bufferlength = 0;", "\t// We have redirect\n\tif (res.statusCode === 301 || res.statusCode === 302) {", "\t\tif (options.noredirect) {\n\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;\n\t\t\tif (options.callback) {\n\t\t\t\toptions.response.origin = options.origin;\n\t\t\t\toptions.response.status = res.statusCode;\n\t\t\t\toptions.response.headers = res.headers;\n\t\t\t\tif (options.custom) {\n\t\t\t\t\toptions.response.stream = res;\n\t\t\t\t\toptions.callback(null, options.response);\n\t\t\t\t} else {\n\t\t\t\t\toptions.response.host = uri.host;\n\t\t\t\t\toptions.response.headers = res.headers;\n\t\t\t\t\toptions.callback(null, options.response);\n\t\t\t\t}\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\tif (options.redirect > (options.redirects || 3)) {", "\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.canceled = true;\n\t\t\toptions.response.origin = options.origin;\n\t\t\toptions.response.headers = res.headers;", "\t\t\tif (options.callback) {\n\t\t\t\tif (options.custom) {\n\t\t\t\t\toptions.response.status = res.statusCode;\n\t\t\t\t\toptions.response.stream = res;\n\t\t\t\t\toptions.callback('Too many redirects', options.response);\n\t\t\t\t} else {\n\t\t\t\t\toptions.response.status = 0;\n\t\t\t\t\toptions.response.host = uri.host;\n\t\t\t\t\toptions.callback('Too many redirects', options.response);\n\t\t\t\t}\n\t\t\t\toptions.callback = null;\n\t\t\t}", "\t\t\tres.req.removeAllListeners();\n\t\t\tres.removeAllListeners();\n\t\t\tres.req = null;\n\t\t\tres = null;\n\t\t\treturn;\n\t\t}", "\t\toptions.redirect++;", "\t\tvar loc = res.headers.location;\n\t\tvar proto = loc.substring(0, 6);", "\t\tif (proto !== 'http:/' && proto !== 'https:')\n\t\t\tloc = uri.protocol + '//' + uri.hostname + (uri.port && !SKIPPORTS[uri.port] ? (':' + uri.port) : '') + loc;", "\t\tvar tmp = Url.parse(loc);\n\t\ttmp.headers = uri.headers;", "\t\t// Transfers cookies\n\t\tif (!options.nocookies) {\n\t\t\tvar cookies = res.headers['set-cookie'];\n\t\t\tif (cookies) {", "\t\t\t\tif (options.$totalinit.cook && !options.$totalinit.cookies)\n\t\t\t\t\toptions.$totalinit.cookies = {};", "\t\t\t\tif (!options.cookies)\n\t\t\t\t\toptions.cookies = {};", "\t\t\t\tfor (var i = 0; i < cookies.length; i++) {\n\t\t\t\t\tvar cookie = cookies[i];\n\t\t\t\t\tvar index = cookie.indexOf(';');\n\t\t\t\t\tif (index !== -1){\n\t\t\t\t\t\tcookie = cookie.substring(0, index);\n\t\t\t\t\t\tindex = cookie.indexOf('=');\n\t\t\t\t\t\tif (index !== -1) {\n\t\t\t\t\t\t\tvar key = decodeURIComponent(cookie.substring(0, index));\n\t\t\t\t\t\t\toptions.cookies[key] = decodeURIComponent(cookie.substring(index + 1));\n\t\t\t\t\t\t\tif (options.$totalinit.cookies)\n\t\t\t\t\t\t\t\toptions.$totalinit.cookies[key] = options.cookies[key];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tvar builder = '';\n\t\t\t\tfor (var m in options.cookies)\n\t\t\t\t\tbuilder += (builder ? '; ' : '') + encodeURIComponent(m) + '=' + encodeURIComponent(options.cookies[m]);", "\t\t\t\tif (tmp.headers.cookie)\n\t\t\t\t\ttmp.headers.cookie = builder;\n\t\t\t\telse\n\t\t\t\t\ttmp.headers.Cookie = builder;\n\t\t\t}\n\t\t}", "\t\t// tmp.agent = false;\n\t\ttmp.method = uri.method;", "\t\tres.req.removeAllListeners();\n\t\tres.req = null;", "\t\tif (options.proxy && tmp.protocol === 'https:') {\n\t\t\t// TLS?\n\t\t\toptions.proxy.tls = true;\n\t\t\toptions.uri = tmp;\n\t\t\toptions.uri.agent = new ProxyAgent(options);\n\t\t\toptions.uri.agent.request = Http.request;\n\t\t\toptions.uri.agent.createSocket = createSecureSocket;\n\t\t\toptions.uri.agent.defaultPort = 443;\n\t\t}", "\t\tif (!options.resolve) {\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\treturn request_call(tmp, options);\n\t\t}", "\t\texports.resolve(tmp, function(err, u, param, origin) {\n\t\t\tif (!err) {\n\t\t\t\ttmp.host = u.host;\n\t\t\t\toptions.origin = origin;\n\t\t\t}\n\t\t\tres.removeAllListeners();\n\t\t\tres = null;\n\t\t\trequest_call(tmp, options);\n\t\t});", "\t\treturn;\n\t}", "\toptions.length = +res.headers['content-length'] || 0;", "\t// Shared cookies\n\tif (options.$totalinit.cook) {", "\t\tif (!options.$totalinit.cookies)\n\t\t\toptions.$totalinit.cookies = {};", "\t\tvar arr = (res.headers['set-cookie'] || '');", "\t\t// Only the one value\n\t\tif (arr && !(arr instanceof Array))\n\t\t\tarr = [arr];", "\t\tif (arr instanceof Array) {\n\t\t\tfor (var i = 0; i < arr.length; i++) {\n\t\t\t\tvar line = arr[i];\n\t\t\t\tvar end = line.indexOf(';');\n\t\t\t\tif (end === -1)\n\t\t\t\t\tend = line.length;\n\t\t\t\tline = line.substring(0, end);\n\t\t\t\tvar index = line.indexOf('=');\n\t\t\t\tif (index !== -1)\n\t\t\t\t\toptions.$totalinit.cookies[line.substring(0, index)] = decodeURIComponent(line.substring(index + 1));\n\t\t\t}\n\t\t}\n\t}", "\tif (res.statusCode === 204) {\n\t\toptions.done = true;\n\t\tif (options.custom) {\n\t\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\t\toptions.response.origin = options.origin;\n\t\t\toptions.response.status = res.statusCode;\n\t\t\toptions.response.headers = res.headers;\n\t\t\toptions.response.stream = res;\n\t\t\toptions.callback(null, options.response);\n\t\t\toptions.callback = null;\n\t\t} else\n\t\t\trequest_process_end.call(res);\n\t\treturn;\n\t}", "\toptions.timeoutid && res.once('data', request_process_ok);", "\tvar encoding = res.headers['content-encoding'] || '';\n\tif (encoding)\n\t\tencoding = encoding.split(',')[0];", "\tif (options.custom) {\n\t\toptions.timeoutid && clearTimeout(options.timeoutid);\n\t\toptions.response.origin = options.origin;\n\t\toptions.response.status = res.statusCode;\n\t\toptions.response.headers = res.headers;\n\t\toptions.response.stream = res;\n\t\toptions.callback && options.callback(null, options.response);\n\t\toptions.callback = null;\n\t} else {\n\t\tif (COMPRESS[encoding]) {\n\t\t\tvar zlib = encoding === 'gzip' ? Zlib.createGunzip() : Zlib.createInflate();\n\t\t\tzlib._buffer = res.buffer;\n\t\t\tzlib.headers = res.headers;\n\t\t\tzlib.statusCode = res.statusCode;\n\t\t\tzlib.res = res;\n\t\t\tzlib.on('data', request_process_data);\n\t\t\tzlib.on('end', request_process_end);\n\t\t\tres.pipe(zlib);\n\t\t} else {\n\t\t\tres.on('data', request_process_data);\n\t\t\tres.on('end', request_process_end);\n\t\t}\n\t}", "\tres.resume();\n}", "function request_process_data(chunk) {\n\tvar self = this;\n\t// Is Zlib\n\tif (!self.req)\n\t\tself = self.res;\n\tvar options = self.req.$options;\n\tif (options.canceled || (options.limit && self._bufferlength > options.limit))\n\t\treturn;\n\tif (self._buffer) {\n\t\tCONCAT[0] = self._buffer;\n\t\tCONCAT[1] = chunk;\n\t\tself._buffer = Buffer.concat(CONCAT);\n\t} else\n\t\tself._buffer = chunk;\n\tself._bufferlength += chunk.length;\n\toptions.ondata && options.ondata(chunk, options.length ? (self._bufferlength / options.length) * 100 : 0);\n\toptions.onprogress && options.onprogress(options.length ? (self._bufferlength / options.length) * 100 : 0);\n}", "function request_process_end() {", "\tvar res = this;", "\t// Is Zlib\n\tif (!res.req)\n\t\tres = res.res;", "\tvar self = res;\n\tvar options = self.req.$options;\n\tvar uri = self.req.$uri;\n\tvar data;", "\toptions.socket && options.uri.agent.destroy();\n\toptions.timeoutid && clearTimeout(options.timeoutid);", "\tif (options.canceled)\n\t\treturn;", "\tvar ct = self.headers['content-type'];", "\tif (!ct || REG_TEXTAPPLICATION.test(ct)) {\n\t\tdata = self._buffer ? options.encoding === 'binary' ? self._buffer : self._buffer.toString(options.encoding) : '';\n\t\tif (options.opt.encrypt && typeof(data) === 'string')\n\t\t\tdata = exports.decrypt_data(data, options.opt.encrypt);\n\t} else\n\t\tdata = self._buffer;", "\toptions.canceled = true;\n\tself._buffer = undefined;", "\tif (options.callback) {\n\t\toptions.response.origin = options.origin;\n\t\toptions.response.headers = self.headers;\n\t\toptions.response.body = data;\n\t\toptions.response.status = self.statusCode;\n\t\toptions.response.host = uri.host || uri.socketPath;\n\t\toptions.response.cookies = options.cookies;\n\t\toptions.callback(null, options.response);\n\t\toptions.callback = null;\n\t}", "\tif (res.statusCode !== 204) {\n\t\tres.req && res.req.removeAllListeners();\n\t\tres.removeAllListeners();\n\t}\n}", "exports.btoa = function(str) {\n\treturn (str instanceof Buffer) ? str.toString('base64') : Buffer.from(str.toString(), 'utf8').toString('base64');\n};", "exports.atob = function(str) {\n\treturn Buffer.from(str, 'base64').toString('utf8');\n};", "/**\n * Trim string properties\n * @param {Object} obj\n * @return {Object}\n */\nexports.trim = function(obj, clean) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type === 'string') {\n\t\tobj = obj.trim();\n\t\treturn clean && !obj ? undefined : obj;\n\t}", "\tif (obj instanceof Array) {\n\t\tfor (var i = 0, length = obj.length; i < length; i++) {", "\t\t\tvar item = obj[i];\n\t\t\ttype = typeof(item);", "\t\t\tif (type === 'object') {\n\t\t\t\texports.trim(item, clean);\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (type !== 'string')\n\t\t\t\tcontinue;", "\t\t\tobj[i] = item.trim();\n\t\t\tif (clean && !obj[i])\n\t\t\t\tobj[i] = undefined;\n\t\t}", "\t\treturn obj;\n\t}", "\tif (type !== 'object')\n\t\treturn obj;", "\tfor (var key in obj) {\n\t\tvar val = obj[key];\n\t\tvar type = typeof(val);\n\t\tif (type === 'object') {\n\t\t\texports.trim(val, clean);\n\t\t\tcontinue;\n\t\t} else if (type !== 'string')\n\t\t\tcontinue;\n\t\tobj[key] = val.trim();\n\t\tif (clean && !obj[key])\n\t\t\tobj[key] = undefined;\n\t}", "\treturn obj;\n};", "/**\n * Noop function\n * @return {Function} Empty function.\n */\nglobal.NOOP = function() {};", "/**\n * Read HTTP status\n * @param {Number} code HTTP code status.\n * @param {Boolean} addCode Add code number to HTTP status.\n * @return {String}\n */\nexports.httpstatus = function(code, addCode) {\n\tif (addCode === undefined)\n\t\taddCode = true;\n\treturn (addCode ? code + ': ' : '') + Http.STATUS_CODES[code];\n};", "/**\n * Extend object\n * @param {Object} target Target object.\n * @param {Object} source Source object.\n * @param {Boolean} rewrite Rewrite exists values (optional, default true).\n * @return {Object} Modified object.\n */\nexports.extend = function(target, source, rewrite) {", "\tif (!target || !source)\n\t\treturn target;", "\tif (typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tif (rewrite === undefined)\n\t\trewrite = true;", "\tfor (var key in source) {\n\t\tif (rewrite || target[key] === undefined)\n\t\t\ttarget[key] = exports.clone(source[key]);\n\t}", "\treturn target;\n};", "exports.extend_headers = function(first, second) {\n\tvar keys = Object.keys(first);\n\tvar headers = {};", "\tvar i = keys.length;\n\twhile (i--)\n\t\theaders[keys[i]] = first[keys[i]];", "\tkeys = Object.keys(second);\n\ti = keys.length;", "\twhile (i--)\n\t\theaders[keys[i]] = second[keys[i]];", "\treturn headers;\n};", "exports.extend_headers2 = function(first, second) {\n\tvar keys = Object.keys(second);\n\tvar i = keys.length;\n\twhile (i--)\n\t\tfirst[keys[i]] = second[keys[i]];\n\treturn first;\n};", "/**\n * Clones object\n * @param {Object} obj\n * @param {Object} skip Optional, can be only object e.g. { name: true, age: true }.\n * @param {Boolean} skipFunctions It doesn't clone functions, optional --> default false.\n * @return {Object}\n */\nglobal.CLONE = exports.clone = function(obj, skip, skipFunctions) {", "\tif (!obj)\n\t\treturn obj;", "\tvar type = typeof(obj);\n\tif (type !== 'object' || obj instanceof Date || obj instanceof Error)\n\t\treturn obj;", "\tvar length;\n\tvar o;", "\tif (obj instanceof Array) {", "\t\tlength = obj.length;\n\t\to = new Array(length);", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\ttype = typeof(obj[i]);\n\t\t\tif (type !== 'object' || obj[i] instanceof Date || obj[i] instanceof Error) {\n\t\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\t\tcontinue;\n\t\t\t\to[i] = obj[i];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\to[i] = exports.clone(obj[i], skip, skipFunctions);\n\t\t}", "\t\treturn o;\n\t}", "\to = {};", "\tfor (var m in obj) {", "\t\tif (skip && skip[m])\n\t\t\tcontinue;", "\t\tvar val = obj[m];", "\t\tif (val instanceof Buffer) {\n\t\t\tvar copy = Buffer.alloc(val.length);\n\t\t\tval.copy(copy);\n\t\t\to[m] = copy;\n\t\t\tcontinue;\n\t\t}", "\t\tvar type = typeof(val);\n\t\tif (type !== 'object' || val instanceof Date || val instanceof Error) {\n\t\t\tif (skipFunctions && type === 'function')\n\t\t\t\tcontinue;\n\t\t\to[m] = val;\n\t\t\tcontinue;\n\t\t}", "\t\to[m] = exports.clone(obj[m], skip, skipFunctions);\n\t}", "\treturn o;\n};", "/**\n * Copy values from object to object\n * @param {Object} source Object source\n * @param {Object} target Object target (optional)\n * @return {Object} Modified object.\n */\nexports.copy = function(source, target) {", "\tif (target === undefined)\n\t\treturn exports.extend({}, source, true);", "\tif (!target || !source || typeof(target) !== 'object' || typeof(source) !== 'object')\n\t\treturn target;", "\tfor (var key in source) {\n\t\tif (target[key] !== undefined)\n\t\t\ttarget[key] = exports.clone(source[key]);\n\t}", "\treturn target;\n};", "/**\n * Reduces an object\n * @param {Object} source Source object.\n * @param {String Array or Object} prop Other properties than these ones will be removed.\n * @param {Boolean} reverse Reverse reducing (prop will be removed), default: false.\n * @return {Object}\n */\nexports.reduce = function(source, prop, reverse) {", "\tif (!(prop instanceof Array)) {\n\t\tif (typeof(prop) === 'object')\n\t\t\treturn exports.reduce(source, Object.keys(prop), reverse);\n\t}", "\tif (source instanceof Array) {\n\t\tvar arr = [];\n\t\tfor (var i = 0, length = source.length; i < length; i++)\n\t\t\tarr.push(exports.reduce(source[i], prop, reverse));\n\t\treturn arr;\n\t}", "\tvar output = {};", "\tfor (var o in source) {\n\t\tif (reverse) {\n\t\t\tif (prop.indexOf(o) === -1)\n\t\t\t\toutput[o] = source[o];\n\t\t} else {\n\t\t\tif (prop.indexOf(o) !== -1)\n\t\t\t\toutput[o] = source[o];\n\t\t}\n\t}", "\treturn output;\n};", "/**\n * Checks if is relative url\n * @param {String} url\n * @return {Boolean}\n */\nexports.isrelative = function(url) {\n\treturn !(url.substring(0, 2) === '//' || url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1);\n};", "/**\n * Streamer method\n * @param {String/Buffer} beg\n * @param {String/Buffer} end\n * @param {Function(value, index)} callback\n */\nexports.streamer = function(beg, end, callback, skip, stream, raw) {", "\tif (typeof(end) === 'function') {\n\t\tstream = skip;\n\t\tskip = callback;\n\t\tcallback = end;\n\t\tend = undefined;\n\t}", "\tif (typeof(skip) === 'object') {\n\t\tstream = skip;\n\t\tskip = 0;\n\t}", "\tvar indexer = 0;\n\tvar buffer = Buffer.alloc(0);\n\tvar canceled = false;\n\tvar fn;", "\tif (skip === undefined)\n\t\tskip = 0;", "\tif (!(beg instanceof Buffer))\n\t\tbeg = Buffer.from(beg, 'utf8');", "\tif (end && !(end instanceof Buffer))\n\t\tend = Buffer.from(end, 'utf8');", "\tif (!end) {\n\t\tvar length = beg.length;\n\t\tfn = function(chunk) {", "\t\t\tif (!chunk || canceled)\n\t\t\t\treturn;", "\t\t\tCONCAT[0] = buffer;\n\t\t\tCONCAT[1] = chunk;", "\t\t\tvar f = 0;", "\t\t\tif (buffer.length) {\n\t\t\t\tf = buffer.length - beg.length;\n\t\t\t\tif (f < 0)\n\t\t\t\t\tf = 0;\n\t\t\t}", "\t\t\tbuffer = Buffer.concat(CONCAT);", "\t\t\tvar index = buffer.indexOf(beg, f);\n\t\t\tif (index === -1)\n\t\t\t\treturn;", "\t\t\twhile (index !== -1) {", "\t\t\t\tif (skip)\n\t\t\t\t\tskip--;\n\t\t\t\telse {\n\t\t\t\t\tif (callback(raw ? buffer.slice(0, index + length) : buffer.toString('utf8', 0, index + length), indexer++) === false)\n\t\t\t\t\t\tcanceled = true;\n\t\t\t\t}", "\t\t\t\tif (canceled)\n\t\t\t\t\treturn;", "\t\t\t\tbuffer = buffer.slice(index + length);\n\t\t\t\tindex = buffer.indexOf(beg);\n\t\t\t\tif (index === -1)\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t};", "\t\tstream && stream.on('end', () => fn(beg));\n\t\treturn fn;\n\t}", "\tvar blength = beg.length;\n\tvar elength = end.length;\n\tvar bi = -1;\n\tvar ei = -1;\n\tvar is = false;", "\tfn = function(chunk) {", "\t\tif (!chunk || canceled)\n\t\t\treturn;", "\t\tCONCAT[0] = buffer;\n\t\tCONCAT[1] = chunk;\n\t\tbuffer = Buffer.concat(CONCAT);", "\t\tif (!is) {\n\t\t\tvar f = CONCAT[0].length - beg.length;\n\t\t\tif (f < 0)\n\t\t\t\tf = 0;\n\t\t\tbi = buffer.indexOf(beg, f);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t}", "\t\tif (is) {\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}", "\t\twhile (bi !== -1) {", "\t\t\tif (skip)\n\t\t\t\tskip--;\n\t\t\telse {\n\t\t\t\tif (callback(raw ? buffer.slice(bi, ei + elength) : buffer.toString('utf8', bi, ei + elength), indexer++) === false)\n\t\t\t\t\tcanceled = true;\n\t\t\t}", "\t\t\tif (canceled)\n\t\t\t\treturn;", "\t\t\tbuffer = buffer.slice(ei + elength);\n\t\t\tis = false;\n\t\t\tbi = buffer.indexOf(beg);\n\t\t\tif (bi === -1)\n\t\t\t\treturn;\n\t\t\tis = true;\n\t\t\tei = buffer.indexOf(end, bi + blength);\n\t\t\tif (ei === -1)\n\t\t\t\treturn;\n\t\t}\n\t};", "\tstream && stream.on('end', () => fn(end));\n\treturn fn;\n};", "exports.streamer2 = function(beg, end, callback, skip, stream) {\n\treturn exports.streamer(beg, end, callback, skip, stream, true);\n};", "/**\n * HTML encode string\n * @param {String} str\n * @return {String}\n */\nexports.encode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.encode();\n};", "/**\n * HTML decode string\n * @param {String} str\n * @return {String}\n */\nexports.decode = function(str) {", "\tif (str == null)\n\t\treturn '';", "\tvar type = typeof(str);\n\tif (type !== 'string')\n\t\tstr = str.toString();", "\treturn str.decode();\n};", "/**\n * Checks if URL contains file extension.\n * @param {String} url\n * @return {Boolean}\n */\nexports.isStaticFile = function(url) {\n\tvar index = url.indexOf('.', url.length - 8);\n\treturn index !== -1;\n};", "/**\n * Converts Value to number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseInt = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseInt(def);\n};", "exports.parseBoolean = function(obj, def) {\n\tif (obj == null)\n\t\treturn def === undefined ? false : def;\n\tvar type = typeof(obj);\n\treturn type === 'boolean' ? obj : type === 'number' ? obj > 0 : (type !== 'string' ? obj.toString() : obj).parseBoolean(def);\n};", "/**\n * Converts Value to float number\n * @param {Object} obj Value to convert.\n * @param {Number} def Default value (default: 0).\n * @return {Number}\n */\nexports.parseFloat = function(obj, def) {\n\tif (obj == null || obj === '')\n\t\treturn def === undefined ? 0 : def;\n\tvar type = typeof(obj);\n\treturn type === 'number' ? obj : (type !== 'string' ? obj.toString() : obj).parseFloat(def);\n};", "/**\n * Check if the object is Date\n * @param {Object} obj\n * @return {Boolean}\n */\nexports.isDate = function(obj) {\n\treturn obj instanceof Date && !isNaN(obj.getTime()) ? true : false;\n};", "/**\n * Get ContentType from file extension.\n * @param {String} ext File extension.\n * @return {String}\n */\nexports.getContentType = function(ext) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);\n\treturn CONTENTTYPES[ext] || 'application/octet-stream';\n};", "/**\n * Get extension from filename\n * @param {String} filename\n * @return {String}\n */\nexports.getExtension = function(filename, raw) {\n\tvar end = filename.length;\n\tfor (var i = filename.length - 1; i > 0; i--) {\n\t\tvar c = filename[i];\n\t\tif (c === ' ' || c === '?')\n\t\t\tend = i;\n\t\telse if (c === '.') {\n\t\t\tc = filename.substring(i + 1, end);\n\t\t\treturn raw ? c : c.toLowerCase();\n\t\t}\n\t\telse if (c === '/' || c === '\\\\')\n\t\t\treturn '';\n\t}\n\treturn '';\n};", "/**\n * Get base name from path\n * @param {String} path\n * @return {String}\n */\nexports.getName = function(path) {\n\tvar l = path.length - 1;\n\tvar c = path[l];\n\tif (c === '/' || c === '\\\\')\n\t\tpath = path.substring(0, l);\n\tvar index = path.lastIndexOf('/');\n\tif (index !== -1)\n\t\treturn path.substring(index + 1);\n\tindex = path.lastIndexOf('\\\\');\n\treturn index === -1 ? path : path.substring(index + 1);\n};", "/**\n * Add a new content type to content types\n * @param {String} ext File extension.\n * @param {String} type Content type (example: application/json).\n */\nexports.setContentType = function(ext, type) {\n\tif (ext[0] === '.')\n\t\text = ext.substring(1);", "\tif (ext.length > 8) {\n\t\tvar tmp = regexpSTATIC.toString().replace(/,\\d+\\}/, ',' + ext.length + '}').substring(1);\n\t\tregexpSTATIC = new RegExp(tmp.substring(0, tmp.length - 1));\n\t}", "\tCONTENTTYPES[ext] = type;\n\treturn true;\n};", "exports.normalize = function(path) {\n\tif (path[0] !== '/')\n\t\tpath = '/' + path;\n\tif (path[path.length - 1] !== '/')\n\t\tpath += '/';\n\treturn path;\n};", "exports.link = function() {\n\tvar builder = '';\n\tfor (var i = 0; i < arguments.length; i++) {", "\t\tvar url = arguments[i];\n\t\tvar between = '';", "\t\tif (builder) {\n\t\t\tvar c = builder[builder.length - 1];\n\t\t\tif (c === '/') {\n\t\t\t\tif (url[0] === '/')\n\t\t\t\t\turl = url.substring(1);\n\t\t\t} else {\n\t\t\t\tif (url[0] !== '/')\n\t\t\t\t\tbetween = '/';\n\t\t\t}\n\t\t} else\n\t\t\tbetween = '';", "\t\tbuilder += between + url;\n\t}\n\treturn builder;\n};", "exports.path = function(path, delimiter) {\n\tif (!path)\n\t\tpath = '';\n\tdelimiter = delimiter || '/';\n\treturn path[path.length - 1] === delimiter ? path : path + delimiter;\n};", "exports.join = function() {\n\tvar path = [''];", "\tfor (var i = 0; i < arguments.length; i++) {\n\t\tvar current = arguments[i];\n\t\tif (current) {\n\t\t\tif (current[0] === '/')\n\t\t\t\tcurrent = current.substring(1);\n\t\t\tvar l = current.length - 1;\n\t\t\tif (current[l] === '/')\n\t\t\t\tcurrent = current.substring(0, l);\n\t\t\tpath.push(current);\n\t\t}\n\t}", "\tpath = path.join('/');\n\treturn !isWindows ? path : path.indexOf(':') > -1 ? path.substring(1) : path;\n};", "/**\n * Prepares Windows path to UNIX like format\n * @internal\n * @param {String} path\n * @return {String}\n */\nexports.$normalize = function(path) {\n\treturn isWindows ? path.replace(regexpPATH, '/') : path;\n};", "const RANDOM_STRING = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');\nconst RANDOM_NUMBER = '0123456789';", "exports.random_string = function(max) {\n\tvar builder = '';\n\tfor (var i = 0; i < max; i++) {\n\t\tvar index = Math.floor(Math.random() * RANDOM_STRING.length);\n\t\tbuilder += RANDOM_STRING[index];\n\t}\n\treturn builder;\n};", "exports.random_number = function(max) {\n\tvar builder = '';\n\tfor (var i = 0; i < max; i++) {\n\t\tvar index = Math.floor(Math.random() * RANDOM_NUMBER.length);\n\t\tif (!i && !index)\n\t\t\tindex++;\n\t\tbuilder += RANDOM_NUMBER[index];\n\t}\n\treturn builder;\n};", "exports.random = function(max, min) {\n\tmax = (max || 100000);\n\tmin = (min || 0);\n\treturn Math.floor(Math.random() * (max - min + 1)) + min;\n};", "function rnd() {\n\treturn Math.floor(Math.random() * 65536).toString(36);\n}", "global.GUID = exports.GUID = function(max) {\n\tmax = max || 40;\n\tvar str = '';\n\tfor (var i = 0; i < (max / 3) + 1; i++)\n\t\tstr += rnd();\n\treturn str.substring(0, max);\n};", "function validate_builder_default(name, value, entity) {", "\tvar type = typeof(value);", "\tif (entity.type === 12)\n\t\treturn value != null && type === 'object' && !(value instanceof Array);", "\tif (entity.type === 11)\n\t\treturn type === 'number';", "\t// Enum + KeyValue + Custom (8+9+10)\n\tif (entity.type > 7)\n\t\treturn value !== undefined;", "\tswitch (entity.subtype) {\n\t\tcase 'uid':\n\t\t\treturn value.isUID();\n\t\tcase 'zip':\n\t\t\treturn value.isZIP();\n\t\tcase 'email':\n\t\t\treturn value.isEmail();\n\t\tcase 'json':\n\t\t\treturn value.isJSON();\n\t\tcase 'url':\n\t\t\treturn value.isURL();\n\t\tcase 'phone':\n\t\t\treturn value.isPhone();\n\t\tcase 'base64':\n\t\t\treturn value.isBase64(true);\n\t}", "\tif (type === 'number')\n\t\treturn value > 0;", "\tif (type === 'string' || value instanceof Array)\n\t\treturn value.length > 0;", "\tif (type === 'boolean')\n\t\treturn value === true;", "\tif (value == null)\n\t\treturn false;", "\tif (value instanceof Date)\n\t\treturn value.toString()[0] !== 'I'; // Invalid Date", "\treturn true;\n}", "exports.validate_builder = function(model, error, schema, path, index, $, pluspath) {", "\tvar current = path ? path + '.' : '';\n\tvar properties = $ ? ($.keys || schema.properties) : schema.properties;\n\tvar result;", "\tif (!pluspath)\n\t\tpluspath = '';", "\tif (model == null)\n\t\tmodel = {};", "\tfor (var i = 0; i < properties.length; i++) {", "\t\tvar name = properties[i];\n\t\tvar TYPE = schema.schema[name];\n\t\tif (!TYPE)\n\t\t\tcontinue;", "\t\tif (TYPE.can && !TYPE.can(model, model.$$workflow || EMPTYOBJECT))\n\t\t\tcontinue;", "\t\tvar value = model[name];\n\t\tvar type = typeof(value);\n\t\tvar prefix = schema.resourcePrefix ? (schema.resourcePrefix + name) : name;", "\t\tif (value === undefined) {\n\t\t\terror.push(pluspath + name, '@', current + name, undefined, prefix);\n\t\t\tcontinue;\n\t\t} else if (type === 'function')\n\t\t\tvalue = model[name]();", "\t\tif (TYPE.isArray) {\n\t\t\tif (TYPE.type === 7 && value instanceof Array && value.length) {\n\t\t\t\tvar nestedschema = GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema) {\n\t\t\t\t\tfor (var j = 0, jl = value.length; j < jl; j++)\n\t\t\t\t\t\texports.validate_builder(value[j], error, nestedschema, current + name + '[' + j + ']', j, undefined, pluspath);\n\t\t\t\t} else\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {", "\t\t\t\tif (!TYPE.required)\n\t\t\t\t\tcontinue;", "\t\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;\n\t\t\t\tif (result == null) {\n\t\t\t\t\tresult = value instanceof Array ? value.length > 0 : false;\n\t\t\t\t\tif (result == null || result === true)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}", "\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, TYPE.invalid, current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean')\n\t\t\t\t\t!result && error.push(pluspath + name, TYPE.invalid, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (TYPE.type === 7) {", "\t\t\tif (!value && !TYPE.required)\n\t\t\t\tcontinue;", "\t\t\t// Another schema\n\t\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;", "\t\t\tif (result == null) {\n\t\t\t\tvar nestedschema = GETSCHEMA(TYPE.raw);\n\t\t\t\tif (nestedschema)\n\t\t\t\t\texports.validate_builder(value, error, nestedschema, current + name, undefined, undefined, pluspath);\n\t\t\t\telse\n\t\t\t\t\tthrow new Error('Nested schema \"{0}\" not found in \"{1}\".'.format(TYPE.raw, schema.parent.name));\n\t\t\t} else {\n\t\t\t\ttype = typeof(result);\n\t\t\t\tif (type === 'string') {\n\t\t\t\t\tif (result[0] === '@')\n\t\t\t\t\t\terror.push(pluspath + name, TYPE.invalid, current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\t\t\telse\n\t\t\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t\t\t} else if (type === 'boolean')\n\t\t\t\t\t!result && error.push(pluspath + name, TYPE.invalid, current + name, index, prefix);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}", "\t\tif (!TYPE.required)\n\t\t\tcontinue;", "\t\tresult = TYPE.validate ? TYPE.validate(value, model) : null;\n\t\tif (result == null) {\n\t\t\tresult = validate_builder_default(name, value, TYPE);\n\t\t\tif (result == null || result === true)\n\t\t\t\tcontinue;\n\t\t}", "\t\ttype = typeof(result);", "\t\tif (type === 'string') {\n\t\t\tif (result[0] === '@')\n\t\t\t\terror.push(pluspath + name, TYPE.invalid, current + name, index, schema.resourcePrefix + result.substring(1));\n\t\t\telse\n\t\t\t\terror.push(pluspath + name, result, current + name, index, prefix);\n\t\t} else if (type === 'boolean')\n\t\t\t!result && error.push(pluspath + name, TYPE.invalid, current + name, index, prefix);\n\t}", "\treturn error;\n};", "/**\n * Combine paths\n * @return {String}\n */\nexports.combine = function() {", "\tvar p = F.directory;", "\tfor (var i = 0, length = arguments.length; i < length; i++) {\n\t\tvar v = arguments[i];\n\t\tif (!v)\n\t\t\tcontinue;\n\t\tif (v[0] === '/')\n\t\t\tv = v.substring(1);", "\t\tif (v[0] === '~')\n\t\t\tp = v.substring(1);\n\t\telse\n\t\t\tp += (p[p.length - 1] !== '/' ? '/' : '') + v;\n\t}\n\treturn exports.$normalize(p);\n};", "/**\n * Simple XML parser\n * @param {String} xml\n * @return {Object}\n */\nexports.parseXML = function(xml, replace) {\n\treturn xml.parseXML(replace);\n};", "function jsonparser(key, value) {\n\treturn typeof(value) === 'string' && value.isJSONDate() ? new Date(value) : value;\n}", "/**\n * Get WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @param {Hexa} type\n * @return {Buffer}\n */\nexports.getWebSocketFrame = function(code, message, type, compress, mask) {", "\tif (mask)\n\t\tmask = ((Math.random() * 214748364) >> 0) + 1;", "\tvar messageBuffer = getWebSocketFrameMessageBytes(code, message);\n\tvar lengthBuffer = getWebSocketFrameLengthBytes(messageBuffer.length);\n\tvar lengthMask = mask ? 4 : 0;\n\tvar frameBuffer = Buffer.alloc(1 + lengthBuffer.length + messageBuffer.length + lengthMask);", "\tframeBuffer[0] = 0x80 | type;", "\tif (compress)\n\t\tframeBuffer[0] |= 0x40;", "\tlengthBuffer.copy(frameBuffer, 1, 0, lengthBuffer.length);", "\tif (mask) {\n\t\tvar offset = lengthBuffer.length + 1;\n\t\tframeBuffer[1] |= 0x80;\n\t\tframeBuffer.writeInt32BE(mask, offset);\n\t\tfor (var i = 0; i < messageBuffer.length; i++)\n\t\t\tmessageBuffer[i] = messageBuffer[i] ^ frameBuffer[offset + (i % 4)];\n\t}", "\tmessageBuffer.copy(frameBuffer, lengthBuffer.length + 1 + lengthMask, 0, messageBuffer.length);\n\treturn frameBuffer;\n};", "/**\n * Get bytes of WebSocket frame message\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} code\n * @param {Buffer or String} message\n * @return {Buffer}\n */\nfunction getWebSocketFrameMessageBytes(code, message) {", "\tvar index = code ? 2 : 0;\n\tvar binary = message instanceof Int8Array || message instanceof Buffer;\n\tvar length = message.length;", "\tvar messageBuffer = Buffer.alloc(length + index);", "\tfor (var i = 0; i < length; i++) {\n\t\tif (binary)\n\t\t\tmessageBuffer[i + index] = message[i];\n\t\telse\n\t\t\tmessageBuffer[i + index] = message.charCodeAt(i);\n\t}", "\tif (code) {\n\t\tmessageBuffer[0] = code >> 8;\n\t\tmessageBuffer[1] = code;\n\t}", "\treturn messageBuffer;\n}", "/**\n * Get length of WebSocket frame\n * @author Jozef Gula <gula.jozef@gmail.com>\n * @param {Number} length\n * @return {Number}\n */\nfunction getWebSocketFrameLengthBytes(length) {\n\tvar lengthBuffer = null;", "\tif (length <= 125) {\n\t\tlengthBuffer = Buffer.alloc(1);\n\t\tlengthBuffer[0] = length;\n\t\treturn lengthBuffer;\n\t}", "\tif (length <= 65535) {\n\t\tlengthBuffer = Buffer.alloc(3);\n\t\tlengthBuffer[0] = 126;\n\t\tlengthBuffer[1] = (length >> 8) & 255;\n\t\tlengthBuffer[2] = (length) & 255;\n\t\treturn lengthBuffer;\n\t}", "\tlengthBuffer = Buffer.alloc(9);", "\tlengthBuffer[0] = 127;\n\tlengthBuffer[1] = 0x00;\n\tlengthBuffer[2] = 0x00;\n\tlengthBuffer[3] = 0x00;\n\tlengthBuffer[4] = 0x00;\n\tlengthBuffer[5] = (length >> 24) & 255;\n\tlengthBuffer[6] = (length >> 16) & 255;\n\tlengthBuffer[7] = (length >> 8) & 255;\n\tlengthBuffer[8] = (length) & 255;", "\treturn lengthBuffer;\n}", "/**\n * GPS distance in KM\n * @param {Number} lat1\n * @param {Number} lon1\n * @param {Number} lat2\n * @param {Number} lon2\n * @return {Number}\n */\nexports.distance = function(lat1, lon1, lat2, lon2) {\n\tvar R = 6371;\n\tvar dLat = (lat2 - lat1).toRad();\n\tvar dLon = (lon2 - lon1).toRad();\n\tvar a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * Math.sin(dLon / 2) * Math.sin(dLon / 2);\n\tvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\treturn (R * c).floor(3);\n};", "function ls(path, callback, advanced, filter) {\n\tvar filelist = new FileList();\n\tvar tmp;", "\tfilelist.advanced = advanced;\n\tfilelist.onComplete = callback;", "\tif (typeof(filter) === 'string') {\n\t\ttmp = filter.toLowerCase();\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : filename.toLowerCase().indexOf(tmp) !== -1;\n\t\t};\n\t} else if (filter && filter.test) {\n\t\t// regexp\n\t\ttmp = filter;\n\t\tfilelist.onFilter = function(filename, is) {\n\t\t\treturn is ? true : tmp.test(filename);\n\t\t};\n\t} else\n\t\tfilelist.onFilter = filter || null;", "\tfilelist.walk(path);\n}", "/**\n * Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename, isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls = function(path, callback, filter) {\n\tls(path, callback, false, filter);\n};", "/**\n * Advanced Directory listing\n * @param {String} path Path.\n * @param {Function(files, directories)} callback Callback\n * @param {Function(filename ,isDirectory) or String or RegExp} filter Custom filter (optional).\n */\nexports.ls2 = function(path, callback, filter) {\n\tls(path, callback, true, filter);\n};", "DP.setTimeZone = function(timezone) {", "\tvar dt = new Date(this.toLocaleString('en-US', { timeZone: timezone }));", "\tvar offset = dt + '';\n\tvar index = offset.indexOf('GMT');\n\tvar op = offset.substring(index + 3, index + 4);\n\tvar count = offset.substring(index + 4, index + 9);\n\tvar h = +count.substring(0, 2);\n\tvar m = +count.substring(2);", "\tif (op === '+') {\n\t\th && dt.setHours(dt.getHours() + h);\n\t\tm && dt.setMinutes(dt.getMinutes() + m);\n\t} else {\n\t\th && dt.setHours(dt.getHours() - h);\n\t\tm && dt.setMinutes(dt.getMinutes() - m);\n\t}", "\treturn dt;\n};", "/**\n * Date difference\n * @param {Date/Number/String} date Optional.\n * @param {String} type Date type: minutes, seconds, hours, days, months, years\n * @return {Number}\n */\nDP.diff = function(date, type) {", "\tif (arguments.length === 1) {\n\t\ttype = date;\n\t\tdate = Date.now();\n\t} else {\n\t\tvar to = typeof(date);\n\t\tif (to === 'string')\n\t\t\tdate = Date.parse(date);\n\t\telse if (exports.isDate(date))\n\t\t\tdate = date.getTime();\n\t}", "\tvar r = this.getTime() - date;", "\tswitch (type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\treturn Math.ceil(r / 1000);\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'minutes':\n\t\t\treturn Math.ceil((r / 1000) / 60);\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\treturn Math.ceil(((r / 1000) / 60) / 60);\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / 24);\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28));", "\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\t// avg: 28 days per month\n\t\t\treturn Math.ceil((((r / 1000) / 60) / 60) / (24 * 28 * 12));\n\t}", "\treturn NaN;\n};", "DP.add = function(type, value) {", "\tvar self = this;", "\tif (type.constructor === Number)\n\t\treturn new Date(self.getTime() + (type - type % 1));", "\tif (value === undefined) {\n\t\tvar arr = type.split(' ');\n\t\ttype = arr[1];\n\t\tvalue = exports.parseInt(arr[0]);\n\t}", "\tvar dt = new Date(self.getTime());", "\tswitch(type) {\n\t\tcase 's':\n\t\tcase 'ss':\n\t\tcase 'sec':\n\t\tcase 'second':\n\t\tcase 'seconds':\n\t\t\tdt.setUTCSeconds(dt.getUTCSeconds() + value);\n\t\t\treturn dt;\n\t\tcase 'm':\n\t\tcase 'mm':\n\t\tcase 'minute':\n\t\tcase 'min':\n\t\tcase 'minutes':\n\t\t\tdt.setUTCMinutes(dt.getUTCMinutes() + value);\n\t\t\treturn dt;\n\t\tcase 'h':\n\t\tcase 'hh':\n\t\tcase 'hour':\n\t\tcase 'hours':\n\t\t\tdt.setUTCHours(dt.getUTCHours() + value);\n\t\t\treturn dt;\n\t\tcase 'd':\n\t\tcase 'dd':\n\t\tcase 'day':\n\t\tcase 'days':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + value);\n\t\t\treturn dt;\n\t\tcase 'w':\n\t\tcase 'ww':\n\t\tcase 'week':\n\t\tcase 'weeks':\n\t\t\tdt.setUTCDate(dt.getUTCDate() + (value * 7));\n\t\t\treturn dt;\n\t\tcase 'M':\n\t\tcase 'MM':\n\t\tcase 'month':\n\t\tcase 'months':\n\t\t\tdt.setUTCMonth(dt.getUTCMonth() + value);\n\t\t\treturn dt;\n\t\tcase 'y':\n\t\tcase 'yyyy':\n\t\tcase 'year':\n\t\tcase 'years':\n\t\t\tdt.setUTCFullYear(dt.getUTCFullYear() + value);\n\t\t\treturn dt;\n\t}\n\treturn dt;\n};", "DP.extend = function(date) {\n\tvar dt = new Date(this);\n\tvar match = date.match(regexpDATE);", "\tif (!match)\n\t\treturn dt;", "\tfor (var i = 0, length = match.length; i < length; i++) {\n\t\tvar m = match[i];\n\t\tvar arr, tmp;", "\t\tif (m.indexOf(':') !== -1) {", "\t\t\tarr = m.split(':');\n\t\t\ttmp = +arr[0];\n\t\t\ttmp >= 0 && dt.setUTCHours(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMinutes(tmp);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCSeconds(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('-') !== -1) {\n\t\t\tarr = m.split('-');", "\t\t\ttmp = +arr[0];\n\t\t\ttmp && dt.setUTCFullYear(tmp);", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\ttmp >= 0 && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\ttmp >= 0 && dt.setUTCDate(tmp);\n\t\t\t}", "\t\t\tcontinue;\n\t\t}", "\t\tif (m.indexOf('.') !== -1) {\n\t\t\tarr = m.split('.');", "\t\t\tif (arr[2]) {\n\t\t\t\ttmp = +arr[2];\n\t\t\t\t!isNaN(tmp) && dt.setUTCFullYear(tmp);\n\t\t\t}", "\t\t\tif (arr[1]) {\n\t\t\t\ttmp = +arr[1];\n\t\t\t\t!isNaN(tmp) && dt.setUTCMonth(tmp - 1);\n\t\t\t}", "\t\t\ttmp = +arr[0];\n\t\t\t!isNaN(tmp) && dt.setUTCDate(tmp);", "\t\t\tcontinue;\n\t\t}\n\t}", "\treturn dt;\n};", "/**\n * Format datetime\n * @param {String} format\n * @return {String}\n */\nDP.format = function(format, resource) {", "\tif (!format)\n\t\treturn this.getUTCFullYear() + '-' + (this.getUTCMonth() + 1).toString().padLeft(2, '0') + '-' + this.getUTCDate().toString().padLeft(2, '0') + 'T' + this.getUTCHours().toString().padLeft(2, '0') + ':' + this.getUTCMinutes().toString().padLeft(2, '0') + ':' + this.getUTCSeconds().toString().padLeft(2, '0') + '.' + this.getUTCMilliseconds().toString().padLeft(3, '0') + 'Z';", "\tif (datetimeformat[format])\n\t\treturn datetimeformat[format](this, resource);", "\tvar key = format;\n\tvar half = false;", "\tif (format && format[0] === '!') {\n\t\thalf = true;\n\t\tformat = format.substring(1);\n\t}", "\tvar beg = '\\'+';\n\tvar end = '+\\'';\n\tvar before = [];", "\tvar ismm = false;\n\tvar isdd = false;\n\tvar isww = false;", "\tformat = format.replace(regexpDATEFORMAT, function(key) {\n\t\tswitch (key) {\n\t\t\tcase 'yyyy':\n\t\t\tcase 'YYYY':\n\t\t\t\treturn beg + 'd.getFullYear()' + end;\n\t\t\tcase 'yy':\n\t\t\tcase 'YY':\n\t\t\t\treturn beg + 'd.getFullYear().toString().substring(2)' + end;\n\t\t\tcase 'MMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, mm) || mm).substring(0, 3)' + end;\n\t\t\tcase 'MMMM':\n\t\t\t\tismm = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, mm) || mm)' + end;\n\t\t\tcase 'MM':\n\t\t\t\treturn beg + '(d.getMonth() + 1).toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'M':\n\t\t\t\treturn beg + '(d.getMonth() + 1)' + end;\n\t\t\tcase 'ddd':\n\t\t\tcase 'DDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, dd) || dd).substring(0, 2).toUpperCase()' + end;\n\t\t\tcase 'dddd':\n\t\t\tcase 'DDDD':\n\t\t\t\tisdd = true;\n\t\t\t\treturn beg + '(RESOURCE(resource, dd) || dd)' + end;\n\t\t\tcase 'dd':\n\t\t\tcase 'DD':\n\t\t\t\treturn beg + 'd.getDate().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'd':\n\t\t\tcase 'D':\n\t\t\t\treturn beg + 'd.getDate()' + end;\n\t\t\tcase 'HH':\n\t\t\tcase 'hh':\n\t\t\t\treturn beg + (half ? 'framework_utils.$pmam(d.getHours()).toString().padLeft(2, \\'0\\')' : 'd.getHours().toString().padLeft(2, \\'0\\')') + end;\n\t\t\tcase 'H':\n\t\t\tcase 'h':\n\t\t\t\treturn beg + (half ? 'framework_utils(d.getHours())' : 'd.getHours()') + end;\n\t\t\tcase 'mm':\n\t\t\t\treturn beg + 'd.getMinutes().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 'm':\n\t\t\t\treturn beg + 'd.getMinutes()' + end;\n\t\t\tcase 'ss':\n\t\t\t\treturn beg + 'd.getSeconds().toString().padLeft(2, \\'0\\')' + end;\n\t\t\tcase 's':\n\t\t\t\treturn beg + 'd.getSeconds()' + end;\n\t\t\tcase 'w':\n\t\t\tcase 'ww':\n\t\t\t\tisww = true;\n\t\t\t\treturn beg + (key === 'ww' ? 'ww.toString().padLeft(2, \\'0\\')' : 'ww') + end;\n\t\t\tcase 'a':\n\t\t\t\tvar b = \"'PM':'AM'\";\n\t\t\t\treturn beg + '(d.getHours() >= 12 ? ' + b + ')' + end;\n\t\t}\n\t});", "\tismm && before.push('var mm = framework_utils.MONTHS[d.getMonth()];');\n\tisdd && before.push('var dd = framework_utils.DAYS[d.getDay()];');\n\tisww && before.push('var ww = new Date(+d);ww.setHours(0, 0, 0);ww.setDate(ww.getDate() + 4 - (ww.getDay() || 7));ww = Math.ceil((((ww - new Date(ww.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);');", "\tdatetimeformat[key] = new Function('d', 'resource', before.join('\\n') + 'return \\'' + format + '\\';');\n\treturn datetimeformat[key](this, resource);\n};", "exports.$pmam = function(value) {\n\treturn value >= 12 ? value - 12 : value;\n};", "DP.toUTC = function(ticks) {\n\tvar dt = this.getTime() + this.getTimezoneOffset() * 60000;\n\treturn ticks ? dt : new Date(dt);\n};", "// +v2.2.0 parses JSON dates as dates and this is the fallback for backward compatibility\nDP.parseDate = function() {\n\treturn this;\n};", "SP.isJSONDate = function() {\n\tvar l = this.length - 1;\n\treturn l > 22 && l < 30 && this[l] === 'Z' && this[10] === 'T' && this[4] === '-' && this[13] === ':' && this[16] === ':';\n};", "SP.ROOT = function(noremap) {", "\tvar str = this;", "\tstr = str.replace(REG_NOREMAP, function() {\n\t\tnoremap = true;\n\t\treturn '';\n\t}).replace(REG_ROOT, $urlmaker);", "\tif (!noremap && CONF.default_root)\n\t\tstr = str.replace(REG_REMAP, $urlremap).replace(REG_AJAX, $urlajax);", "\treturn str;\n};", "function $urlremap(text) {\n\tvar pos = text[0] === 'h' ? 6 : 5;\n\treturn REG_URLEXT.test(text) ? text : ((text[0] === 'h' ? 'href' : 'src') + '=\"' + CONF.default_root + (text[pos] === '/' ? text.substring(pos + 1) : text));\n}", "function $urlajax(text) {\n\treturn text.substring(0, text.length - 1) + CONF.default_root;\n}", "function $urlmaker(text) {\n\tvar c = text[4];\n\treturn CONF.default_root ? CONF.default_root : (c || '');\n}", "if (!SP.trim) {\n\tSP.trim = function() {\n\t\treturn this.replace(regexpTRIM, '');\n\t};\n}", "/**\n * Checks if the string starts with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.startsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.startsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(0, length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr(ignoreCase, length);\n\telse\n\t\ttmp = self.substring(0, length);", "\treturn tmp.length === length && tmp === text;\n};", "/**\n * Checks if the string ends with the text\n * @see {@link http://docs.totaljs.com/SP/#SP.endsWith|Documentation}\n * @param {String} text Text to find.\n * @param {Boolean/Number} ignoreCase Ingore case sensitive or position in the string.\n * @return {Boolean}\n */\nSP.endsWith = function(text, ignoreCase) {\n\tvar self = this;\n\tvar length = text.length;\n\tvar tmp;", "\tif (ignoreCase === true) {\n\t\ttmp = self.substring(self.length - length);\n\t\treturn tmp.length === length && tmp.toLowerCase() === text.toLowerCase();\n\t}", "\tif (ignoreCase)\n\t\ttmp = self.substr((self.length - ignoreCase) - length, length);\n\telse\n\t\ttmp = self.substring(self.length - length);", "\treturn tmp.length === length && tmp === text;\n};", "SP.replacer = function(find, text) {\n\tvar self = this;\n\tvar beg = self.indexOf(find);\n\treturn beg === -1 ? self : (self.substring(0, beg) + text + self.substring(beg + find.length));\n};", "/**\n * Hash string\n * @param {String} type Hash type.\n * @param {String} salt Optional, salt.\n * @return {String}\n */\nSP.hash = function(type, salt) {\n\tvar str = salt ? this + salt : this;\n\tswitch (type) {\n\t\tcase 'md5':\n\t\t\treturn str.md5();\n\t\tcase 'sha1':\n\t\t\treturn str.sha1();\n\t\tcase 'sha256':\n\t\t\treturn str.sha256();\n\t\tcase 'sha512':\n\t\t\treturn str.sha512();\n\t\tcase 'crc32':\n\t\t\treturn str.crc32();\n\t\tcase 'crc32unsigned':\n\t\t\treturn str.crc32(true);\n\t\tdefault:\n\t\t\tvar val = string_hash(str);\n\t\t\treturn type === true ? val >>> 0 : val;\n\t}\n};", "global.HASH = function(value, type) {\n\treturn value.hash(type ? type : true);\n};", "SP.makeid = function() {\n\treturn this.hash(true).toString(36);\n};", "SP.crc32 = function(unsigned) {\n\tvar crc = -1;\n\tfor (var i = 0, length = this.length; i < length; i++)\n\t\tcrc = (crc >>> 8) ^ CRC32TABLE[(crc ^ this.charCodeAt(i)) & 0xFF];\n\tvar val = crc ^ (-1);\n\treturn unsigned ? val >>> 0 : val;\n};", "function string_hash(s, convert) {\n\tvar hash = 0;\n\tif (s.length === 0)\n\t\treturn convert ? '' : hash;\n\tfor (var i = 0, l = s.length; i < l; i++) {\n\t\tvar char = s.charCodeAt(i);\n\t\thash = ((hash << 5) - hash) + char;\n\t\thash |= 0;\n\t}\n\treturn hash;\n}", "SP.count = function(text) {\n\tvar index = 0;\n\tvar count = 0;\n\tdo {\n\t\tindex = this.indexOf(text, index + text.length);\n\t\tif (index > 0)\n\t\t\tcount++;\n\t} while (index > 0);\n\treturn count;\n};", "SP.parseComponent = function(tags) {", "\tvar html = this;\n\tvar beg = -1;\n\tvar end = -1;\n\tvar output = {};", "\tfor (var key in tags) {", "\t\tvar tagbeg = tags[key];\n\t\tvar tagindex = tagbeg.indexOf(' ');", "\t\tif (tagindex === -1)\n\t\t\ttagindex = tagbeg.length - 1;", "\t\tvar tagend = '</' + tagbeg.substring(1, tagindex) + '>';\n\t\tvar tagbeg2 = '<' + tagend.substring(2);", "\t\tbeg = html.indexOf(tagbeg);", "\t\tif (beg !== -1) {", "\t\t\tvar count = 0;\n\t\t\tend = -1;", "\t\t\tfor (var j = (beg + tagbeg.length); j < html.length; j++) {\n\t\t\t\tvar a = html.substring(j, j + tagbeg2.length);\n\t\t\t\tif (a === tagbeg2) {\n\t\t\t\t\tcount++;\n\t\t\t\t} else {\n\t\t\t\t\tif (html.substring(j, j + tagend.length) === tagend) {\n\t\t\t\t\t\tif (count) {\n\t\t\t\t\t\t\tcount--;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tend = j;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (end !== -1) {\n\t\t\t\tvar tmp = html.substring(html.indexOf('>', beg) + 1, end);\n\t\t\t\thtml = html.replace(html.substring(beg, end + tagend.length), '').trim();\n\t\t\t\toutput[key] = tmp.trim();\n\t\t\t}", "\t\t}\n\t}", "\treturn output;\n};", "SP.parseXML = function(replace) {", "\tvar xml = this;\n\tvar beg = -1;\n\tvar end = 0;\n\tvar tmp = 0;\n\tvar current = [];\n\tvar obj = {};\n\tvar from = -1;", "\twhile (true) {\n\t\tbeg = xml.indexOf('<![CDATA[', beg);\n\t\tif (beg === -1)\n\t\t\tbreak;\n\t\tend = xml.indexOf(']]>', beg + 9);\n\t\txml = xml.substring(0, beg) + xml.substring(beg + 9, end).trim().encode() + xml.substring(end + 3);\n\t\tbeg += 9;\n\t}", "\tbeg = -1;\n\tend = 0;", "\twhile (true) {", "\t\tbeg = xml.indexOf('<', beg + 1);\n\t\tif (beg === -1)\n\t\t\tbreak;", "\t\tend = xml.indexOf('>', beg + 1);\n\t\tif (end === -1)\n\t\t\tbreak;", "\t\tvar el = xml.substring(beg, end + 1);\n\t\tvar c = el[1];", "\t\tif (el.substring(0, 4) === '<!--') {\n\t\t\tbeg = end + 3;\n\t\t\tcontinue;\n\t\t}", "\t\tif (c === '?' || c === '/') {", "\t\t\tvar o = current.pop();", "\t\t\tif (from === -1 || o !== el.substring(2, el.length - 1))\n\t\t\t\tcontinue;", "\t\t\tvar path = (current.length ? current.join('.') + '.' : '') + o;\n\t\t\tvar value = xml.substring(from, beg).decode();", "\t\t\tif (replace)\n\t\t\t\tpath = path.replace(REG_XMLKEY, '_');", "\t\t\tif (obj[path] === undefined)\n\t\t\t\tobj[path] = value;\n\t\t\telse if (obj[path] instanceof Array)\n\t\t\t\tobj[path].push(value);\n\t\t\telse\n\t\t\t\tobj[path] = [obj[path], value];", "\t\t\tfrom = -1;\n\t\t\tcontinue;\n\t\t}", "\t\ttmp = el.indexOf(' ');\n\t\tvar hasAttributes = true;", "\t\tif (tmp === -1) {\n\t\t\ttmp = el.length - 1;\n\t\t\thasAttributes = false;\n\t\t}", "\t\tfrom = beg + el.length;", "\t\tvar isSingle = el[el.length - 2] === '/';\n\t\tvar name = el.substring(1, tmp);", "\t\tif (!isSingle)\n\t\t\tcurrent.push(name);", "\t\tif (!hasAttributes)\n\t\t\tcontinue;", "\t\tvar match = el.match(regexpXML);\n\t\tif (!match)\n\t\t\tcontinue;", "\t\tvar attr = {};\n\t\tvar length = match.length;", "\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar index = match[i].indexOf('\"');\n\t\t\tattr[match[i].substring(0, index - 1)] = match[i].substring(index + 1, match[i].length - 1).decode();\n\t\t}", "\t\tvar k = current.join('.') + (isSingle ? '.' + name : '') + '[]';\n\t\tif (replace)\n\t\t\tk = k.replace(REG_XMLKEY, '_');\n\t\tobj[k] = attr;\n\t}", "\treturn obj;\n};", "SP.parseJSON = function(date) {\n\ttry {\n\t\treturn JSON.parse(this, date ? jsonparser : undefined);\n\t} catch (e) {}\n};", "function parseQueryArgumentsDecode(val) {\n\ttry {\n\t\treturn decodeURIComponent(val);\n\t} catch (e) {\n\t\treturn '';\n\t}\n}", "const QUERY_ALLOWED = { '45': 1, '95': 1, 46: 1, '91': 1, '93': 1 };", "SP.parseEncoded = function() {", "\tvar str = this + '&';\n\tvar obj = {};\n\tvar key = '';\n\tvar val = '';\n\tvar is = false;\n\tvar decodev = false;\n\tvar decodek = false;\n\tvar count = 0;\n\tvar pos = 0;", "\tfor (var i = 0; i < str.length; i++) {\n\t\tvar n = str.charCodeAt(i);", "\t\tif (n === 38) {", "\t\t\tif (key) {\n\t\t\t\tif (pos < i)\n\t\t\t\t\tval += str.substring(pos, i);", "\t\t\t\tif (decodev)\n\t\t\t\t\tval = parseQueryArgumentsDecode(val);", "\t\t\t\tif (decodek)\n\t\t\t\t\tkey = parseQueryArgumentsDecode(key);", "\t\t\t\tobj[key] = val;\n\t\t\t}", "\t\t\tif (key)\n\t\t\t\tkey = '';", "\t\t\tif (val)\n\t\t\t\tval = '';", "\t\t\tpos = i + 1;\n\t\t\tis = false;\n\t\t\tdecodek = false;\n\t\t\tdecodev = false;", "\t\t\tif ((count++) >= CONF.default_request_maxkeys)\n\t\t\t\tbreak;", "\t\t} else {", "\t\t\tif (n === 61) {\n\t\t\t\tif ((i - pos) > CONF.default_request_maxkey)\n\t\t\t\t\tkey = '';\n\t\t\t\telse {\n\t\t\t\t\tif (pos < i)\n\t\t\t\t\t\tkey += str.substring(pos, i);\n\t\t\t\t\tpos = i + 1;\n\t\t\t\t\tis = true;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (!is) {\n\t\t\t\tvar can = false;\n\t\t\t\tif (n > 47 && n < 58)\n\t\t\t\t\tcan = true;\n\t\t\t\telse if ((n > 64 && n < 91) || (n > 96 && n < 123))\n\t\t\t\t\tcan = true;\n\t\t\t\telse if (QUERY_ALLOWED[n])\n\t\t\t\t\tcan = true;\n\t\t\t\tif (!can)\n\t\t\t\t\tbreak;\n\t\t\t}", "\t\t\tif (n === 43) {\n\t\t\t\tif (is)\n\t\t\t\t\tval += str.substring(pos, i) + ' ';\n\t\t\t\telse\n\t\t\t\t\tkey += str.substring(pos, i) + ' ';\n\t\t\t\tpos = i + 1;\n\t\t\t}", "\t\t\tif (n === 37) {\n\t\t\t\tif (str.charCodeAt(i + 1) === 48 && str.charCodeAt(i + 2) === 48)\n\t\t\t\t\tpos = i + 3;\n\t\t\t\telse if (is) {\n\t\t\t\t\tif (!decodev)\n\t\t\t\t\t\tdecodev = true;\n\t\t\t\t} else {\n\t\t\t\t\tif (!decodev)\n\t\t\t\t\t\tdecodek = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "\treturn obj;\n};", "SP.parseUA = function(structured) {", "\tvar ua = this;", "\tif (!ua)\n\t\treturn '';", "\tvar arr = ua.match(regexpUA);\n\tvar uid = '';", "\tif (arr) {", "\t\tvar data = {};", "\t\tfor (var i = 0; i < arr.length; i++) {", "\t\t\tif (arr[i] === 'like' && arr[i + 1] === 'Gecko') {\n\t\t\t\ti += 1;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tvar key = arr[i].toLowerCase();\n\t\t\tif (key === 'like')\n\t\t\t\tbreak;", "\t\t\tswitch (key) {\n\t\t\t\tcase 'linux':\n\t\t\t\tcase 'windows':\n\t\t\t\tcase 'mac':\n\t\t\t\tcase 'symbian':\n\t\t\t\tcase 'symbos':\n\t\t\t\tcase 'tizen':\n\t\t\t\tcase 'android':\n\t\t\t\t\tdata[arr[i]] = 2;\n\t\t\t\t\tif (key === 'tizen' || key === 'android')\n\t\t\t\t\t\tdata.Mobile = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'webos':\n\t\t\t\t\tdata.WebOS = 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'media':\n\t\t\t\tcase 'center':\n\t\t\t\tcase 'tv':\n\t\t\t\tcase 'smarttv':\n\t\t\t\tcase 'smart':\n\t\t\t\t\tdata[arr[i]] = 5;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'iemobile':\n\t\t\t\tcase 'mobile':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'ipad':\n\t\t\t\tcase 'ipod':\n\t\t\t\tcase 'iphone':\n\t\t\t\t\tdata.iOS = 2;\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tif (key === 'ipad')\n\t\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'phone':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tizenbrowser':\n\t\t\t\tcase 'blackberry':\n\t\t\t\tcase 'mini':\n\t\t\t\t\tdata.Mobile = 3;\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'samsungbrowser':\n\t\t\t\tcase 'chrome':\n\t\t\t\tcase 'firefox':\n\t\t\t\tcase 'msie':\n\t\t\t\tcase 'opera':\n\t\t\t\tcase 'brave':\n\t\t\t\tcase 'vivaldi':\n\t\t\t\tcase 'outlook':\n\t\t\t\tcase 'safari':\n\t\t\t\tcase 'mail':\n\t\t\t\tcase 'edge':\n\t\t\t\tcase 'maxthon':\n\t\t\t\tcase 'electron':\n\t\t\t\t\tdata[arr[i]] = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'trident':\n\t\t\t\t\tdata.MSIE = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'opr':\n\t\t\t\t\tdata.Opera = 1;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'tablet':\n\t\t\t\t\tdata.Tablet = 4;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (data.MSIE) {\n\t\t\tdata.IE = 1;\n\t\t\tdelete data.MSIE;\n\t\t}", "\t\tif (data.WebOS || data.Android)\n\t\t\tdelete data.Linux;", "\t\tif (data.IEMobile) {\n\t\t\tif (data.Android)\n\t\t\t\tdelete data.Android;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t} else if (data.MSIE) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Edge) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Opera || data.Electron) {\n\t\t\tif (data.Chrome)\n\t\t\t\tdelete data.Chrome;\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t} else if (data.Chrome) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t\tif (data.SamsungBrowser)\n\t\t\t\tdelete data.SamsungBrowser;\n\t\t} else if (data.SamsungBrowser) {\n\t\t\tif (data.Safari)\n\t\t\t\tdelete data.Safari;\n\t\t}", "\t\tif (structured) {\n\t\t\tvar output = { os: '', browser: '', device: 'desktop' };", "\t\t\tif (data.Tablet)\n\t\t\t\toutput.device = 'tablet';\n\t\t\telse if (data.Mobile)\n\t\t\t\toutput.device = 'mobile';", "\t\t\tfor (var key in data) {\n\t\t\t\tvar val = data[key];\n\t\t\t\tswitch (val) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\toutput.browser += (output.browser ? ' ' : '') + key;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\toutput.os += (output.os ? ' ' : '') + key;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\toutput.device = 'tv';\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn output;\n\t\t}", "\t\tuid = Object.keys(data).join(' ');\n\t}", "\treturn uid;\n};", "SP.parseCSV = function(delimiter) {", "\tif (!delimiter)\n\t\tdelimiter = ',';", "\tvar delimiterstring = '\"';\n\tvar t = this;\n\tvar scope;\n\tvar tmp = {};\n\tvar index = 1;\n\tvar data = [];\n\tvar current = 'a';", "\tfor (var i = 0; i < t.length; i++) {\n\t\tvar c = t[i];", "\t\tif (!scope) {", "\t\t\tif (c === '\\n' || c === '\\r') {\n\t\t\t\ttmp && data.push(tmp);\n\t\t\t\tindex = 1;\n\t\t\t\tcurrent = 'a';\n\t\t\t\ttmp = null;\n\t\t\t\tcontinue;\n\t\t\t}", "\t\t\tif (c === delimiter) {\n\t\t\t\tcurrent = String.fromCharCode(97 + index);\n\t\t\t\tindex++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (c === delimiterstring) {\n\t\t\t// Check escaped quotes\n\t\t\tif (scope && t[i + 1] === delimiterstring) {\n\t\t\t\ti++;\n\t\t\t} else {\n\t\t\t\tscope = c === scope ? '' : c;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (!tmp)\n\t\t\ttmp = {};", "\t\tif (tmp[current])\n\t\t\ttmp[current] += c;\n\t\telse\n\t\t\ttmp[current] = c;\n\t}", "\ttmp && data.push(tmp);\n\treturn data;\n};", "SP.parseTerminal = function(fields, fn, skip, take) {", "\tvar lines = this.split('\\n');", "\tif (typeof(fields) === 'function') {\n\t\ttake = skip;\n\t\tskip = fn;\n\t\tfn = fields;\n\t\tparseTerminal2(lines, fn, skip, take);\n\t\treturn this;\n\t}", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tvar headers = [];\n\tvar indexer = 0;\n\tvar line = lines[0];", "\tif (!line) {\n\t\tline = lines[1];\n\t\tskip++;\n\t}", "\tif (!line) {\n\t\tline = lines[2];\n\t\tskip++;\n\t}", "\tif (!line)\n\t\treturn this;", "\tvar fieldslength = fields.length;\n\tvar tmp;", "\tfor (var i = 0, length = fieldslength; i < length; i++) {\n\t\tvar field = fields[i];", "\t\tvar beg = -1;\n\t\tvar end = -1;\n\t\tvar type = typeof(field);", "\t\tif (type === 'object' && field.test) {\n\t\t\ttmp = line.match(field);\n\t\t\tif (tmp) {\n\t\t\t\tbeg = tmp.index;\n\t\t\t\tend = beg + tmp.toString().length;\n\t\t\t} else {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t}\n\t\t} else if (type === 'string') {\n\t\t\ttmp = line.indexOf(field);\n\t\t\tif (tmp === -1) {\n\t\t\t\tbeg = -1;\n\t\t\t\tend = -1;\n\t\t\t} else {\n\t\t\t\tbeg = tmp;\n\t\t\t\tend = line.indexOf(' ', beg + field.length);\n\t\t\t}\n\t\t}", "\t\theaders.push({ beg: beg, end: end });\n\t}", "\tfor (var i = skip + 1, length = skip + 1 + take; i < length; i++) {", "\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;", "\t\tvar arr = [];\n\t\tvar is = false;\n\t\tvar beg;", "\t\tfor (var j = 0; j < fieldslength; j++) {\n\t\t\tvar header = headers[j];\n\t\t\tif (header.beg !== -1) {\n\t\t\t\tis = true;\n\t\t\t\tbeg = 0;", "\t\t\t\tfor (var k = header.beg; k > -1; k--) {\n\t\t\t\t\tif (line[k] === ' ') {\n\t\t\t\t\t\tbeg = k + 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}", "\t\t\t\tarr.push(line.substring(beg, header.end === -1 ? undefined : header.end).trim());\n\t\t\t} else\n\t\t\t\tarr.push('');\n\t\t}", "\t\tis && fn(arr, indexer++, length, i);\n\t}", "\treturn this;\n};", "function parseTerminal2(lines, fn, skip, take) {\n\tvar indexer = 0;", "\tif (skip === undefined)\n\t\tskip = 0;\n\tif (take === undefined)\n\t\ttake = lines.length;", "\tfor (var i = skip, length = skip + take; i < length; i++) {\n\t\tvar line = lines[i];\n\t\tif (!line)\n\t\t\tcontinue;\n\t\tvar m = line.match(regexpTERMINAL);\n\t\tm && fn(m, indexer++, length, i);\n\t}\n}", "function parseDateFormat(format, val) {", "\tvar tmp = [];\n\tvar tmpformat = [];\n\tvar prev = '';\n\tvar prevformat = '';\n\tvar allowed = { y: 1, Y: 1, M: 1, m: 1, d: 1, D: 1, H: 1, s: 1, a: 1, w: 1 };", "\tfor (var i = 0; i < format.length; i++) {", "\t\tvar c = format[i];", "\t\tif (!allowed[c])\n\t\t\tcontinue;", "\t\tif (prev !== c) {\n\t\t\tprevformat && tmpformat.push(prevformat);\n\t\t\tprevformat = c;\n\t\t\tprev = c;\n\t\t} else\n\t\t\tprevformat += c;\n\t}", "\tprev = '';", "\tfor (var i = 0; i < val.length; i++) {\n\t\tvar code = val.charCodeAt(i);\n\t\tif (code >= 48 && code <= 57)\n\t\t\tprev += val[i];\n\t}", "\tprevformat && tmpformat.push(prevformat);", "\tvar f = 0;\n\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar l = tmpformat[i].length;\n\t\ttmp.push(prev.substring(f, f + l));\n\t\tf += l;\n\t}", "\tvar dt = {};", "\tfor (var i = 0; i < tmpformat.length; i++) {\n\t\tvar type = tmpformat[i];\n\t\tif (tmp[i])\n\t\t\tdt[type[0]] = +tmp[i];\n\t}", "\tvar h = dt.h || dt.H;", "\tif (h != null) {\n\t\tvar ampm = val.match(REG_TIME);\n\t\tif (ampm && ampm[0].toLowerCase() === 'pm')\n\t\t\th += 12;\n\t}", "\treturn new Date((dt.y || dt.Y) || 0, (dt.M || 1) - 1, dt.d || dt.D || 0, h || 0, dt.m || 0, dt.s || 0);\n}", "SP.parseDate = function(format) {", "\tif (format)\n\t\treturn parseDateFormat(format, this);", "\tvar self = this.trim();\n\tvar lc = self.charCodeAt(self.length - 1);", "\t// Classic date\n\tif (lc === 41)\n\t\treturn new Date(self);", "\t// JSON format\n\tif (lc === 90)\n\t\treturn new Date(Date.parse(self));", "\tvar arr = self.indexOf(' ') === -1 ? self.split('T') : self.split(' ');\n\tvar index = arr[0].indexOf(':');\n\tvar length = arr[0].length;", "\tif (index !== -1) {\n\t\tvar tmp = arr[1];\n\t\tarr[1] = arr[0];\n\t\tarr[0] = tmp;\n\t}", "\tif (arr[0] === undefined)\n\t\tarr[0] = '';", "\tvar noTime = arr[1] === undefined ? true : arr[1].length === 0;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = arr[0].charCodeAt(i);\n\t\tif (c === 45 || c === 46 || (c > 47 && c < 58))\n\t\t\tcontinue;\n\t\tif (noTime)\n\t\t\treturn new Date(self);\n\t}", "\tif (arr[1] === undefined)\n\t\tarr[1] = '00:00:00';", "\tvar firstDay = arr[0].indexOf('-') === -1;", "\tvar date = (arr[0] || '').split(firstDay ? '.' : '-');\n\tvar time = (arr[1] || '').split(':');\n\tvar parsed = [];", "\tif (date.length < 4 && time.length < 2)\n\t\treturn new Date(self);", "\tindex = (time[2] || '').indexOf('.');", "\t// milliseconds\n\tif (index !== -1) {\n\t\ttime[3] = time[2].substring(index + 1);\n\t\ttime[2] = time[2].substring(0, index);\n\t} else\n\t\ttime[3] = '0';", "\tparsed.push(+date[firstDay ? 2 : 0]); // year\n\tparsed.push(+date[1]); // month\n\tparsed.push(+date[firstDay ? 0 : 2]); // day\n\tparsed.push(+time[0]); // hours\n\tparsed.push(+time[1]); // minutes\n\tparsed.push(+time[2]); // seconds\n\tparsed.push(+time[3]); // miliseconds", "\tvar def = new Date();", "\tfor (var i = 0, length = parsed.length; i < length; i++) {\n\t\tif (isNaN(parsed[i]))\n\t\t\tparsed[i] = 0;", "\t\tvar value = parsed[i];\n\t\tif (value !== 0)\n\t\t\tcontinue;", "\t\tswitch (i) {\n\t\t\tcase 0:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getFullYear();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getMonth() + 1;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tif (value <= 0)\n\t\t\t\t\tparsed[i] = def.getDate();\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn new Date(parsed[0], parsed[1] - 1, parsed[2], parsed[3], parsed[4] - NOW.getTimezoneOffset(), parsed[5]);\n};", "SP.parseDateExpiration = function() {\n\tvar self = this;", "\tvar arr = self.split(' ');\n\tvar dt = new Date();\n\tvar length = arr.length;", "\tfor (var i = 0; i < length; i += 2) {\n\t\tvar num = arr[i].parseInt();\n\t\tif (num === 0)\n\t\t\tcontinue;\n\t\tvar type = arr[i + 1];\n\t\tif (type)\n\t\t\tdt = dt.add(type, num);\n\t}", "\treturn dt;\n};", "var configurereplace = function(text) {\n\tvar val = CONF[text.substring(1, text.length - 1)];\n\treturn val == null ? '' : val;\n};", "SP.env = function() {\n\treturn this.replace(regexpCONFIGURE, configurereplace);\n};", "/**\n * Parse configuration from a string\n * @param {Object} def\n * @onerr {Function} error handling\n * @return {Object}\n */\nSP.parseConfig = function(def, onerr) {", "\tif (typeof(def) === 'function') {\n\t\tonerr = def;\n\t\tdef = null;\n\t}", "\tvar arr = this.split('\\n');\n\tvar length = arr.length;\n\tvar obj = def ? exports.extend({}, def) : {};\n\tvar subtype;\n\tvar name;\n\tvar index;\n\tvar value;", "\tfor (var i = 0; i < length; i++) {", "\t\tvar str = arr[i];\n\t\tif (!str || str[0] === '#' || str.substring(0, 2) === '//')\n\t\t\tcontinue;", "\t\tindex = str.indexOf(':');\n\t\tif (index === -1) {\n\t\t\tindex = str.indexOf('\\t:');\n\t\t\tif (index === -1)\n\t\t\t\tcontinue;\n\t\t}", "\t\tname = str.substring(0, index).trim();\n\t\tvalue = str.substring(index + 2).trim();", "\t\tindex = name.indexOf('(');\n\t\tif (index !== -1) {\n\t\t\tsubtype = name.substring(index + 1, name.indexOf(')')).trim().toLowerCase();\n\t\t\tname = name.substring(0, index).trim();\n\t\t} else\n\t\t\tsubtype = '';", "\t\tswitch (subtype) {\n\t\t\tcase 'string':\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t\tcase 'number':\n\t\t\tcase 'float':\n\t\t\tcase 'double':\n\t\t\tcase 'currency':\n\t\t\t\tobj[name] = value.isNumber(true) ? value.parseFloat2() : value.parseInt2();\n\t\t\t\tbreak;\n\t\t\tcase 'boolean':\n\t\t\tcase 'bool':\n\t\t\t\tobj[name] = (/true|on|1|enabled/i).test(value);\n\t\t\t\tbreak;\n\t\t\tcase 'config':\n\t\t\t\tobj[name] = CONF[value];\n\t\t\t\tbreak;\n\t\t\tcase 'eval':\n\t\t\tcase 'object':\n\t\t\tcase 'array':\n\t\t\t\ttry {\n\t\t\t\t\tobj[name] = new Function('return ' + value)();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tif (onerr)\n\t\t\t\t\t\tonerr(e, arr[i]);\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow new Error('A value of \"{0}\" can\\'t be converted to \"{1}\": '.format(name, subtype) + e.toString());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'json':\n\t\t\t\tobj[name] = value.parseJSON(true);\n\t\t\t\tbreak;\n\t\t\tcase 'env':\n\t\t\tcase 'environment':\n\t\t\t\tobj[name] = process.env[value];\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\tcase 'time':\n\t\t\tcase 'datetime':\n\t\t\t\tobj[name] = value.parseDate();\n\t\t\t\tbreak;\n\t\t\tcase 'random':\n\t\t\t\tobj[name] = GUID((value || '0').parseInt() || 10);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tobj[name] = value;\n\t\t\t\tbreak;\n\t\t}\n\t}", "\treturn obj;\n};", "SP.format = function() {\n\tvar arg = arguments;\n\treturn this.replace(regexpSTRINGFORMAT, function(text) {\n\t\tvar value = arg[+text.substring(1, text.length - 1)];\n\t\treturn value == null ? '' : value;\n\t});\n};", "SP.encrypt_uid = function(key) {\n\treturn exports.encrypt_uid(this, key);\n};", "SP.decrypt_uid = function(key) {\n\treturn exports.decrypt_uid(this, key);\n};", "SP.encode = function() {\n\tvar output = '';\n\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i];\n\t\tswitch (c) {\n\t\t\tcase '<':\n\t\t\t\toutput += '&lt;';\n\t\t\t\tbreak;\n\t\t\tcase '>':\n\t\t\t\toutput += '&gt;';\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\toutput += '&quot;';\n\t\t\t\tbreak;\n\t\t\tcase '\\'':\n\t\t\t\toutput += '&apos;';\n\t\t\t\tbreak;\n\t\t\tcase '&':\n\t\t\t\toutput += '&amp;';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\toutput += c;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn output;\n};", "SP.decode = function() {\n\treturn this.replace(regexpDECODE, function(s) {\n\t\tif (s.charAt(1) !== '#')\n\t\t\treturn ALPHA_INDEX[s] || s;\n\t\tvar code = s[2].toLowerCase() === 'x' ? parseInt(s.substr(3), 16) : parseInt(s.substr(2));\n\t\treturn !code || code < -32768 || code > 65535 ? '' : String.fromCharCode(code);\n\t});\n};", "SP.arg = SP.args = function(obj, encode, def) {\n\tif (typeof(encode) === 'string')\n\t\tdef = encode;\n\treturn this.replace(regexpARG, function(text) {\n\t\t// Is double?\n\t\tvar l = text[1] === '{' ? 2 : 1;\n\t\tvar val = obj[text.substring(l, text.length - l).trim()];\n\t\tif (encode && encode === 'json')\n\t\t\treturn JSON.stringify(val);\n\t\treturn val == null ? (def == null ? text : def) : encode ? encode === 'html' ? (val + '').encode() : encodeURIComponent(val + '') : val;\n\t});\n};", "SP.max = function(length, chars) {\n\tvar str = this;\n\tif (chars == null)\n\t\tchars = '...';\n\treturn str.length > length ? str.substring(0, length - chars.length) + chars : str;\n};", "SP.isJSON = function() {\n\tvar self = this;\n\tif (self.length <= 1)\n\t\treturn false;", "\tvar l = self.length - 1;\n\tvar a;\n\tvar b;\n\tvar i = 0;", "\twhile (true) {\n\t\ta = self[i++];\n\t\tif (a === ' ' || a === '\\n' || a === '\\r' || a === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\twhile (true) {\n\t\tb = self[l--];\n\t\tif (b === ' ' || b === '\\n' || b === '\\r' || b === '\\t')\n\t\t\tcontinue;\n\t\tbreak;\n\t}", "\treturn (a === '\"' && b === '\"') || (a === '[' && b === ']') || (a === '{' && b === '}') || (a.charCodeAt(0) > 47 && b.charCodeAt(0) < 57);\n};", "SP.isURL = function() {\n\treturn this.length <= 7 ? false : DEF.validators.url.test(this);\n};", "SP.isZIP = function() {\n\treturn DEF.validators.zip.test(this);\n};", "SP.isEmail = function() {\n\treturn this.length <= 4 ? false : DEF.validators.email.test(this);\n};", "SP.isPhone = function() {\n\treturn this.length < 6 ? false : DEF.validators.phone.test(this);\n};", "SP.isBase64 = function(isdata) {", "\tvar str = this;\n\tvar count = str.length;", "\tif (isdata) {\n\t\tvar index = str.indexOf(';base64,');\n\t\tif (index !== -1)\n\t\t\tcount -= (index + 8);\n\t}", "\treturn count % 4 === 0 && (isdata ? regexpBASE64_2.test(str) : regexpBASE64.test(str));\n};", "SP.isUID = function() {\n\tvar str = this;", "\tif (str.length < 12 && str.length > 25)\n\t\treturn false;", "\tvar is = DEF.validators.uid.test(str);\n\tif (is) {", "\t\tvar sum;\n\t\tvar beg;\n\t\tvar end;\n\t\tvar e = str[str.length - 1];", "\t\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = +str[str.length - 3];\n\t\t\tend = str.length - 5;\n\t\t\tvar tmp = e === 'c' || e === 'd' ? (+str.substring(beg, end)) : parseInt(str.substring(beg, end), 16);\n\t\t\treturn sum === (tmp % 2 ? '1' : '0');\n\t\t} else if (e === 'a') {\n\t\t\tsum = str[str.length - 2];\n\t\t\tbeg = 6;\n\t\t\tend = str.length - 4;\n\t\t} else {\n\t\t\tsum = str[str.length - 1];\n\t\t\tbeg = 10;\n\t\t\tend = str.length - 4;\n\t\t}", "\t\twhile (beg++ < end) {\n\t\t\tif (str[beg] !== '0') {\n\t\t\t\tif (((+str.substring(beg, end)) % 2 ? '1' : '0') === sum)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n};", "SP.parseUID = function() {\n\tvar self = this;\n\tvar obj = {};\n\tvar hash;\n\tvar e = self[self.length - 1];", "\tif (e === 'b' || e === 'c' || e === 'd') {\n\t\tend = +self[self.length - 3];\n\t\tvar ticks = ((e === 'b' ? (+self.substring(0, end)) : parseInt(self.substring(0, end), e=== 'd' ? 36 : 16)) * 1000 * 60) + 1580511600000; // 1.1.2020\n\t\tobj.date = new Date(ticks);\n\t\tbeg = end;\n\t\tend = self.length - 5;\n\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else if (e === 'a') {\n\t\tvar ticks = ((+self.substring(0, 6)) * 1000 * 60) + 1548975600000; // old 1.1.2019\n\t\tobj.date = new Date(ticks);\n\t\tbeg = 7;\n\t\tend = self.length - 4;\n\t\thash = +self.substring(end + 2, end + 3);\n\t\tobj.century = Math.floor((obj.date.getFullYear() - 1) / 100) + 1;\n\t\tobj.hash = self.substring(end, end + 2);\n\t} else {\n\t\tvar y = self.substring(0, 2);\n\t\tvar M = self.substring(2, 4);\n\t\tvar d = self.substring(4, 6);\n\t\tvar H = self.substring(6, 8);\n\t\tvar m = self.substring(8, 10);", "\t\tobj.date = new Date(+('20' + y), (+M) - 1, +d, +H, +m, 0);", "\t\tvar beg = 0;\n\t\tvar end = 0;\n\t\tvar index = 10;", "\t\twhile (true) {", "\t\t\tvar c = self[index];", "\t\t\tif (!c)\n\t\t\t\tbreak;", "\t\t\tif (!beg && c !== '0')\n\t\t\t\tbeg = index;", "\t\t\tif (c.charCodeAt(0) > 96) {\n\t\t\t\tend = index;\n\t\t\t\tbreak;\n\t\t\t}", "\t\t\tindex++;\n\t\t}", "\t\tobj.century = self.substring(end + 4);", "\t\tif (obj.century) {\n\t\t\tobj.century = 20 + (+obj.century);\n\t\t\tobj.date.setYear(obj.date.getFullYear() + 100);\n\t\t} else\n\t\t\tobj.century = 21;", "\t\thash = +self.substring(end + 3, end + 4);\n\t\tobj.hash = self.substring(end, end + 3);\n\t}", "\tobj.index = +self.substring(beg, end);\n\tobj.valid = (obj.index % 2 ? 1 : 0) === hash;\n\treturn obj;\n};", "SP.parseENV = function() {", "\tvar arr = this.split(regexpLINES);\n\tvar obj = {};", "\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar line = arr[i];\n\t\tif (!line || line.substring(0, 2) === '//' || line[0] === '#')\n\t\t\tcontinue;", "\t\tvar index = line.indexOf('=');\n\t\tif (index === -1)\n\t\t\tcontinue;", "\t\tvar key = line.substring(0, index);\n\t\tvar val = line.substring(index + 1).replace(/\\\\n/g, '\\n');\n\t\tvar end = val.length - 1;", "\t\tif ((val[0] === '\"' && val[end] === '\"') || (val[0] === '\\'' && val[end] === '\\''))\n\t\t\tval = val.substring(1, end);\n\t\telse\n\t\t\tval = val.trim();", "\t\tobj[key] = val;\n\t}", "\treturn obj;\n};", "SP.parseInt = function(def) {\n\tvar str = this.trim();\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.parseInt2 = function(def) {\n\tvar num = this.match(regexpINTEGER);\n\treturn num ? +num[0] : (def === undefined ? 0 : def);\n};", "SP.parseFloat2 = function(def) {\n\tvar num = this.match(regexpFLOAT);\n\treturn num ? +num[0].toString().replace(/,/g, '.') : (def === undefined ? 0 : def);\n};", "SP.parseBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn self === 'true' || self === '1' || self === 'on';\n};", "SP.parseFloat = function(def) {\n\tvar str = this.trim();\n\tif (str.indexOf(',') !== -1)\n\t\tstr = str.replace(',', '.');\n\tvar num = +str;\n\treturn isNaN(num) ? (def === undefined ? 0 : def) : num;\n};", "SP.capitalize = function(first) {", "\tif (first)\n\t\treturn (this[0] || '').toUpperCase() + this.substring(1);", "\tvar builder = '';\n\tvar c;", "\tfor (var i = 0, length = this.length; i < length; i++) {\n\t\tvar c = this[i - 1];\n\t\tif (!c || (c === ' ' || c === '\\t' || c === '\\n'))\n\t\t\tc = this[i].toUpperCase();\n\t\telse\n\t\t\tc = this[i];\n\t\tbuilder += c;\n\t}", "\treturn builder;\n};", "SP.toUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tvar c = this[i].charCodeAt(0);\n\t\tif(c > 126 || c < 32)\n\t\t\toutput += '\\\\u' + ('000' + c.toString(16)).substr(-4);\n\t\telse\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.fromUnicode = function() {\n\tvar output = '';\n\tfor (var i = 0; i < this.length; i++) {\n\t\tif (this[i] === '\\\\' && this[i + 1] === 'u') {\n\t\t\toutput += String.fromCharCode(parseInt(this[i + 2] + this[i + 3] + this[i + 4] + this[i + 5], 16));\n\t\t\ti += 5;\n\t\t} else\n\t\t\toutput += this[i];\n\t}\n\treturn output;\n};", "SP.sha1 = function(salt) {\n\tvar hash = Crypto.createHash('sha1');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha256 = function(salt) {\n\tvar hash = Crypto.createHash('sha256');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.sha512 = function(salt) {\n\tvar hash = Crypto.createHash('sha512');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.md5 = function(salt) {\n\tvar hash = Crypto.createHash('md5');\n\thash.update(this + (salt || ''), ENCODING);\n\treturn hash.digest('hex');\n};", "SP.toSearch = function() {\n\tvar str = this.replace(regexpSEARCH, '').trim().toLowerCase().toASCII();\n\tvar buf = [];\n\tvar prev = '';\n\tfor (var i = 0, length = str.length; i < length; i++) {\n\t\tvar c = str[i];\n\t\tif (c === 'y')\n\t\t\tc = 'i';\n\t\tif (c === prev)\n\t\t\tcontinue;\n\t\tprev = c;\n\t\tbuf.push(c);\n\t}", "\treturn buf.join('');\n};", "SP.toKeywords = SP.keywords = function(forSearch, alternative, max_count, max_length, min_length) {\n\treturn exports.keywords(this, forSearch, alternative, max_count, max_length, min_length);\n};", "function checksum(val) {\n\tvar sum = 0;\n\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);\n\treturn sum;\n}", "SP.encrypt = function(key, isUnique, secret) {\n\tvar str = '0' + this;\n\tvar data_count = str.length;\n\tvar key_count = key.length;\n\tvar random = isUnique ? exports.random(120) + 40 : 65;\n\tvar count = data_count + (random % key_count);\n\tvar values = [];\n\tvar index = 0;", "\tvalues[0] = String.fromCharCode(random);", "\tvar counter = this.length + key.length;", "\tfor (var i = count - 1; i > 0; i--) {\n\t\tindex = str.charCodeAt(i % data_count);\n\t\tvalues[i] = String.fromCharCode(index ^ (key.charCodeAt(i % key_count) ^ random));\n\t}", "\tstr = Buffer.from(counter + '=' + values.join(''), ENCODING).toString('hex');\n\tvar sum = 0;", "\tfor (var i = 0; i < str.length; i++)\n\t\tsum += str.charCodeAt(i);", "\treturn (sum + checksum((secret || CONF.secret) + key)) + '-' + str;\n};", "SP.decrypt = function(key, secret) {", "\tvar index = this.indexOf('-');\n\tif (index === -1)\n\t\treturn null;", "\tvar cs = +this.substring(0, index);\n\tif (!cs || isNaN(cs))\n\t\treturn null;", "\tvar hash = this.substring(index + 1);\n\tvar sum = checksum((secret || CONF.secret) + key);\n\tfor (var i = 0; i < hash.length; i++)\n\t\tsum += hash.charCodeAt(i);", "\tif (sum !== cs)\n\t\treturn null;", "\tvar values = Buffer.from(hash, 'hex').toString(ENCODING);\n\tvar index = values.indexOf('=');\n\tif (index === -1)\n\t\treturn null;", "\tvar counter = +values.substring(0, index);\n\tif (isNaN(counter))\n\t\treturn null;", "\tvalues = values.substring(index + 1);", "\tvar count = values.length;\n\tvar random = values.charCodeAt(0);\n\tvar key_count = key.length;\n\tvar data_count = count - (random % key_count);\n\tvar decrypt_data = [];", "\tfor (var i = data_count - 1; i > 0; i--) {\n\t\tindex = values.charCodeAt(i) ^ (random ^ key.charCodeAt(i % key_count));\n\t\tdecrypt_data[i] = String.fromCharCode(index);\n\t}", "\tvar val = decrypt_data.join('');\n\treturn counter !== (val.length + key.length) ? null : val;\n};", "exports.encrypt_data = function(value, key, encode) {", "\tvar builder = [];\n\tvar index = 0;\n\tvar length = key.length;", "\tfor (var i = 0; i < value.length; i++) {", "\t\tif (SKIPBODYENCRYPTOR[value[i]]) {\n\t\t\tbuilder.push(value[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (index === length)\n\t\t\tindex = 0;", "\t\tvar a = value.charCodeAt(i) + 2;\n\t\tvar b = key.charCodeAt(index++);\n\t\tvar t = (a + b).toString(36);\n\t\tbuilder.push(t.length + t);\n\t}", "\tvar mask = Buffer.alloc(4);\n\tmask.writeInt32BE((Math.random() * 214748364) >> 0);", "\tvar buffer = Buffer.from(builder.join(''));\n\tfor (var i = 0; i < buffer.length; i++)\n\t\tbuffer[i] = buffer[i] ^ mask[i % 4];", "\tvar buf = Buffer.concat([mask, buffer]);\n\treturn encode === 'buffer' ? buf : buf.toString(encode || 'base64');\n};", "exports.decrypt_data = function(value, key, encode) {", "\ttry {\n\t\tvalue = value instanceof Buffer ? value : Buffer.from(value, encode || 'base64');\n\t} catch (e) {\n\t\treturn null;\n\t}", "\tvar index = 0;\n\tvar length = key.length;\n\tvar builder = [];\n\tvar mask = Buffer.alloc(4);\n\tvar buffer = Buffer.alloc(value.length - 4);\n\tmask.writeInt32BE(value.readInt32BE(0));", "\tfor (var i = 4; i < value.length; i++)\n\t\tbuffer[i - 4] = value[i] ^ mask[i % 4];", "\tvalue = buffer.toString('utf8');", "\tfor (var i = 0; i < value.length; i++) {", "\t\tvar c = value[i];", "\t\tif (SKIPBODYENCRYPTOR[c]) {\n\t\t\tbuilder.push(c);\n\t\t\tcontinue;\n\t\t}", "\t\tif (index === length)\n\t\t\tindex = 0;", "\t\tvar l = +value.charAt(i);\n\t\tvar code = parseInt(value.substring(i + 1, i + 1 + l), 36);\n\t\tvar b = key.charCodeAt(index++);\n\t\tbuilder.push(String.fromCharCode(code - b - 2));\n\t\ti += l;\n\t}", "\treturn builder.join('');\n};", "exports.encrypt_uid = function(val, key) {", "\tvar num = typeof(val) === 'number';\n\tvar sum = 0;", "\tif (!key)\n\t\tkey = CONF.secret;", "\tval = val + '';", "\tfor (var i = 0; i < val.length; i++)\n\t\tsum += val.charCodeAt(i);", "\tfor (var i = 0; i < key.length; i++)\n\t\tsum += key.charCodeAt(i);", "\treturn (num ? 'n' : 'x') + (CONF.secret_uid + val + sum + key).crc32(true).toString(32) + 'x' + val;\n};", "exports.decrypt_uid = function(val, key) {\n\tvar num = val[0] === 'n';\n\tvar raw = val.substring(val.indexOf('x', 1) + 1);", "\tif (num)\n\t\traw = +raw;", "\treturn exports.encrypt_uid(raw, key) === val ? raw : null;\n};", "exports.encrypt_crypto = function(type, key, value) {\n\tif (!F.temporary.keys[key])\n\t\tF.temporary.keys[key] = Buffer.from(key);\n\tvar cipher = Crypto.createCipheriv(type, F.temporary.keys[key], CONF.default_crypto_iv);\n\tCONCAT[0] = cipher.update(value);\n\tCONCAT[1] = cipher.final();\n\treturn Buffer.concat(CONCAT);\n};", "exports.decrypt_crypto = function(type, key, value) {\n\tif (!F.temporary.keys[key])\n\t\tF.temporary.keys[key] = Buffer.from(key);\n\tvar decipher = Crypto.createDecipheriv(type, F.temporary.keys[key], CONF.default_crypto_iv);\n\ttry {\n\t\tCONCAT[0] = decipher.update(value);\n\t\tCONCAT[1] = decipher.final();\n\t\treturn Buffer.concat(CONCAT);\n\t} catch (e) {}\n};", "SP.base64ToFile = function(filename, callback) {\n\tvar self = this;\n\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;\n\tFs.writeFile(filename, self.substring(index), 'base64', callback || NOOP);\n\treturn this;\n};", "SP.base64ToBuffer = function() {\n\tvar self = this;", "\tvar index = self.indexOf(',');\n\tif (index === -1)\n\t\tindex = 0;\n\telse\n\t\tindex++;", "\treturn Buffer.from(self.substring(index), 'base64');\n};", "SP.base64ContentType = function() {\n\tvar self = this;\n\tvar index = self.indexOf(';');\n\treturn index === -1 ? '' : self.substring(5, index);\n};", "var toascii = c => DIACRITICSMAP[c] || c;", "SP.toASCII = function() {\n\treturn this.replace(regexpDiacritics, toascii);\n};", "SP.indent = function(max, c) {\n\tvar plus = '';\n\tif (c === undefined)\n\t\tc = ' ';\n\twhile (max--)\n\t\tplus += c;\n\treturn plus + this;\n};", "SP.isNumber = function(isDecimal) {", "\tvar self = this;\n\tvar length = self.length;", "\tif (!length)\n\t\treturn false;", "\tisDecimal = isDecimal || false;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar ascii = self.charCodeAt(i);", "\t\tif (isDecimal) {\n\t\t\tif (ascii === 44 || ascii === 46) {\n\t\t\t\tisDecimal = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}", "\t\tif (ascii < 48 || ascii > 57)\n\t\t\treturn false;\n\t}", "\treturn true;\n};", "if (!SP.padLeft) {\n\tSP.padLeft = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself = c + self;\n\t\treturn self;\n\t};\n}", "\nif (!SP.padRight) {\n\tSP.padRight = function(max, c) {\n\t\tvar self = this;\n\t\tvar len = max - self.length;\n\t\tif (len < 0)\n\t\t\treturn self;\n\t\tif (c === undefined)\n\t\t\tc = ' ';\n\t\twhile (len--)\n\t\t\tself += c;\n\t\treturn self;\n\t};\n}", "SP.insert = function(index, value) {\n\tvar str = this;\n\tvar a = str.substring(0, index);\n\tvar b = value.toString() + str.substring(index);\n\treturn a + b;\n};", "/**\n * Create a link from String\n * @param {Number} max A maximum length, default: 60 and optional.\n * @return {String}\n */\nSP.slug = function(max) {\n\tmax = max || 60;", "\tvar self = this.trim().toLowerCase().toASCII();\n\tvar builder = '';\n\tvar length = self.length;", "\tfor (var i = 0; i < length; i++) {\n\t\tvar c = self[i];\n\t\tvar code = self.charCodeAt(i);", "\t\tif (code > 540){\n\t\t\tbuilder = '';\n\t\t\tbreak;\n\t\t}", "\t\tif (builder.length >= max)\n\t\t\tbreak;", "\t\tif (code > 31 && code < 48) {\n\t\t\tif (builder[builder.length - 1] !== '-')\n\t\t\t\tbuilder += '-';\n\t\t\tcontinue;\n\t\t}", "\t\tif ((code > 47 && code < 58) || (code > 94 && code < 123))\n\t\t\tbuilder += c;\n\t}", "\tif (builder.length > 1) {\n\t\tlength = builder.length - 1;\n\t\treturn builder[length] === '-' ? builder.substring(0, length) : builder;\n\t} else if (!length)\n\t\treturn '';", "\tlength = self.length;\n\tself = self.replace(/\\s/g, '');\n\tbuilder = self.crc32(true).toString(36) + '';\n\treturn self[0].charCodeAt(0).toString(32) + builder + self[self.length - 1].charCodeAt(0).toString(32) + length;\n};", "SP.pluralize = function(zero, one, few, other) {\n\treturn this.parseInt().pluralize(zero, one, few, other);\n};", "SP.isBoolean = function() {\n\tvar self = this.toLowerCase();\n\treturn (self === 'true' || self === 'false') ? true : false;\n};", "/**\n* Remove all Html Tags from a string\n* @return {string}\n*/\nSP.removeTags = function() {\n\treturn this.replace(regexpTags, '');\n};", "NP.between = function(condition, otherwise) {", "\tvar val = this;", "\tfor (var key in condition) {", "\t\tvar arr = key.split('-');", "\t\tvar a = arr[0] ? +arr[0] : null;\n\t\tvar b = arr[1] ? +arr[1] : null;", "\t\tif (a != null && b !== null) {\n\t\t\tif (val >= a && val <= b)\n\t\t\t\treturn condition[key];\n\t\t} else if (a != null) {\n\t\t\tif (val >= a)\n\t\t\t\treturn condition[key];\n\t\t} else if (b != null)\n\t\t\tif (val <= b)\n\t\t\t\treturn condition[key];\n\t}", "\treturn otherwise;\n};", "NP.floor = function(decimals) {\n\treturn Math.floor(this * Math.pow(10, decimals)) / Math.pow(10, decimals);\n};", "NP.fixed = function(decimals) {\n\treturn +this.toFixed(decimals);\n};", "NP.padLeft = function(max, c) {\n\treturn this.toString().padLeft(max, c || '0');\n};", "NP.padRight = function(max, c) {\n\treturn this.toString().padRight(max, c || '0');\n};", "NP.round = function(precision) {\n\tvar m = Math.pow(10, precision) || 1;\n\treturn Math.round(this * m) / m;\n};", "NP.currency = function(currency, a, b, c) {\n\tvar curr = DEF.currencies[currency || 'default'];\n\treturn curr ? curr(this, a, b, c) : this.format(2);\n};", "/**\n * Async decrements\n * @param {Function(index, next)} fn\n * @param {Function} callback\n * @return {Number}\n */\nNP.async = function(fn, callback) {\n\tvar number = this;\n\tif (number)\n\t\tfn(number--, () => setImmediate(() => number.async(fn, callback)));\n\telse\n\t\tcallback && callback();\n\treturn number;\n};", "/**\n * Format number\n * @param {Number} decimals Maximum decimal numbers\n * @param {String} separator Number separator, default ' '\n * @param {String} separatorDecimal Decimal separator, default '.' if number separator is ',' or ' '.\n * @return {String}\n */\nNP.format = function(decimals, separator, separatorDecimal) {", "\tvar self = this;\n\tvar num = self.toString();\n\tvar dec = '';\n\tvar output = '';\n\tvar minus = num[0] === '-' ? '-' : '';\n\tif (minus)\n\t\tnum = num.substring(1);", "\tvar index = num.indexOf('.');", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = separator;\n\t\tseparator = decimals;\n\t\tdecimals = tmp;\n\t}", "\tif (separator === undefined)\n\t\tseparator = ' ';", "\tif (index !== -1) {\n\t\tdec = num.substring(index + 1);\n\t\tnum = num.substring(0, index);\n\t}", "\tindex = -1;\n\tfor (var i = num.length - 1; i >= 0; i--) {\n\t\tindex++;\n\t\tif (index > 0 && index % 3 === 0)\n\t\t\toutput = separator + output;\n\t\toutput = num[i] + output;\n\t}", "\tif (decimals || dec.length) {\n\t\tif (dec.length > decimals)\n\t\t\tdec = dec.substring(0, decimals || 0);\n\t\telse\n\t\t\tdec = dec.padRight(decimals || 0, '0');\n\t}", "\tif (dec.length && separatorDecimal === undefined)\n\t\tseparatorDecimal = separator === '.' ? ',' : '.';", "\treturn minus + output + (dec.length ? separatorDecimal + dec : '');\n};", "NP.add = function(value, decimals) {", "\tif (value == null)\n\t\treturn this;", "\tif (typeof(value) === 'number')\n\t\treturn this + value;", "\tvar first = value.charCodeAt(0);\n\tvar is = false;", "\tif (first < 48 || first > 57) {\n\t\tis = true;\n\t\tvalue = value.substring(1);\n\t}", "\tvar length = value.length;\n\tvar num;", "\tif (value[length - 1] === '%') {\n\t\tvalue = value.substring(0, length - 1);\n\t\tif (is) {\n\t\t\tvar val = value.parseFloat();\n\t\t\tswitch (first) {\n\t\t\t\tcase 42:\n\t\t\t\t\tnum = this * ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 43:\n\t\t\t\t\tnum = this + ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 45:\n\t\t\t\t\tnum = this - ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 47:\n\t\t\t\t\tnum = this / ((this / 100) * val);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t} else {\n\t\t\tnum = (this / 100) * value.parseFloat();\n\t\t\treturn decimals !== undefined ? num.floor(decimals) : num;\n\t\t}", "\t} else\n\t\tnum = value.parseFloat();", "\tswitch (first) {\n\t\tcase 42:\n\t\t\tnum = this * num;\n\t\t\tbreak;\n\t\tcase 43:\n\t\t\tnum = this + num;\n\t\t\tbreak;\n\t\tcase 45:\n\t\t\tnum = this - num;\n\t\t\tbreak;\n\t\tcase 47:\n\t\t\tnum = this / num;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tnum = this;\n\t\t\tbreak;\n\t}", "\tif (decimals !== undefined)\n\t\treturn num.floor(decimals);", "\treturn num;\n};", "NP.pluralize = function(zero, one, few, other) {", "\tvar num = this;\n\tvar value = '';", "\tif (num == 0)\n\t\tvalue = zero || '';\n\telse if (num == 1)\n\t\tvalue = one || '';\n\telse if (num > 1 && num < 5)\n\t\tvalue = few || '';\n\telse\n\t\tvalue = other;", "\tvar beg = value.indexOf('#');\n\tif (beg === -1)\n\t\treturn value;", "\tvar end = value.lastIndexOf('#');\n\tvar format = value.substring(beg, end + 1);\n\treturn num.format(format) + value.replace(format, '');\n};", "NP.hex = function(length) {\n\tvar str = this.toString(16).toUpperCase();\n\twhile(str.length < length)\n\t\tstr = '0' + str;\n\treturn str;\n};", "NP.VAT = function(percentage, decimals, includedVAT) {\n\tvar num = this;\n\tvar type = typeof(decimals);", "\tif (type === 'boolean') {\n\t\tvar tmp = includedVAT;\n\t\tincludedVAT = decimals;\n\t\tdecimals = tmp;\n\t\ttype = typeof(decimals);\n\t}", "\tif (type === 'undefined')\n\t\tdecimals = 2;", "\treturn !percentage || !num ? num.round(decimals) : includedVAT ? (num / ((percentage / 100) + 1)).round(decimals) : (num * ((percentage / 100) + 1)).round(decimals);\n};", "NP.discount = function(percentage, decimals) {\n\tvar num = this;\n\tif (decimals === undefined)\n\t\tdecimals = 2;\n\treturn !num || !percentage ? num : (num - (num / 100) * percentage).floor(decimals);\n};", "NP.parseDate = function(plus) {\n\treturn new Date(this + (plus || 0));\n};", "if (!NP.toRad) {\n\tNP.toRad = function () {\n\t\treturn this * Math.PI / 180;\n\t};\n}", "NP.filesize = function(decimals, type) {", "\tif (typeof(decimals) === 'string') {\n\t\tvar tmp = type;\n\t\ttype = decimals;\n\t\tdecimals = tmp;\n\t}", "\tvar value;", "\t// this === bytes\n\tswitch (type) {\n\t\tcase 'bytes':\n\t\t\tvalue = this;\n\t\t\tbreak;\n\t\tcase 'KB':\n\t\t\tvalue = this / 1024;\n\t\t\tbreak;\n\t\tcase 'MB':\n\t\t\tvalue = filesizehelper(this, 2);\n\t\t\tbreak;\n\t\tcase 'GB':\n\t\t\tvalue = filesizehelper(this, 3);\n\t\t\tbreak;\n\t\tcase 'TB':\n\t\t\tvalue = filesizehelper(this, 4);\n\t\t\tbreak;\n\t\tdefault:", "\t\t\ttype = 'bytes';\n\t\t\tvalue = this;", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'KB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'MB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'GB';\n\t\t\t}", "\t\t\tif (value > 1023) {\n\t\t\t\tvalue = value / 1024;\n\t\t\t\ttype = 'TB';\n\t\t\t}", "\t\t\tbreak;\n\t}", "\ttype = ' ' + type;\n\treturn (decimals === undefined ? value.format(2).replace('.00', '') : value.format(decimals)) + type;\n};", "function filesizehelper(number, count) {\n\twhile (count--) {\n\t\tnumber = number / 1024;\n\t\tif (number.toFixed(3) === '0.000')\n\t\t\treturn 0;\n\t}\n\treturn number;\n}", "var AP = Array.prototype;", "/**\n * Take items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.take = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tfor (var i = 0; i < self.length; i++) {\n\t\tarr.push(self[i]);\n\t\tif (arr.length >= count)\n\t\t\treturn arr;\n\t}\n\treturn arr;\n};", "/**\n * First item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.first = function(def) {\n\tvar item = this[0];\n\treturn item === undefined ? def : item;\n};", "/**\n * Create object from Array\n * @param {String} name Optional, property name.\n * @return {Object}\n */\nAP.toObject = function(name) {", "\tvar self = this;\n\tvar obj = {};", "\tfor (var i = 0; i < self.length; i++) {\n\t\tvar item = self[i];\n\t\tif (name)\n\t\t\tobj[item[name]] = item;\n\t\telse\n\t\t\tobj[item] = true;\n\t}", "\treturn obj;\n};", "/**\n * Last item in array\n * @param {Object} def Default value.\n * @return {Object}\n */\nAP.last = function(def) {\n\tvar item = this[this.length - 1];\n\treturn item === undefined ? def : item;\n};", "AP.quicksort = function(sort) {", "\tvar self = this;\n\tif (self.length < 2)\n\t\treturn self;", "\t// Backward compatibility\n\tif (!sort) {\n\t\tself.sort(COMPARER);\n\t\treturn self;\n\t}", "\t// Backward compatibility\n\tif (sort === true) {\n\t\tself.sort(COMPARER_DESC);\n\t\treturn self;\n\t}", "\tif (arguments[1] === true || arguments[1] === 2)\n\t\tsort += '_desc';", "\tshellsort(self, exports.sortcomparer(sort));\n\treturn self;\n};", "exports.sortcomparer = function(sort) {", "\tvar key = 'sort_' + sort;\n\tvar meta = F.temporary.other[key];", "\tif (!meta) {\n\t\tmeta = [];\n\t\tsort = sort.replace(/\\s/g, '').split(',');\n\t\tfor (var i = 0; i < sort.length; i++) {\n\t\t\tvar tmp = sort[i].split((/_(desc|asc)/));\n\t\t\tvar obj = { name: tmp[0], type: null, desc: tmp[1] === 'desc' };\n\t\t\tif (tmp[0].indexOf('.') !== -1)\n\t\t\t\tobj.read = new Function('val', 'return val.' + tmp[0].replace(/\\./g, '?.'));\n\t\t\tmeta.push(obj);\n\t\t}\n\t\tF.temporary.other[key] = meta;\n\t}", "\treturn function(a, b) {\n\t\tfor (var i = 0; i < meta.length; i++) {\n\t\t\tvar col = meta[i];\n\t\t\tvar va = col.read ? col.read(a) : a[col.name];\n\t\t\tvar vb = col.read ? col.read(b) : b[col.name];", "\t\t\tif (!col.type) {\n\t\t\t\tif (va != null)\n\t\t\t\t\tcol.type = va instanceof Date ? 4 : typeof(va);\n\t\t\t\telse if (vb != null)\n\t\t\t\t\tcol.type = vb instanceof Date ? 4: typeof(vb);\n\t\t\t\tswitch (col.type) {\n\t\t\t\t\tcase 'string':\n\t\t\t\t\t\tcol.type = 1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'number':\n\t\t\t\t\t\tcol.type = 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'boolean':\n\t\t\t\t\t\tcol.type = 3;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'object':\n\t\t\t\t\t\tcol.type = 5;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}", "\t\t\tif (col.type) {\n\t\t\t\tswitch (col.type) {", "\t\t\t\t\tcase 1:\n\t\t\t\t\t\ttmp = col.desc ? COMPARER_DESC(va, vb) : COMPARER(va, vb);\n\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;\n\t\t\t\t\t\tbreak;", "\t\t\t\t\tcase 2:\n\t\t\t\t\t\ttmp = va > vb ? (col.desc ? -1 : 1) : va < vb ? (col.desc ? 1 : -1) : 0;\n\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;\n\t\t\t\t\t\tbreak;", "\t\t\t\t\tcase 3:\n\t\t\t\t\t\ttmp = va === true && vb === false ? (col.desc ? -1 : 1) : va === false && vb === true ? (col.desc ? 1 : -1) : 0;\n\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;\n\t\t\t\t\t\tbreak;", "\t\t\t\t\tcase 4:", "\t\t\t\t\t\tif (!va && !vb)\n\t\t\t\t\t\t\tbreak;", "\t\t\t\t\t\tif (va && !vb)\n\t\t\t\t\t\t\treturn col.desc ? -1 : 1;", "\t\t\t\t\t\tif (!va && vb)\n\t\t\t\t\t\t\treturn col.desc ? 1 : -1;", "\t\t\t\t\t\tif (!va.getTime)\n\t\t\t\t\t\t\tva = new Date(va);", "\t\t\t\t\t\tif (!vb.getTime)\n\t\t\t\t\t\t\tvb = new Date(vb);", "\t\t\t\t\t\ttmp = va > vb ? (col.desc ? -1 : 1) : va < vb ? (col.desc ? 1 : -1) : 0;", "\t\t\t\t\t\tif (tmp)\n\t\t\t\t\t\t\treturn tmp;", "\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\treturn 0;\n\t\t}", "\t\treturn 0;\n\t};\n};", "AP.trim = function() {\n\tvar self = this;\n\tvar output = [];\n\tfor (var i = 0, length = self.length; i < length; i++) {\n\t\tif (typeof(self[i]) === 'string')\n\t\t\tself[i] = self[i].trim();\n\t\tself[i] && output.push(self[i]);\n\t}\n\treturn output;\n};", "/**\n * Skip items from array\n * @param {Number} count\n * @return {Array}\n */\nAP.skip = function(count) {\n\tvar arr = [];\n\tvar self = this;\n\tvar length = self.length;\n\tfor (var i = 0; i < length; i++)\n\t\ti >= count && arr.push(self[i]);\n\treturn arr;\n};", "/**\n * Find items in Array\n * @param {Function(item, index) or String/Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.findAll = function(cb, value) {", "\tvar self = this;\n\tvar selected = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tcb.call(self, self[i], i) && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] === value && selected.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] === cb && selected.push(self[i]);\n\t}", "\treturn selected;\n};", "AP.findValue = function(cb, value, path, def) {\n\tvar index = this.findIndex(cb, value);\n\tif (index !== -1) {\n\t\tvar item = this[index][path];\n\t\treturn item == null ? def : item;\n\t}\n\treturn def;\n};", "AP.findItem = function(cb, value) {\n\tvar self = this;\n\tvar index = self.findIndex(cb, value);\n\tif (index === -1)\n\t\treturn null;\n\treturn self[index];\n};", "AP.findIndex = function(cb, value) {", "\tvar self = this;\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\tif (cb.call(self, self[i], i))\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tif (self[i] && self[i][cb] === value)\n\t\t\t\treturn i;\n\t\t\tcontinue;\n\t\t}", "\t\tif (self[i] === cb)\n\t\t\treturn i;\n\t}", "\treturn -1;\n};", "/**\n * Remove items from Array\n * @param {Function(item, index) or Object} cb\n * @param {Object} value Optional.\n * @return {Array}\n */\nAP.remove = function(cb, value) {", "\tvar self = this;\n\tvar arr = [];\n\tvar isFN = typeof(cb) === 'function';\n\tvar isV = value !== undefined;", "\tfor (var i = 0, length = self.length; i < length; i++) {", "\t\tif (isFN) {\n\t\t\t!cb.call(self, self[i], i) && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tif (isV) {\n\t\t\tself[i] && self[i][cb] !== value && arr.push(self[i]);\n\t\t\tcontinue;\n\t\t}", "\t\tself[i] !== cb && arr.push(self[i]);\n\t}\n\treturn arr;\n};", "AP.wait = function(onItem, callback, thread, tmp) {", "\tvar self = this;\n\tvar init = false;", "\t// INIT\n\tif (!tmp) {", "\t\tif (typeof(callback) !== 'function') {\n\t\t\tthread = callback;\n\t\t\tcallback = null;\n\t\t}", "\t\ttmp = {};\n\t\ttmp.pending = 0;\n\t\ttmp.index = 0;\n\t\ttmp.thread = thread;", "\t\t// thread === Boolean then array has to be removed item by item", "\t\tinit = true;\n\t}", "\tvar item = thread === true ? self.shift() : self[tmp.index++];\n\tif (item === undefined) {\n\t\tif (!tmp.pending) {\n\t\t\tcallback && callback();\n\t\t\ttmp.cancel = true;\n\t\t}\n\t\treturn self;\n\t}", "\ttmp.pending++;\n\tonItem.call(self, item, () => setImmediate(next_wait, self, onItem, callback, thread, tmp), tmp.index);", "\tif (!init || tmp.thread === 1)\n\t\treturn self;", "\tfor (var i = 1; i < tmp.thread; i++)\n\t\tself.wait(onItem, callback, 1, tmp);", "\treturn self;\n};", "function next_wait(self, onItem, callback, thread, tmp) {\n\ttmp.pending--;\n\tself.wait(onItem, callback, thread, tmp);\n}", "/**\n * Creates a function async list\n * @param {Function} callback Optional\n * @return {Array}\n */\nAP.async = function(thread, callback, pending) {", "\tvar self = this;", "\tif (typeof(thread) === 'function') {\n\t\tcallback = thread;\n\t\tthread = 1;\n\t} else if (thread === undefined)\n\t\tthread = 1;", "\tif (pending === undefined)\n\t\tpending = 0;", "\tvar item = self.shift();\n\tif (item === undefined) {\n\t\tif (!pending) {\n\t\t\tpending = undefined;\n\t\t\tcallback && callback();\n\t\t}\n\t\treturn self;\n\t}", "\tfor (var i = 0; i < thread; i++) {", "\t\tif (i)\n\t\t\titem = self.shift();", "\t\tpending++;\n\t\titem(function() {\n\t\t\tsetImmediate(function() {\n\t\t\t\tpending--;\n\t\t\t\tself.async(1, callback, pending);\n\t\t\t});\n\t\t});\n\t}", "\treturn self;\n};", "// Fisher-Yates shuffle\nAP.random = function(item) {\n\tif (item)\n\t\treturn this[exports.random(this.length - 1)];\n\tfor (var i = this.length - 1; i > 0; i--) {\n\t\tvar j = Math.floor(Math.random() * (i + 1));\n\t\tvar temp = this[i];\n\t\tthis[i] = this[j];\n\t\tthis[j] = temp;\n\t}\n\treturn this;\n};", "AP.limit = function(max, fn, callback, index) {", "\tif (index === undefined)\n\t\tindex = 0;", "\tvar current = [];\n\tvar self = this;\n\tvar length = index + max;", "\tfor (var i = index; i < length; i++) {\n\t\tvar item = self[i];", "\t\tif (item !== undefined) {\n\t\t\tcurrent.push(item);\n\t\t\tcontinue;\n\t\t}", "\t\tif (!current.length) {\n\t\t\tcallback && callback();\n\t\t\treturn self;\n\t\t}", "\t\tfn(current, () => callback && callback(), index, index + max);\n\t\treturn self;\n\t}", "\tif (!current.length) {\n\t\tcallback && callback();\n\t\treturn self;\n\t}", "\tfn(current, function() {\n\t\tif (length < self.length)\n\t\t\tself.limit(max, fn, callback, length);\n\t\telse\n\t\t\tcallback && callback();\n\t}, index, index + max);", "\treturn self;\n};", "ArrayBuffer.prototype.toBuffer = function() {\n\tvar buf = new Buffer(this.byteLength);\n\tvar view = new Uint8Array(this);\n\tfor (var i = 0; i < buf.length; ++i)\n\t\tbuf[i] = view[i];\n\treturn buf;\n};", "function FileList() {\n\tthis.pending = [];\n\tthis.pendingDirectory = [];\n\tthis.directory = [];\n\tthis.file = [];\n\tthis.onComplete = null;\n\tthis.onFilter = null;\n\tthis.advanced = false;\n}", "const FLP = FileList.prototype;", "FLP.reset = function() {\n\tthis.file.length = 0;\n\tthis.directory.length = 0;\n\tthis.pendingDirectory.length = 0;\n\treturn this;\n};", "FLP.walk = function(directory) {", "\tvar self = this;", "\tif (directory instanceof Array) {\n\t\tvar length = directory.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pendingDirectory.push(directory[i]);\n\t\tself.next();\n\t\treturn;\n\t}", "\tFs.readdir(directory, function(err, arr) {\n\t\tif (err)\n\t\t\treturn self.next();\n\t\tvar length = arr.length;\n\t\tfor (var i = 0; i < length; i++)\n\t\t\tself.pending.push(Path.join(directory, arr[i]));\n\t\tself.next();\n\t});\n};", "FLP.stat = function(path) {\n\tvar self = this;", "\tFs.stat(path, function(err, stats) {", "\t\tif (err)\n\t\t\treturn self.next();", "\t\tif (stats.isDirectory()) {\n\t\t\tpath = self.clean(path);\n\t\t\tif (!self.onFilter || self.onFilter(path, true)) {\n\t\t\t\tself.directory.push(path);\n\t\t\t\tself.pendingDirectory.push(path);\n\t\t\t}\n\t\t} else if (!self.onFilter || self.onFilter(path, false))\n\t\t\tself.file.push(self.advanced ? { filename: path, stats: stats } : path);", "\t\tself.next();\n\t});\n};", "FLP.clean = function(path) {\n\treturn path[path.length - 1] === Path.sep ? path : path + Path.sep;\n};", "FLP.next = function() {\n\tvar self = this;", "\tif (self.pending.length) {\n\t\tvar item = self.pending.shift();\n\t\tself.stat(item);\n\t\treturn;\n\t}", "\tif (self.pendingDirectory.length) {\n\t\tvar directory = self.pendingDirectory.shift();\n\t\tself.walk(directory);\n\t\treturn;\n\t}", "\tself.onComplete(self.file, self.directory);\n};\n", "", "exports.async = function(fn, isApply) {\n\tvar context = this;\n\treturn function(complete) {", "\t\tvar self = this;\n\t\tvar argv;", "\t\tif (arguments.length) {", "\t\t\tif (isApply) {\n\t\t\t\t// index.js/Subscribe.prototype.doExecute\n\t\t\t\targv = arguments[1];\n\t\t\t} else {\n\t\t\t\targv = [];\n\t\t\t\tfor (var i = 1; i < arguments.length; i++)\n\t\t\t\t\targv.push(arguments[i]);\n\t\t\t}\n\t\t} else\n\t\t\targv = new Array(0);", "\t\tvar generator = fn.apply(context, argv);\n\t\tnext(null);", "\t\tfunction next(err, result) {", "\t\t\tvar g, type;", "\t\t\ttry\n\t\t\t{\n\t\t\t\tvar can = err ? false : true;\n\t\t\t\tswitch (can) {\n\t\t\t\t\tcase true:\n\t\t\t\t\t\tg = generator.next(result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase false:\n\t\t\t\t\t\tg = generator.throw(err);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}", "\t\t\t} catch (e) {", "\t\t\t\tif (!complete)\n\t\t\t\t\treturn;", "\t\t\t\ttype = typeof(complete);", "\t\t\t\tif (type === 'object' && complete.isController) {\n\t\t\t\t\tif (e instanceof ErrorBuilder)\n\t\t\t\t\t\tcomplete.content(e);\n\t\t\t\t\telse\n\t\t\t\t\t\tcomplete.view500(e);\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\ttype === 'function' && setImmediate(() => complete(e));\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tif (g.done) {\n\t\t\t\ttypeof(complete) === 'function' && complete(null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\tvar promise = g.value instanceof Promise;", "\t\t\tif (typeof(g.value) !== 'function' && !promise) {\n\t\t\t\tnext.call(self, null, g.value);\n\t\t\t\treturn;\n\t\t\t}", "\t\t\ttry\n\t\t\t{\n\t\t\t\tif (promise) {\n\t\t\t\t\tg.value.then((value) => next.call(self, null, value));\n\t\t\t\t\treturn;\n\t\t\t\t}", "\t\t\t\tg.value.call(self, function() {\n\t\t\t\t\tnext.apply(self, arguments);\n\t\t\t\t});", "\t\t\t} catch (e) {\n\t\t\t\tsetImmediate(() => next.call(self, e));\n\t\t\t}\n\t\t}", "\t\treturn generator.value;\n\t};\n};", "// MIT\n// Written by Jozef Gula\n// Optimized by Peter Sirka\nconst CACHE_GML1 = [null, null, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];\nconst CACHE_GML2 = [null, null, null, null, null, null, null, null];\nexports.getMessageLength = function(data, isLE) {", "\tvar length = data[1] & 0x7f;", "\tif (length === 126) {\n\t\tif (data.length < 4)\n\t\t\treturn -1;\n\t\tCACHE_GML1[0] = data[3];\n\t\tCACHE_GML1[1] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML1, 0, isLE);\n\t}", "\tif (length === 127) {\n\t\tif (data.Length < 10)\n\t\t\treturn -1;\n\t\tCACHE_GML2[0] = data[9];\n\t\tCACHE_GML2[1] = data[8];\n\t\tCACHE_GML2[2] = data[7];\n\t\tCACHE_GML2[3] = data[6];\n\t\tCACHE_GML2[4] = data[5];\n\t\tCACHE_GML2[5] = data[4];\n\t\tCACHE_GML2[6] = data[3];\n\t\tCACHE_GML2[7] = data[2];\n\t\treturn converBytesToInt64(CACHE_GML2, 0, isLE);\n\t}", "\treturn length;\n};", "// MIT\n// Written by Jozef Gula\nfunction converBytesToInt64(data, startIndex, isLE) {\n\treturn isLE ? (data[startIndex] | (data[startIndex + 1] << 0x08) | (data[startIndex + 2] << 0x10) | (data[startIndex + 3] << 0x18) | (data[startIndex + 4] << 0x20) | (data[startIndex + 5] << 0x28) | (data[startIndex + 6] << 0x30) | (data[startIndex + 7] << 0x38)) : ((data[startIndex + 7] << 0x20) | (data[startIndex + 6] << 0x28) | (data[startIndex + 5] << 0x30) | (data[startIndex + 4] << 0x38) | (data[startIndex + 3]) | (data[startIndex + 2] << 0x08) | (data[startIndex + 1] << 0x10) | (data[startIndex] << 0x18));\n}", "exports.queuecache = {};", "function queue_next(name) {", "\tvar item = exports.queuecache[name];\n\tif (!item)\n\t\treturn;", "\titem.running--;", "\tif (item.running < 0)\n\t\titem.running = 0;", "\tif (item.pending.length) {\n\t\tvar fn = item.pending.shift();\n\t\tif (fn) {\n\t\t\titem.running++;\n\t\t\tsetImmediate(queue_next_callback, fn, name);\n\t\t} else\n\t\t\titem.running = 0;\n\t}\n}", "function queue_next_callback(fn, name) {\n\tfn(() => queue_next(name));\n}", "exports.json2replacer = function(key, value) {\n\tif (value != null)\n\t\treturn value;\n};", "/**\n * Queue list\n * @param {String} name\n * @param {Number} max Maximum stack.\n * @param {Function(next)} fn\n */\nexports.queue = function(name, max, fn) {", "\tif (!fn)\n\t\treturn false;", "\tif (!max) {\n\t\tfn(NOOP);\n\t\treturn true;\n\t}", "\tif (!exports.queuecache[name])\n\t\texports.queuecache[name] = { limit: max, running: 0, pending: [] };", "\tvar item = exports.queuecache[name];\n\tif (item.running >= item.limit) {\n\t\titem.pending.push(fn);\n\t\treturn false;\n\t}", "\titem.running++;\n\tsetImmediate(queue_next_callback, fn, name);\n\treturn true;\n};", "exports.minify_css = function(val) {\n\treturn Internal.compile_css(val);\n};", "exports.minify_js = function(val) {\n\treturn Internal.compile_javascript(val);\n};", "exports.minify_html = function(val) {\n\treturn Internal.compile_html(val);\n};", "exports.parseTheme = function(value) {\n\tif (value[0] !== '=')\n\t\treturn '';\n\tvar index = value.indexOf('/', 2);\n\tif (index === -1)\n\t\treturn '';\n\tvalue = value.substring(1, index);\n\treturn value === '?' ? CONF.default_theme : value;\n};", "", "\n// =============================================\n// SHELL SORT IMPLEMENTATION OF ALGORITHM\n// =============================================", "function _shellInsertionSort(list, length, gapSize, fn) {\n\tvar temp, i, j;\n\tfor (i = gapSize; i < length; i += gapSize ) {\n\t\tj = i;\n\t\twhile(j > 0 && fn(list[j - gapSize], list[j]) === 1) {\n\t\t\ttemp = list[j];\n\t\t\tlist[j] = list[j - gapSize];\n\t\t\tlist[j - gapSize] = temp;\n\t\t\tj -= gapSize;\n\t\t}\n\t}\n}", "function shellsort(arr, fn) {\n\tvar length = arr.length;\n\tvar gapSize = Math.floor(length / 2);\n\twhile(gapSize) {\n\t\t_shellInsertionSort(arr, length, gapSize, fn);\n\t\tgapSize = Math.floor(gapSize / 2);\n\t}\n\treturn arr;\n}", "function EventEmitter2(obj) {\n\tif (obj) {\n\t\t!obj.emit && EventEmitter2.extend(obj);\n\t\treturn obj;\n\t} else\n\t\tthis.$events = {};\n}", "const EE2P = EventEmitter2.prototype;", "EE2P.emit = function(name, a, b, c, d, e, f, g) {", "\tif (!this.$events)\n\t\treturn this;", "\tvar evt = this.$events[name];\n\tif (evt) {\n\t\tvar clean = false;\n\t\tfor (var i = 0, length = evt.length; i < length; i++) {\n\t\t\tif (evt[i].$once)\n\t\t\t\tclean = true;\n\t\t\tevt[i].call(this, a, b, c, d, e, f, g);\n\t\t}\n\t\tif (clean) {\n\t\t\tevt = evt.remove(n => n.$once);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.on = function(name, fn) {\n\tif (!this.$events)\n\t\tthis.$events = {};\n\tif (this.$events[name])\n\t\tthis.$events[name].push(fn);\n\telse\n\t\tthis.$events[name] = [fn];\n\treturn this;\n};", "EE2P.once = function(name, fn) {\n\tfn.$once = true;\n\treturn this.on(name, fn);\n};", "EE2P.removeListener = function(name, fn) {\n\tif (this.$events) {\n\t\tvar evt = this.$events[name];\n\t\tif (evt) {\n\t\t\tevt = evt.remove(n => n === fn);\n\t\t\tif (evt.length)\n\t\t\t\tthis.$events[name] = evt;\n\t\t\telse\n\t\t\t\tthis.$events[name] = undefined;\n\t\t}\n\t}\n\treturn this;\n};", "EE2P.removeAllListeners = function(name) {\n\tif (this.$events) {\n\t\tif (name === true)\n\t\t\tthis.$events = EMPTYOBJECT;\n\t\telse if (name)\n\t\t\tthis.$events[name] = undefined;\n\t\telse\n\t\t\tthis.$events = {};\n\t}\n\treturn this;\n};", "EventEmitter2.extend = function(obj) {\n\tobj.emit = EE2P.emit;\n\tobj.on = EE2P.on;\n\tobj.once = EE2P.once;\n\tobj.removeListener = EE2P.removeListener;\n\tobj.removeAllListeners = EE2P.removeAllListeners;\n};", "exports.EventEmitter2 = EventEmitter2;", "function Chunker(name, max) {\n\tthis.name = name;\n\tthis.max = max || 50;\n\tthis.index = 0;\n\tthis.filename = '{0}-'.format(name);\n\tthis.stack = [];\n\tthis.flushing = 0;\n\tthis.pages = 0;\n\tthis.count = 0;\n\tthis.percentage = 0;\n\tthis.autoremove = true;\n\tthis.compress = true;\n\tthis.filename = PATH.temp(this.filename);\n}", "const CHP = Chunker.prototype;", "CHP.append = CHP.write = function(obj) {\n\tvar self = this;", "\tself.stack.push(obj);", "\tvar tmp = self.stack.length;", "\tif (tmp >= self.max) {", "\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.end = function() {\n\tvar self = this;\n\tvar tmp = self.stack.length;\n\tif (tmp) {\n\t\tself.flushing++;\n\t\tself.pages++;\n\t\tself.count += tmp;", "\t\tvar index = (self.index++);", "\t\tif (self.compress) {\n\t\t\tZlib.deflate(Buffer.from(JSON.stringify(self.stack), ENCODING), function(err, buffer) {\n\t\t\t\tFs.writeFile(self.filename + index + '.chunker', buffer, () => self.flushing--);\n\t\t\t});\n\t\t} else\n\t\t\tFs.writeFile(self.filename + index + '.chunker', JSON.stringify(self.stack), () => self.flushing--);", "\t\tself.stack = [];\n\t}", "\treturn self;\n};", "CHP.each = function(onItem, onEnd, indexer) {", "\tvar self = this;", "\tif (indexer == null) {\n\t\tself.percentage = 0;\n\t\tindexer = 0;\n\t}", "\tif (indexer >= self.index)\n\t\treturn onEnd && onEnd();", "\tself.read(indexer++, function(err, items) {\n\t\tself.percentage = Math.ceil((indexer / self.pages) * 100);\n\t\tonItem(items, () => self.each(onItem, onEnd, indexer), indexer - 1);\n\t});", "\treturn self;\n};", "CHP.read = function(index, callback) {\n\tvar self = this;", "\tif (self.flushing) {\n\t\tself.flushing_timeout = setTimeout(() => self.read(index, callback), 300);\n\t\treturn;\n\t}", "\tvar filename = self.filename + index + '.chunker';", "\tFs.readFile(filename, function(err, data) {", "\t\tif (err) {\n\t\t\tcallback(null, EMPTYARRAY);\n\t\t\treturn;\n\t\t}", "\t\tif (self.compress) {\n\t\t\tZlib.inflate(data, function(err, data) {\n\t\t\t\tif (err) {\n\t\t\t\t\tcallback(null, EMPTYARRAY);\n\t\t\t\t} else {\n\t\t\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tself.autoremove && Fs.unlink(filename, NOOP);\n\t\t\tcallback(null, data.toString('utf8').parseJSON(true));\n\t\t}\n\t});", "\treturn self;\n};", "CHP.clear = function() {\n\tvar files = [];\n\tfor (var i = 0; i < this.index; i++)\n\t\tfiles.push(this.filename + i + '.chunker');\n\tfiles.wait((filename, next) => Fs.unlink(filename, next));\n\treturn this;\n};", "CHP.destroy = function() {\n\tthis.clear();\n\tthis.indexer = 0;\n\tthis.flushing = 0;\n\tclearTimeout(this.flushing_timeout);\n\tthis.stack = null;\n\treturn this;\n};", "exports.chunker = function(name, max) {\n\treturn new Chunker(name, max);\n};", "exports.Chunker = Chunker;", "exports.ObjectToArray = function(obj) {\n\tif (obj == null)\n\t\treturn EMPTYARRAY;\n\tvar output = [];\n\tfor (var key in obj)\n\t\toutput.push({ key: key, value: obj[key]});\n\treturn output;\n};", "exports.createBufferSize = (size) => Buffer.alloc(size || 0);\nexports.createBuffer = (val, type) => Buffer.from(val || '', type);", "function Callback(count, callback) {\n\tthis.pending = count;\n\tthis.$callback = callback;\n}\nconst CP = Callback.prototype;", "CP.done = function(callback) {\n\tthis.$callback = callback;\n\treturn this;\n};", "CP.next = function() {\n\tvar self = this;\n\tself.pending--;\n\tif (!self.pending && self.$callback) {\n\t\tself.$callback();\n\t\tself.$callback = null;\n\t}\n\treturn self;\n};", "global.Callback = Callback;", "exports.Callback = function(count, callback) {\n\treturn new Callback(count, callback);\n};", "function Reader() {\n\tvar t = this;\n\t// t.tmp;\n\tt.$add = function(builder) {\n\t\tvar b = require('./textdb-builder').make();\n\t\tbuilder.options.filter = builder.options.filter && builder.options.filter.length ? builder.options.filter.join('&&') : 'true';\n\t\tb.assign(builder.options);", "\t\tif (builder.$)\n\t\t\tb.$resolve = builder.$resolve;\n\t\telse\n\t\t\tb.$callback = builder.$callback;", "\t\tif (t.reader)\n\t\t\tt.reader.add(b);\n\t\telse {\n\t\t\tt.reader = require('./textdb-reader').make();\n\t\t\tt.reader.add(b);\n\t\t\tt.reader.prepare();\n\t\t}\n\t};", "\tt.push = function(data) {\n\t\tif (t.reader) {\n\t\t\tif (data)\n\t\t\t\tt.reader.compare(data instanceof Array ? data : [data]);\n\t\t\telse\n\t\t\t\tt.reader.done();\n\t\t} else\n\t\t\tsetImmediate(t.push, data);\n\t};", "}", "const RP = Reader.prototype;", "RP.done = function() {\n\tvar self = this;\n\tself.reader.done();\n\treturn self;\n};", "RP.reset = function() {\n\tvar self = this;\n\tself.reader.reset();\n\treturn self;\n};", "RP.find = function() {\n\tvar self = this;\n\tvar builder = require('./textdb-wrapper').makebuilder();\n\tbuilder.command = 'find';\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "function listing(builder, items, response) {\n\tvar skip = builder.options.skip || 0;\n\tvar take = builder.options.take || 0;\n\treturn { page: skip && take ? ((skip / take) + 1) : 1, pages: response.count && take ? Math.ceil(response.count / take) : response.count ? 1 : 0, limit: take, count: response.count, items: items || [] };\n}", "RP.list = function() {\n\tvar self = this;\n\tvar builder = require('./textdb-wrapper').makebuilder();\n\tbuilder.command = 'find';\n\tbuilder.parent = {};\n\tbuilder.$callback = function(err, response, meta) {\n\t\tif (builder.parent.$) {\n\t\t\tif (err)\n\t\t\t\tbuilder.parent.$.invalid(err);\n\t\t\telse\n\t\t\t\tbuilder.parent.$resolve(response);\n\t\t} else if (builder.parent.$callback)\n\t\t\tbuilder.parent.$callback(err, listing(builder, response, meta), meta);\n\t};\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "RP.read = function() {\n\tvar self = this;\n\tvar builder = require('./textdb-wrapper').makebuilder();\n\tbuilder.command = 'find';\n\tbuilder.options.take = 1;\n\tbuilder.options.first = 1;\n\tsetImmediate(self.$add, builder);\n\treturn builder;\n};", "RP.count = function() {\n\tvar builder = this.find();\n\tbuilder.options.scalar = 'arg.count++';\n\tbuilder.options.scalararg = { count: 0 };\n\treturn builder;\n};", "RP.scalar = function(type, key, key2) {\n\tvar builder = this.find();", "\tif (key == null) {\n\t\tkey = type;\n\t\ttype = '*';\n\t}", "\tswitch (type) {\n\t\tcase 'group':\n\t\t\tbuilder.options.scalar = key2 ? 'if (doc.{0}!=null){tmp.val=doc.{0};arg[tmp.val]=(arg[tmp.val]||0)+(doc.{1}||0)}'.format(key, key2) : 'if (doc.{0}!=null){tmp.val=doc.{0};arg[tmp.val]=(arg[tmp.val]||0)+1}'.format(key);\n\t\t\tbuilder.options.scalararg = {};\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t// min, max, sum, count\n\t\t\tif (key2) {\n\t\t\t\tbuilder.options.scalar = 'var k=doc.' + key + '+\\'\\';if (arg[k]){tmp.bk=doc.' + key2 + '||0;' + (type === 'max' ? 'if(tmp.bk>arg[k])arg[k]=tmp.bk' : type === 'min' ? 'if(tmp.bk<arg[k])arg[k]=tmp.bk' : 'arg[k]+=tmp.bk') + '}else{arg[k]=doc.' + key2 + '||0}';\n\t\t\t} else {\n\t\t\t\tbuilder.options.scalar = 'if (doc.{0}!=null){tmp.val=doc.{0};arg.count+=1;arg.min=arg.min==null?tmp.val:arg.min>tmp.val?tmp.val:arg.min;arg.max=arg.max==null?tmp.val:arg.max<tmp.val?tmp.val:arg.max;if(!(tmp.val instanceof Date))arg.sum+=tmp.val}'.format(key);\n\t\t\t\tbuilder.options.scalararg = { count: 0, sum: 0 };\n\t\t\t}\n\t\t\tbreak;\n\t}\n\treturn builder;\n};", "RP.stats = function(groupfield, datefield, key, type) {\n\tvar builder = this.find();\n\tbuilder.options.scalar = 'if (doc.{0}!=null&&doc.{2}!=null&&doc.{1} instanceof Date){tmp.val=doc.{2};tmp.group=doc.{0};tmp.date=doc.{1}.format(\\'{3}\\');if(!arg[tmp.group])arg[tmp.group]={};if(!arg[tmp.group][tmp.date])arg[tmp.group][tmp.date]={min:null,max:null,count:0};tmp.cur=arg[tmp.group][tmp.date];tmp.cur.count++;if(tmp.cur.max==null){tmp.cur.max=tmp.val}else if(tmp.cur.max<tmp.val){tmp.cur.max=tmp.val}if(tmp.cur.min==null){tmp.cur.min=tmp.val}else if(tmp.cur.min>tmp.val){tmp.cur.min=tmp.val}}'.format(groupfield, datefield, key, type === 'hourly' ? 'yyyyMMddHH' : type === 'monthly' ? 'yyyyMM' : type === 'yearly' ? 'yyyy' : 'yyyyMMdd');\n\tbuilder.options.scalararg = {};\n\treturn builder;\n};", "exports.reader = function(items) {\n\tvar instance = new Reader();\n\tif (items) {\n\t\tinstance.push(items);\n\t\tinstance.push(null);\n\t}\n\treturn instance;\n};", "global.WAIT = function(fnValid, fnCallback, timeout, interval) {", "\tif (fnValid() === true)\n\t\treturn fnCallback(null, true);", "\tvar id_timeout = null;\n\tvar id_interval = setInterval(function() {", "\t\tif (fnValid() === true) {\n\t\t\tclearInterval(id_interval);\n\t\t\tclearTimeout(id_timeout);\n\t\t\tfnCallback && fnCallback(null, true);\n\t\t}", "\t}, interval || 500);", "\tid_timeout = setTimeout(function() {\n\t\tclearInterval(id_interval);\n\t\tfnCallback && fnCallback(new Error('Timeout.'), false);\n\t}, timeout || 5000);\n};", "// Author: Peter Širka\n// License: MIT\nfunction MultipartParser(multipart, stream, callback) {", "\tif (UPLOADINDEXER > 9999999999)\n\t\tUPLOADINDEXER = 1;", "\tvar self = this;", "\tself.buffer = null;\n\tself.header = Buffer.from(multipart, 'ascii');\n\tself.length = self.header.length;\n\tself.tmp = PATH.temp((F.clusterid || '') + 'upload_');", "\t// 0: nothing\n\t// 1: head\n\t// 2: data\n\t// 3: file\n\tself.step = 0;", "\t// Meta data\n\tself.sizes = { total: 0, files: 0, data: 0, parts: 0 };\n\tself.limits = { total: 0, files: 0, data: 0, parts: 0 };\n\tself.current = {};\n\tself.body = {};\n\tself.files = [];\n\tself.size = 0;", "\tself.ondata = function(chunk) {\n\t\tself.size += chunk.length;\n\t\tif (self.buffer) {\n\t\t\tCONCAT[0] = self.buffer;\n\t\t\tCONCAT[1] = chunk;\n\t\t\tself.buffer = Buffer.concat(CONCAT);\n\t\t\tself.parse(1);\n\t\t} else {\n\t\t\tself.buffer = chunk;\n\t\t\tself.parse(0);\n\t\t}\n\t};", "\tself.onend = function() {\n\t\tself.isend = true;\n\t\tself.checkready();\n\t};", "\tself.onclose = () => self.free('3: Request closed');\n\tself.callback = callback;\n\tself.stream = stream;\n\tself.stream.on('data', self.ondata);\n\tself.stream.on('end', self.onend);\n\t// self.stream.on('close', self.onclose);\n\tself.stream.on('abort', self.onclose);\n}", "MultipartParser.prototype.free = function(err) {\n\tvar self = this;", "\tif (!self.stream)\n\t\treturn;", "\tself.stream.removeListener('data', self.ondata);\n\tself.stream.removeListener('end', self.onend);\n\t// self.stream.removeListener('close', self.onclose);\n\tself.stream.removeListener('abort', self.onclose);\n\tself.current.stream && self.current.stream.end();\n\tself.stream = null;\n\tself.buffer = null;\n\tself.callback && self.callback(err, self);\n};", "MultipartParser.prototype.parse = function(type) {\n\tvar self = this;\n\tswitch (self.step) {\n\t\tcase 0: // no data, tries to parse meta\n\t\t\tself.parse_meta(type);\n\t\t\tbreak;\n\t\tcase 1: // part found\n\t\t\tself.parse_head();\n\t\t\tbreak;\n\t\tcase 2: // part data\n\t\t\tself.parse_data();\n\t\t\tbreak;\n\t\tcase 3: // part file\n\t\t\tself.parse_file();\n\t\t\tbreak;\n\t}\n};", "MultipartParser.prototype.parse_meta = function(type) {", "\tvar self = this;", "\tvar fromindex = type === 1 ? (self.buffer.length - self.header.length) : 0;\n\tif (fromindex < 0)\n\t\tfromindex = 0;", "\tvar index = type === 2 ? 0 : self.buffer.indexOf(self.header, fromindex);", "\tif (index === -1)\n\t\treturn;", "\t// Is end?\n\tif (self.buffer[index + self.length - 1] === 45) {\n\t\tself.current.stream && self.current.stream.end();\n\t\tself.current.stream = null;\n\t\treturn;\n\t}", "\tself.sizes.parts++;", "\tif (self.limits.parts && self.sizes.parts > self.limits.parts) {\n\t\tself.kill('1: Count of parts is too large');\n\t\treturn;\n\t}", "\tself.buffer = self.buffer.slice(self.length + 2);\n\tself.step = 1;\n\tself.parse();", "};", "MultipartParser.prototype.kill = function(err) {\n\tthis.free(err);\n};", "var multipartfileready = function() {\n\tthis.$mpfile.ready = true;\n\tthis.$mpfile = null;\n\tthis.$mpinstance.checkready();\n\tthis.$mpinstance = null;\n};", "MultipartParser.prototype.checkready = function() {", "\tvar self = this;", "\tif (!self.stream || !self.isend)\n\t\treturn;", "\tfor (var i = 0; i < self.files.length; i++) {\n\t\tif (!self.files[i].ready)\n\t\t\treturn;\n\t}", "\tself.free();\n};", "MultipartParser.prototype.parse_head = function() {", "\tvar self = this;\n\tvar index = self.buffer.indexOf(HEADEREND);", "\tif (index === -1)\n\t\treturn;", "\tvar header = self.buffer.slice(0, index).toString('utf8').trim();\n\tif (header.substring(0, HEADERCHECK.length).toLowerCase() !== HEADERCHECK) {\n\t\tself.kill('7:');\n\t\treturn;\n\t}", "\theader = header.substring(HEADERCHECK.length).trim();", "\tvar beg = header.indexOf('filename=\"');\n\tvar isfile = beg !== -1;", "\tself.current.filename = isfile ? header.substring(beg + 10, header.indexOf('\"', beg + 10)).trim() : null;", "\tif (isfile && !self.current.filename)\n\t\treturn;", "\tbeg = header.indexOf('name=\"');\n\tif (beg === -1) {\n\t\tself.kill('2: Invalid part header');\n\t\treturn;\n\t}", "\tself.current.name = header.substring(beg + 6, header.indexOf('\"', beg + 6));\n\tself.current.size = 0;", "\tif (isfile) {", "\t\tif (REG_EMPTYBUFFER_TEST.test(self.current.filename))\n\t\t\tself.current.filename = self.current.filename.replace(REG_EMPTYBUFFER, '');", "\t\tvar type = header.match(/content-type:\\s.*?((\\r\\n)|$)/i);\n\t\tif (type) {\n\t\t\tself.current.type = type[0].substring(14);\n\t\t\tself.current.width = 0;\n\t\t\tself.current.height = 0;\n\t\t\tswitch (self.current.type) {\n\t\t\t\tcase 'image/svg+xml':\n\t\t\t\tcase 'image/svg':\n\t\t\t\t\tself.current.measure = 'measureSVG';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/jpeg':\n\t\t\t\tcase 'image/jpg':\n\t\t\t\t\tself.current.measure = 'measureJPG';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/png':\n\t\t\t\t\tself.current.measure = 'measurePNG';\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'image/gif':\n\t\t\t\t\tself.current.measure = 'measureGIF';\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tself.current.measure = null;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}", "\t\tif (self.current.stream) {\n\t\t\tself.current.stream.end();\n\t\t\tself.current.stream = null;\n\t\t}", "\t\tif (!type) {\n\t\t\tself.kill('2: Invalid part header');\n\t\t\treturn;\n\t\t}", "\t\tself.current.path = self.tmp + (UPLOADINDEXER++) + '.bin';\n\t\tself.current.stream = Fs.createWriteStream(self.current.path);\n\t\tvar file = { path: self.current.path, name: self.current.name, filename: self.current.filename, size: 0, type: self.current.type, width: 0, height: 0 };\n\t\tself.current.file = file;\n\t\tself.current.stream.$mpfile = file;\n\t\tself.current.stream.$mpinstance = self;\n\t\tself.current.stream.on('close', multipartfileready);\n\t} else\n\t\tself.current.file = null;", "\tself.buffer = self.buffer.slice(index + HEADEREND.length);\n\tself.step = isfile ? 3 : 2;\n\tself.current.size = 0;\n\tself.parse();\n};", "MultipartParser.prototype.parse_file = function() {", "\tvar self = this;\n\tvar index = self.buffer.indexOf(self.header);\n\tvar tmp;", "\tif (self.current.measure) {\n\t\ttmp = framework_image[self.current.measure](self.buffer);\n\t\tif (tmp) {\n\t\t\tself.current.file.width = tmp.width;\n\t\t\tself.current.file.height = tmp.height;\n\t\t}\n\t\tself.current.measure = null;\n\t}", "\tif (index !== -1) {", "\t\tself.current.size += index - 4;\n\t\tself.current.file.size += index - 4;\n\t\tself.sizes.total += index - 4;\n\t\tself.sizes.files += index - 4;", "\t\tif (self.limits.files && self.sizes.files > self.limits.files) {\n\t\t\tself.kill('4: File body is too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && self.sizes.total > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t\tvar data = self.buffer.slice(0, index - 4);\n\t\tself.current.stream.end(data);\n\t\tself.current.stream = null;\n\t\tself.files.push(self.current.file);\n\t\tself.buffer = self.buffer.slice(index);\n\t\tself.current.file = null;\n\t\tself.step = 0;\n\t\tself.parse(2);", "\t} else {", "\t\tvar length = self.buffer.length;", "\t\tself.current.size += length;\n\t\tself.current.file.size += length;\n\t\tself.sizes.total += length;\n\t\tself.sizes.files += length;", "\t\tif (self.limits.files && self.sizes.files > self.limits.files) {\n\t\t\tself.kill('4: File body is too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && self.sizes.total > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t\tself.current.stream.write(self.buffer);\n\t\tself.buffer = null;\n\t}\n};", "MultipartParser.prototype.parse_data = function() {\n\tvar self = this;\n\tvar index = self.buffer.indexOf(self.header);", "\tif (index !== -1) {", "\t\tself.sizes.total += index - 2;\n\t\tself.sizes.data += index - 2;", "\t\tif (self.limits.data && self.sizes.data > self.limits.data) {\n\t\t\tself.kill('5: Data are too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && self.sizes.total > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t\tvar val = self.buffer.slice(0, index - 4).toString('utf8');", "\t\tif (REG_EMPTYBUFFER_TEST.test(val))\n\t\t\tval = val.replace(REG_EMPTYBUFFER, '');", "\t\tself.body[self.current.name] = val;\n\t\tself.buffer = self.buffer.slice(index);\n\t\tself.step = 0;\n\t\tself.parse(true);", "\t} else {", "\t\tself.current.size += self.buffer.length;", "\t\tif (self.limits.data && self.current.size > self.limits.data) {\n\t\t\tself.kill('5: Data are too large');\n\t\t\treturn;\n\t\t}", "\t\tif (self.limits.total && (self.sizes.total + self.current.size) > self.limits.total) {\n\t\t\tself.kill('6: Stream is too large');\n\t\t\treturn;\n\t\t}", "\t}\n};", "var measuring = {};", "function showtime(name) {", "\tvar arr = measuring[name];\n\tvar min = null;\n\tvar max = null;\n\tvar sum = 0;", "\tfor (var i = 0; i < arr.length; i++) {", "\t\tvar val = arr[i];", "\t\tif (min == null || min > val)\n\t\t\tmin = val;", "\t\tif (max == null || max < val)\n\t\t\tmax = val;", "\t\tsum += val;\n\t}", "\tconsole.log(name, 'avg:', (sum / arr.length).floor(2), 'max:', max, 'min:', min);\n}", "exports.measure = function(name, timeout) {\n\tvar key = '_' + name;\n\tif (measuring[key]) {\n\t\tvar diff = Date.now() - measuring[key];\n\t\tif (!measuring[name])\n\t\t\tmeasuring[name] = [];\n\t\tmeasuring[name].push(diff);\n\t\tmeasuring[key] = 0;\n\t} else\n\t\tmeasuring[key] = Date.now();\n\tsetTimeout(showtime, timeout || 1000, name);\n};", "exports.multipartparser = function(multipart, stream, callback) {\n\treturn new MultipartParser(multipart, stream, callback);\n};", "var QUERIFYMETHODS = { GET: 1, POST: 1, DELETE: 1, PUT: 1, PATCH: 1, API: 1 };", "global.QUERIFY = function(url, obj) {", "\tif (typeof(url) !== 'string') {\n\t\tobj = url;\n\t\turl = '';\n\t}", "\tif (!obj)\n\t\treturn url;", "\tvar arg = [];\n\tvar keys = Object.keys(obj);", "\tfor (var i = 0; i < keys.length; i++) {", "\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\t\tif (val != null) {", "\t\t\tif (val instanceof Date)\n\t\t\t\tval = val.toISOString();\n\t\t\telse if (val instanceof Array)\n\t\t\t\tval = val.join(',');", "\t\t\tval = val + '';\n\t\t\tval && arg.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));\n\t\t}\n\t}", "\tif (url) {\n\t\tvar arr = url.split(' ');\n\t\tvar index = QUERIFYMETHODS[arr[0]] ? 1 : 0;\n\t\tarr[index] += (arr[index].indexOf('?') === -1 ? '?' : '&') + arg.join('&');\n\t\treturn arr.join(' ');\n\t}", "\treturn '?' + arg.join('&');\n};", "exports.connect = function(opt, callback) {", "\t// opt.secure {Boolean}\n\t// opt.host\n\t// opt.port\n\t// opt.timeout", "\tvar opt = CLONE(opt);\n\tvar tls = opt.tls;\n\tvar meta = {};\n\tvar timeout;", "\tmeta.opt = opt;\n\tmeta.tls = tls;", "\tdelete opt.tls;", "\tvar close = function() {", "\t\tif (meta.socket1) {\n\t\t\tmeta.socket1.removeAllListeners();\n\t\t\tmeta.socket1.end();\n\t\t\tmeta.socket1.destroy();\n\t\t\tmeta.socket1 = null;\n\t\t}", "\t\tif (meta.socket2) {\n\t\t\tmeta.socket2.removeAllListeners();\n\t\t\tmeta.socket2.end();\n\t\t\tmeta.socket2.destroy();\n\t\t\tmeta.socket2 = null;\n\t\t}", "\t};", "\tvar error = function(err) {\n\t\tcallback && callback(err);\n\t\tcallback = null;\n\t\tclose();\n\t};", "\tif (opt.timeout)\n\t\ttimeout = setTimeout(() => error(new Error('Timeout')), opt.timeout);", "\tmeta.destroy = meta.close = close;\n\tmeta.write = function(data) {\n\t\tmeta.socket.write(data);\n\t};", "\tmeta.ondata = function(fn) {\n\t\tmeta.socket.on('data', fn);\n\t};", "\tmeta.onend = function(fn) {\n\t\tmeta.socket.on('destroy', fn);\n\t};", "\tvar done = function() {", "\t\tif (!callback)\n\t\t\treturn;", "\t\tif (opt.tls) {\n\t\t\tif (!meta.socket2) {\n\t\t\t\ttls.socket = meta.socket1;\n\t\t\t\tmeta.socket2 = Tls.connect(tls, done);\n\t\t\t\tmeta.socket2.on('error', error);\n\t\t\t\tmeta.socket2.on('clientError', error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}", "\t\tmeta.socket = meta.socket2 || meta.socket1;\n\t\ttimeout && clearTimeout(timeout);\n\t\ttimeout = null;\n\t\tcallback && callback(null, meta);\n\t\tcallback = null;\n\t};", "\tif (opt.secure)\n\t\tmeta.socket1 = Tls.connect(opt, done);\n\telse\n\t\tmeta.socket1 = Net.createConnection(opt.port, opt.host, done);", "\tmeta.socket1.on('error', error);\n\tmeta.socket1.on('clientError', error);\n};", "String.prototype.toJSONSchema = function(name, url) {", "\tvar obj = {};\n\tvar p = (url || CONF.url || 'https://schemas.totaljs.com/');", "\tif (p[p.length - 1] !== '/')\n\t\tp += '/';", "\tobj.$id = p + (name || (HASH(this) + '')) + '.json';\n\tobj.$schema = 'https://json-schema.org/draft/2020-12/schema';\n\tobj.type = 'object';\n\tobj.properties = {};", "\tvar prop = this.split(',');\n\tvar required = [];", "\tfor (var i = 0; i < prop.length; i++) {", "\t\tvar arr = prop[i].split(':');\n\t\tvar tmp;", "\t\tif (arr[0][0] === '!' || arr[0][0] === '*') {\n\t\t\t// required\n\t\t\tarr[0] = arr[0].substring(1);\n\t\t\trequired.push(arr[0]);\n\t\t}", "\t\tvar type = arr[1].toLowerCase().trim();\n\t\tvar size = 0;\n\t\tvar isarr = type[0] === '[';\n\t\tif (isarr)\n\t\t\ttype = type.substring(1, type.length - 1);", "\t\tvar index = type.indexOf('(');\n\t\tif (index !== -1) {\n\t\t\tsize = +type.substring(index + 1, type.length - 1).trim();\n\t\t\ttype = type.substring(0, index);\n\t\t}", "\t\tswitch (type) {\n\t\t\tcase 'string':\n\t\t\tcase 'uid':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'string' };\n\t\t\t\t\tif (size)\n\t\t\t\t\t\ttmp.items.maxLength = size;\n\t\t\t\t} else {\n\t\t\t\t\ttmp.type = 'string';\n\t\t\t\t\tif (size)\n\t\t\t\t\t\ttmp.maxLength = size;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'number':\n\t\t\tcase 'number2':\n\t\t\tcase 'float':\n\t\t\tcase 'decimal':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'number' };\n\t\t\t\t} else {\n\t\t\t\t\ttmp.type = 'number';\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase 'bool':\n\t\t\tcase 'boolean':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'boolean' };\n\t\t\t\t} else\n\t\t\t\t\ttmp.type = 'boolean';\n\t\t\t\tbreak;\n\t\t\tcase 'date':\n\t\t\t\ttmp = {};\n\t\t\t\tif (isarr) {\n\t\t\t\t\ttmp.type = 'array';\n\t\t\t\t\ttmp.items = { type: 'date' };\n\t\t\t\t} else\n\t\t\t\t\ttmp.type = 'date';\n\t\t\t\tbreak;\n\t\t}\n\t\tif (tmp)\n\t\t\tobj.properties[arr[0].trim()] = tmp;\n\t}", "\tif (required.length)\n\t\tobj.required = required;", "\treturn obj;\n};", "!global.F && require('./index');" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [5, 5563], "buggy_code_start_loc": [5, 5206], "filenames": ["changelog.txt", "utils.js"], "fixing_code_end_loc": [10, 5418], "fixing_code_start_loc": [6, 5205], "message": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:totaljs:total4:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "47233194-DF6F-400D-A2BB-E5B07141E828", "versionEndExcluding": "0.0.43", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "The package total4 before 0.0.43 are vulnerable to Arbitrary Code Execution via the U.set() and U.get() functions."}, {"lang": "es", "value": "El paquete total4 versiones anteriores a 0.0.43, son vulnerables a una ejecuci\u00f3n de c\u00f3digo arbitrario por medio de las funciones U.set() y U.get()"}], "evaluatorComment": null, "id": "CVE-2021-23390", "lastModified": "2021-07-14T17:38:45.477", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "HIGH", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "PARTIAL", "baseScore": 7.5, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "report@snyk.io", "type": "Secondary"}]}, "published": "2021-07-12T16:15:09.030", "references": [{"source": "report@snyk.io", "tags": ["Broken Link"], "url": "https://github.com/totaljs/framework4/blob/master/utils.js%23L5430-L5455"}, {"source": "report@snyk.io", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, {"source": "report@snyk.io", "tags": ["Exploit", "Patch", "Third Party Advisory"], "url": "https://snyk.io/vuln/SNYK-JS-TOTAL4-1130527"}], "sourceIdentifier": "report@snyk.io", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-94"}], "source": "nvd@nist.gov", "type": "Primary"}]}, "github_commit_url": "https://github.com/totaljs/framework4/commit/8a72d8c20f38bbcac031a76a51238aa528f68821"}, "type": "CWE-94"}
39
Determine whether the {function_name} code is vulnerable or not.
[ "import { logger, SlpTransactionDetails, SlpTransactionType } from \"../index\";\nimport { Slp, SlpValidator } from \"./slp\";", "import BigNumber from \"bignumber.js\";\nimport { BITBOX } from \"bitbox-sdk\";\nimport * as Bitcore from \"bitcore-lib-cash\";", "import { Crypto } from \"./crypto\";", "export interface Validation { validity: boolean|null; parents: Parent[]; details: SlpTransactionDetails|null; invalidReason: string|null; waiting: boolean; }\nexport type GetRawTransactionsAsync = (txid: string[]) => Promise<string[]>;", "const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));", "interface Parent {\n txid: string;\n vout: number;\n versionType: number;\n valid: boolean|null;\n inputQty: BigNumber|null;\n}", "export class LocalValidator implements SlpValidator {\n public BITBOX: BITBOX;\n public cachedRawTransactions: { [txid: string]: string };\n public cachedValidations: { [txid: string]: Validation };\n public getRawTransactions: GetRawTransactionsAsync;\n public slp: Slp;\n public logger: logger = { log: (s: string) => null };", " constructor(BITBOX: BITBOX, getRawTransactions: GetRawTransactionsAsync, logger?: logger) {\n if (!BITBOX) {\n throw Error(\"Must provide BITBOX instance to class constructor.\");\n }\n if (!getRawTransactions) {\n throw Error(\"Must provide method getRawTransactions to class constructor.\");\n }\n if (logger) {\n this.logger = logger;\n }\n this.BITBOX = BITBOX;\n this.getRawTransactions = getRawTransactions;\n this.slp = new Slp(BITBOX);\n this.cachedValidations = {};\n this.cachedRawTransactions = {};\n }", " public addValidationFromStore(hex: string, isValid: boolean) {\n const id = Crypto.txid(Buffer.from(hex, \"hex\")).toString(\"hex\");\n if (!this.cachedValidations[id]) {\n this.cachedValidations[id] = { validity: isValid, parents: [], details: null, invalidReason: null, waiting: false };\n }\n if (!this.cachedRawTransactions[id]) {\n this.cachedRawTransactions[id] = hex;\n }\n }", " public async waitForCurrentValidationProcessing(txid: string) {\n const cached: Validation = this.cachedValidations[txid];", " while (true) {\n if (typeof cached.validity === \"boolean\") {\n cached.waiting = false;\n break;\n }\n await sleep(10);\n }\n }", " public async waitForTransactionDownloadToComplete(txid: string){\n while (true) {\n if (this.cachedRawTransactions[txid] && this.cachedRawTransactions[txid] !== \"waiting\") {\n break;\n }\n await sleep(10);\n }\n }", " public async retrieveRawTransaction(txid: string) {\n const checkTxnRegex = (txn: string) => {\n const re = /^([A-Fa-f0-9]{2}){61,}$/;\n if (!re.test(txn)) {\n throw Error(`Regex failed for retrieved transaction, got: ${txn}`);\n }\n };\n if (!this.cachedRawTransactions[txid]) {\n this.cachedRawTransactions[txid] = \"waiting\";\n const txns = await this.getRawTransactions([txid]);\n if (!txns || txns.length === 0 || typeof txns[0] !== \"string\") {\n throw Error(`Response error in getRawTransactions, got: ${txns}`);\n }\n checkTxnRegex(txns[0]);\n this.cachedRawTransactions[txid] = txns[0];\n return txns[0];\n } else {\n checkTxnRegex(this.cachedRawTransactions[txid]);\n return this.cachedRawTransactions[txid];\n }\n }", " public async isValidSlpTxid(txid: string, tokenIdFilter?: string, tokenTypeFilter?: number): Promise<boolean> {\n this.logger.log(\"SLPJS Validating: \" + txid);\n const valid = await this._isValidSlpTxid(txid, tokenIdFilter, tokenTypeFilter);\n this.logger.log(\"SLPJS Result: \" + valid + \" (\" + txid + \")\");\n if (!valid && this.cachedValidations[txid].invalidReason) {\n this.logger.log(\"SLPJS Invalid Reason: \" + this.cachedValidations[txid].invalidReason);\n } else if (!valid) {\n this.logger.log(\"SLPJS Invalid Reason: unknown (result is user supplied)\");\n }\n return valid;\n }", " //\n // This method uses recursion to do a Depth-First-Search with the node result being\n // computed in Postorder Traversal (left/right/root) order. A validation cache\n // is used to keep track of the results for nodes that have already been evaluated.\n //\n // Each call to this method evaluates node validity with respect to\n // its parent node(s), so it walks backwards until the\n // validation cache provides a result or the GENESIS node is evaluated.\n // Root nodes await the validation result of their upstream parent.\n //\n // In the case of NFT1 the search continues to the group/parent NFT DAG after the Genesis\n // of the NFT child is discovered.\n //\n public async _isValidSlpTxid(txid: string, tokenIdFilter?: string, tokenTypeFilter?: number): Promise<boolean> {\n // Check to see if this txn has been processed by looking at shared cache, if doesn't exist then download txn.\n if (!this.cachedValidations[txid]) {\n this.cachedValidations[txid] = {\n validity: null,\n parents: [],\n details: null,\n invalidReason: null,\n waiting: false,\n };\n await this.retrieveRawTransaction(txid);\n }\n // Otherwise, we can use the cached result as long as a special filter isn't being applied.\n else if (typeof this.cachedValidations[txid].validity === \"boolean\") {\n return this.cachedValidations[txid].validity!;\n }", " //\n // Handle the case where neither branch of the previous if/else statement was\n // executed and the raw transaction has never been downloaded.\n //\n // Also handle case where a 2nd request of same txid comes in\n // during the download of a previous request.\n //\n if (!this.cachedRawTransactions[txid] || this.cachedRawTransactions[txid] === \"waiting\") {\n if (this.cachedRawTransactions[txid] !== \"waiting\") {\n this.retrieveRawTransaction(txid);\n }", " // Wait for previously a initiated download to completed\n await this.waitForTransactionDownloadToComplete(txid);\n }", " // Handle case where txid is already in the process of being validated from a previous call\n if (this.cachedValidations[txid].waiting) {\n await this.waitForCurrentValidationProcessing(txid);\n if (typeof this.cachedValidations[txid].validity === \"boolean\") {\n return this.cachedValidations[txid].validity!;\n }\n }", " this.cachedValidations[txid].waiting = true;", " // Check SLP message validity\n const txn: Bitcore.Transaction = new Bitcore.Transaction(this.cachedRawTransactions[txid]);\n let slpmsg: SlpTransactionDetails;\n try {\n slpmsg = this.cachedValidations[txid].details = this.slp.parseSlpOutputScript(txn.outputs[0]._scriptBuffer);\n if (slpmsg.transactionType === SlpTransactionType.GENESIS) {\n slpmsg.tokenIdHex = txid;\n }\n } catch (e) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"SLP OP_RETURN parsing error (\" + e.message + \").\";\n return this.cachedValidations[txid].validity!;\n }", " // Check for tokenId filter\n if (tokenIdFilter && slpmsg.tokenIdHex !== tokenIdFilter) {\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Validator was run with filter only considering tokenId \" + tokenIdFilter + \" as valid.\";\n return false; // Don't save boolean result to cache incase cache is ever used without tokenIdFilter.\n } else {\n if (this.cachedValidations[txid].validity !== false) {\n this.cachedValidations[txid].invalidReason = null;\n }\n }", " // Check specified token type is being respected\n if (tokenTypeFilter && slpmsg.versionType !== tokenTypeFilter) {\n this.cachedValidations[txid].validity = null;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Validator was run with filter only considering token type: \" + tokenTypeFilter + \" as valid.\";\n return false; // Don't save boolean result to cache incase cache is ever used with different token type.\n } else {\n if (this.cachedValidations[txid].validity !== false) {\n this.cachedValidations[txid].invalidReason = null;\n }\n }", " // Check DAG validity\n if (slpmsg.transactionType === SlpTransactionType.GENESIS) {\n // Check for NFT1 child (type 0x41)\n if (slpmsg.versionType === 0x41) {\n // An NFT1 parent should be provided at input index 0,\n // so we check this first before checking the whole parent DAG\n let input_txid = txn.inputs[0].prevTxId.toString(\"hex\");\n let input_txhex = await this.retrieveRawTransaction(input_txid);\n let input_tx: Bitcore.Transaction = new Bitcore.Transaction(input_txhex);\n let input_slpmsg;\n try {\n input_slpmsg = this.slp.parseSlpOutputScript(input_tx.outputs[0]._scriptBuffer);\n } catch (_) { }\n if (!input_slpmsg || input_slpmsg.versionType !== 0x81) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"NFT1 child GENESIS does not have a valid NFT1 parent input.\";\n return this.cachedValidations[txid].validity!;\n }\n // Check that the there is a burned output >0 in the parent txn SLP message\n if (input_slpmsg.transactionType === SlpTransactionType.SEND &&\n (!input_slpmsg.sendOutputs![1].isGreaterThan(0)))\n {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"NFT1 child's parent has SLP output that is not greater than zero.\";\n return this.cachedValidations[txid].validity!;\n } else if ((input_slpmsg.transactionType === SlpTransactionType.GENESIS ||\n input_slpmsg.transactionType === SlpTransactionType.MINT) &&\n !input_slpmsg.genesisOrMintQuantity!.isGreaterThan(0))\n {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"NFT1 child's parent has SLP output that is not greater than zero.\";\n return this.cachedValidations[txid].validity!;\n }\n // Continue to check the NFT1 parent DAG\n let nft_parent_dag_validity = await this.isValidSlpTxid(input_txid, undefined, 0x81);\n this.cachedValidations[txid].validity = nft_parent_dag_validity;\n this.cachedValidations[txid].waiting = false;\n if (!nft_parent_dag_validity) {\n this.cachedValidations[txid].invalidReason = \"NFT1 child GENESIS does not have valid parent DAG.\";\n }\n return this.cachedValidations[txid].validity!;\n }\n // All other supported token types (includes 0x01 and 0x81)\n // No need to check type here since op_return parser throws on other types.\n else {\n this.cachedValidations[txid].validity = true;\n this.cachedValidations[txid].waiting = false;\n return this.cachedValidations[txid].validity!;\n }\n }\n else if (slpmsg.transactionType === SlpTransactionType.MINT) {\n for (let i = 0; i < txn.inputs.length; i++) {\n let input_txid = txn.inputs[i].prevTxId.toString(\"hex\");\n let input_txhex = await this.retrieveRawTransaction(input_txid);\n let input_tx: Bitcore.Transaction = new Bitcore.Transaction(input_txhex);\n try {\n let input_slpmsg = this.slp.parseSlpOutputScript(input_tx.outputs[0]._scriptBuffer);\n if (input_slpmsg.transactionType === SlpTransactionType.GENESIS) {\n input_slpmsg.tokenIdHex = input_txid;\n }\n if (input_slpmsg.tokenIdHex === slpmsg.tokenIdHex) {\n if (input_slpmsg.transactionType === SlpTransactionType.GENESIS || input_slpmsg.transactionType === SlpTransactionType.MINT) {\n if (txn.inputs[i].outputIndex === input_slpmsg.batonVout) {\n this.cachedValidations[txid].parents.push({\n txid: txn.inputs[i].prevTxId.toString(\"hex\"),\n vout: txn.inputs[i].outputIndex!,\n versionType: input_slpmsg.versionType,\n valid: null,\n inputQty: null,\n });\n }\n }\n }\n } catch (_) {}\n }", " if (this.cachedValidations[txid].parents.length !== 1) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"MINT transaction must have 1 valid baton parent.\";", " return this.cachedValidations[txid].validity!;\n }\n }\n else if (slpmsg.transactionType === SlpTransactionType.SEND) {\n const tokenOutQty = slpmsg.sendOutputs!.reduce((t, v) => { return t.plus(v); }, new BigNumber(0));\n let tokenInQty = new BigNumber(0);\n for (let i = 0; i < txn.inputs.length; i++) {\n let input_txid = txn.inputs[i].prevTxId.toString(\"hex\");\n let input_txhex = await this.retrieveRawTransaction(input_txid);\n let input_tx: Bitcore.Transaction = new Bitcore.Transaction(input_txhex);\n try {\n let input_slpmsg = this.slp.parseSlpOutputScript(input_tx.outputs[0]._scriptBuffer);\n if (input_slpmsg.transactionType === SlpTransactionType.GENESIS) {\n input_slpmsg.tokenIdHex = input_txid;\n }\n if (input_slpmsg.tokenIdHex === slpmsg.tokenIdHex) {\n if (input_slpmsg.transactionType === SlpTransactionType.SEND) {\n if (txn.inputs[i].outputIndex! <= input_slpmsg.sendOutputs!.length - 1) {\n tokenInQty = tokenInQty.plus(input_slpmsg.sendOutputs![txn.inputs[i].outputIndex!]);\n this.cachedValidations[txid].parents.push({\n txid: txn.inputs[i].prevTxId.toString(\"hex\"),\n vout: txn.inputs[i].outputIndex!,\n versionType: input_slpmsg.versionType,\n valid: null,\n inputQty: input_slpmsg.sendOutputs![txn.inputs[i].outputIndex!]\n });\n }\n }\n else if (input_slpmsg.transactionType === SlpTransactionType.GENESIS || input_slpmsg.transactionType === SlpTransactionType.MINT) {\n if (txn.inputs[i].outputIndex === 1) {\n tokenInQty = tokenInQty.plus(input_slpmsg.genesisOrMintQuantity!);\n this.cachedValidations[txid].parents.push({\n txid: txn.inputs[i].prevTxId.toString(\"hex\"),\n vout: txn.inputs[i].outputIndex!,\n versionType: input_slpmsg.versionType,\n valid: null,\n inputQty: input_slpmsg.genesisOrMintQuantity\n });\n }\n }\n }\n } catch (_) {}\n }", " // Check token inputs are greater than token outputs (includes valid and invalid inputs)\n if (tokenOutQty.isGreaterThan(tokenInQty)) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Token outputs are greater than possible token inputs.\";\n return this.cachedValidations[txid].validity!;\n }\n }", " // Set validity validation-cache for parents, and handle MINT condition with no valid input\n // we don't need to check proper token id since we only added parents with same ID in above steps.\n const parentTxids = [...new Set(this.cachedValidations[txid].parents.map(p => p.txid))];", " for (let i = 0; i < parentTxids.length; i++) {\n const valid = await this.isValidSlpTxid(parentTxids[i]);\n this.cachedValidations[txid].parents.filter(p => p.txid === parentTxids[i]).map(p => p.valid = valid);\n if (this.cachedValidations[txid].details!.transactionType === SlpTransactionType.MINT && !valid) {", " this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"MINT transaction with invalid baton parent.\";\n return this.cachedValidations[txid].validity!;\n }\n }", " // Check valid inputs are greater than token outputs\n if (this.cachedValidations[txid].details!.transactionType === SlpTransactionType.SEND) {\n const validInputQty = this.cachedValidations[txid].parents.reduce((t, v) => { return v.valid ? t.plus(v.inputQty!) : t; }, new BigNumber(0));\n const tokenOutQty = slpmsg.sendOutputs!.reduce((t, v) => { return t.plus(v); }, new BigNumber(0));\n if (tokenOutQty.isGreaterThan(validInputQty)) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Token outputs are greater than valid token inputs.\";\n return this.cachedValidations[txid].validity!;\n }\n }", " // Check versionType is not different from valid parents\n if (this.cachedValidations[txid].parents.filter(p => p.valid).length > 0) {\n const validVersionType = this.cachedValidations[txid].parents.find(p => p.valid!)!.versionType;\n if (this.cachedValidations[txid].details!.versionType !== validVersionType) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"SLP version/type mismatch from valid parent.\";\n return this.cachedValidations[txid].validity!;\n }\n }\n this.cachedValidations[txid].validity = true;\n this.cachedValidations[txid].waiting = false;\n return this.cachedValidations[txid].validity!;\n }", " public async validateSlpTransactions(txids: string[]): Promise<string[]> {\n const res = [];\n for (let i = 0; i < txids.length; i++) {\n res.push((await this.isValidSlpTxid(txids[i])) ? txids[i] : \"\");\n }\n return res.filter((id: string) => id.length > 0);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [349], "buggy_code_start_loc": [285], "filenames": ["lib/localvalidator.ts"], "fixing_code_end_loc": [353], "fixing_code_start_loc": [285], "message": "SLPJS (npm package slpjs) before version 0.27.2, has a vulnerability where users could experience false-negative validation outcomes for MINT transaction operations. A poorly implemented SLP wallet could allow spending of the affected tokens which would result in the destruction of a user's minting baton. This is fixed in version 0.27.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:simpleledger:slpjs:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "035AB245-62DC-434B-A63F-D1AC45D95DFC", "versionEndExcluding": "0.27.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SLPJS (npm package slpjs) before version 0.27.2, has a vulnerability where users could experience false-negative validation outcomes for MINT transaction operations. A poorly implemented SLP wallet could allow spending of the affected tokens which would result in the destruction of a user's minting baton. This is fixed in version 0.27.2."}, {"lang": "es", "value": "SLPJS (paquete slpjs de npm) versiones anteriores a 0.27.2, presenta una vulnerabilidad donde los usuarios podr\u00edan experimentar resultados de comprobaci\u00f3n falsos negativos para las operaciones de transacci\u00f3n MINT. Una billetera SLP mal implementada podr\u00eda permitir el gasto de los tokens afectados, lo que resultar\u00eda en la destrucci\u00f3n minting baton del usuario. Esto es corrigido en la versi\u00f3n 0.27.2."}], "evaluatorComment": null, "id": "CVE-2020-11071", "lastModified": "2020-05-19T16:18:03.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-12T01:15:11.150", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Tool Signature"], "url": "https://github.com/simpleledger/slpjs/commit/3671be2ffb6d4cfa94c00c6dc8649d1ba1d75754"}, {"source": "security-advisories@github.com", "tags": ["Tool Signature"], "url": "https://github.com/simpleledger/slpjs/security/advisories/GHSA-jc83-cpf9-q7c6"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-697"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-697"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/simpleledger/slpjs/commit/3671be2ffb6d4cfa94c00c6dc8649d1ba1d75754"}, "type": "CWE-697"}
40
Determine whether the {function_name} code is vulnerable or not.
[ "import { logger, SlpTransactionDetails, SlpTransactionType } from \"../index\";\nimport { Slp, SlpValidator } from \"./slp\";", "import BigNumber from \"bignumber.js\";\nimport { BITBOX } from \"bitbox-sdk\";\nimport * as Bitcore from \"bitcore-lib-cash\";", "import { Crypto } from \"./crypto\";", "export interface Validation { validity: boolean|null; parents: Parent[]; details: SlpTransactionDetails|null; invalidReason: string|null; waiting: boolean; }\nexport type GetRawTransactionsAsync = (txid: string[]) => Promise<string[]>;", "const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));", "interface Parent {\n txid: string;\n vout: number;\n versionType: number;\n valid: boolean|null;\n inputQty: BigNumber|null;\n}", "export class LocalValidator implements SlpValidator {\n public BITBOX: BITBOX;\n public cachedRawTransactions: { [txid: string]: string };\n public cachedValidations: { [txid: string]: Validation };\n public getRawTransactions: GetRawTransactionsAsync;\n public slp: Slp;\n public logger: logger = { log: (s: string) => null };", " constructor(BITBOX: BITBOX, getRawTransactions: GetRawTransactionsAsync, logger?: logger) {\n if (!BITBOX) {\n throw Error(\"Must provide BITBOX instance to class constructor.\");\n }\n if (!getRawTransactions) {\n throw Error(\"Must provide method getRawTransactions to class constructor.\");\n }\n if (logger) {\n this.logger = logger;\n }\n this.BITBOX = BITBOX;\n this.getRawTransactions = getRawTransactions;\n this.slp = new Slp(BITBOX);\n this.cachedValidations = {};\n this.cachedRawTransactions = {};\n }", " public addValidationFromStore(hex: string, isValid: boolean) {\n const id = Crypto.txid(Buffer.from(hex, \"hex\")).toString(\"hex\");\n if (!this.cachedValidations[id]) {\n this.cachedValidations[id] = { validity: isValid, parents: [], details: null, invalidReason: null, waiting: false };\n }\n if (!this.cachedRawTransactions[id]) {\n this.cachedRawTransactions[id] = hex;\n }\n }", " public async waitForCurrentValidationProcessing(txid: string) {\n const cached: Validation = this.cachedValidations[txid];", " while (true) {\n if (typeof cached.validity === \"boolean\") {\n cached.waiting = false;\n break;\n }\n await sleep(10);\n }\n }", " public async waitForTransactionDownloadToComplete(txid: string){\n while (true) {\n if (this.cachedRawTransactions[txid] && this.cachedRawTransactions[txid] !== \"waiting\") {\n break;\n }\n await sleep(10);\n }\n }", " public async retrieveRawTransaction(txid: string) {\n const checkTxnRegex = (txn: string) => {\n const re = /^([A-Fa-f0-9]{2}){61,}$/;\n if (!re.test(txn)) {\n throw Error(`Regex failed for retrieved transaction, got: ${txn}`);\n }\n };\n if (!this.cachedRawTransactions[txid]) {\n this.cachedRawTransactions[txid] = \"waiting\";\n const txns = await this.getRawTransactions([txid]);\n if (!txns || txns.length === 0 || typeof txns[0] !== \"string\") {\n throw Error(`Response error in getRawTransactions, got: ${txns}`);\n }\n checkTxnRegex(txns[0]);\n this.cachedRawTransactions[txid] = txns[0];\n return txns[0];\n } else {\n checkTxnRegex(this.cachedRawTransactions[txid]);\n return this.cachedRawTransactions[txid];\n }\n }", " public async isValidSlpTxid(txid: string, tokenIdFilter?: string, tokenTypeFilter?: number): Promise<boolean> {\n this.logger.log(\"SLPJS Validating: \" + txid);\n const valid = await this._isValidSlpTxid(txid, tokenIdFilter, tokenTypeFilter);\n this.logger.log(\"SLPJS Result: \" + valid + \" (\" + txid + \")\");\n if (!valid && this.cachedValidations[txid].invalidReason) {\n this.logger.log(\"SLPJS Invalid Reason: \" + this.cachedValidations[txid].invalidReason);\n } else if (!valid) {\n this.logger.log(\"SLPJS Invalid Reason: unknown (result is user supplied)\");\n }\n return valid;\n }", " //\n // This method uses recursion to do a Depth-First-Search with the node result being\n // computed in Postorder Traversal (left/right/root) order. A validation cache\n // is used to keep track of the results for nodes that have already been evaluated.\n //\n // Each call to this method evaluates node validity with respect to\n // its parent node(s), so it walks backwards until the\n // validation cache provides a result or the GENESIS node is evaluated.\n // Root nodes await the validation result of their upstream parent.\n //\n // In the case of NFT1 the search continues to the group/parent NFT DAG after the Genesis\n // of the NFT child is discovered.\n //\n public async _isValidSlpTxid(txid: string, tokenIdFilter?: string, tokenTypeFilter?: number): Promise<boolean> {\n // Check to see if this txn has been processed by looking at shared cache, if doesn't exist then download txn.\n if (!this.cachedValidations[txid]) {\n this.cachedValidations[txid] = {\n validity: null,\n parents: [],\n details: null,\n invalidReason: null,\n waiting: false,\n };\n await this.retrieveRawTransaction(txid);\n }\n // Otherwise, we can use the cached result as long as a special filter isn't being applied.\n else if (typeof this.cachedValidations[txid].validity === \"boolean\") {\n return this.cachedValidations[txid].validity!;\n }", " //\n // Handle the case where neither branch of the previous if/else statement was\n // executed and the raw transaction has never been downloaded.\n //\n // Also handle case where a 2nd request of same txid comes in\n // during the download of a previous request.\n //\n if (!this.cachedRawTransactions[txid] || this.cachedRawTransactions[txid] === \"waiting\") {\n if (this.cachedRawTransactions[txid] !== \"waiting\") {\n this.retrieveRawTransaction(txid);\n }", " // Wait for previously a initiated download to completed\n await this.waitForTransactionDownloadToComplete(txid);\n }", " // Handle case where txid is already in the process of being validated from a previous call\n if (this.cachedValidations[txid].waiting) {\n await this.waitForCurrentValidationProcessing(txid);\n if (typeof this.cachedValidations[txid].validity === \"boolean\") {\n return this.cachedValidations[txid].validity!;\n }\n }", " this.cachedValidations[txid].waiting = true;", " // Check SLP message validity\n const txn: Bitcore.Transaction = new Bitcore.Transaction(this.cachedRawTransactions[txid]);\n let slpmsg: SlpTransactionDetails;\n try {\n slpmsg = this.cachedValidations[txid].details = this.slp.parseSlpOutputScript(txn.outputs[0]._scriptBuffer);\n if (slpmsg.transactionType === SlpTransactionType.GENESIS) {\n slpmsg.tokenIdHex = txid;\n }\n } catch (e) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"SLP OP_RETURN parsing error (\" + e.message + \").\";\n return this.cachedValidations[txid].validity!;\n }", " // Check for tokenId filter\n if (tokenIdFilter && slpmsg.tokenIdHex !== tokenIdFilter) {\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Validator was run with filter only considering tokenId \" + tokenIdFilter + \" as valid.\";\n return false; // Don't save boolean result to cache incase cache is ever used without tokenIdFilter.\n } else {\n if (this.cachedValidations[txid].validity !== false) {\n this.cachedValidations[txid].invalidReason = null;\n }\n }", " // Check specified token type is being respected\n if (tokenTypeFilter && slpmsg.versionType !== tokenTypeFilter) {\n this.cachedValidations[txid].validity = null;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Validator was run with filter only considering token type: \" + tokenTypeFilter + \" as valid.\";\n return false; // Don't save boolean result to cache incase cache is ever used with different token type.\n } else {\n if (this.cachedValidations[txid].validity !== false) {\n this.cachedValidations[txid].invalidReason = null;\n }\n }", " // Check DAG validity\n if (slpmsg.transactionType === SlpTransactionType.GENESIS) {\n // Check for NFT1 child (type 0x41)\n if (slpmsg.versionType === 0x41) {\n // An NFT1 parent should be provided at input index 0,\n // so we check this first before checking the whole parent DAG\n let input_txid = txn.inputs[0].prevTxId.toString(\"hex\");\n let input_txhex = await this.retrieveRawTransaction(input_txid);\n let input_tx: Bitcore.Transaction = new Bitcore.Transaction(input_txhex);\n let input_slpmsg;\n try {\n input_slpmsg = this.slp.parseSlpOutputScript(input_tx.outputs[0]._scriptBuffer);\n } catch (_) { }\n if (!input_slpmsg || input_slpmsg.versionType !== 0x81) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"NFT1 child GENESIS does not have a valid NFT1 parent input.\";\n return this.cachedValidations[txid].validity!;\n }\n // Check that the there is a burned output >0 in the parent txn SLP message\n if (input_slpmsg.transactionType === SlpTransactionType.SEND &&\n (!input_slpmsg.sendOutputs![1].isGreaterThan(0)))\n {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"NFT1 child's parent has SLP output that is not greater than zero.\";\n return this.cachedValidations[txid].validity!;\n } else if ((input_slpmsg.transactionType === SlpTransactionType.GENESIS ||\n input_slpmsg.transactionType === SlpTransactionType.MINT) &&\n !input_slpmsg.genesisOrMintQuantity!.isGreaterThan(0))\n {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"NFT1 child's parent has SLP output that is not greater than zero.\";\n return this.cachedValidations[txid].validity!;\n }\n // Continue to check the NFT1 parent DAG\n let nft_parent_dag_validity = await this.isValidSlpTxid(input_txid, undefined, 0x81);\n this.cachedValidations[txid].validity = nft_parent_dag_validity;\n this.cachedValidations[txid].waiting = false;\n if (!nft_parent_dag_validity) {\n this.cachedValidations[txid].invalidReason = \"NFT1 child GENESIS does not have valid parent DAG.\";\n }\n return this.cachedValidations[txid].validity!;\n }\n // All other supported token types (includes 0x01 and 0x81)\n // No need to check type here since op_return parser throws on other types.\n else {\n this.cachedValidations[txid].validity = true;\n this.cachedValidations[txid].waiting = false;\n return this.cachedValidations[txid].validity!;\n }\n }\n else if (slpmsg.transactionType === SlpTransactionType.MINT) {\n for (let i = 0; i < txn.inputs.length; i++) {\n let input_txid = txn.inputs[i].prevTxId.toString(\"hex\");\n let input_txhex = await this.retrieveRawTransaction(input_txid);\n let input_tx: Bitcore.Transaction = new Bitcore.Transaction(input_txhex);\n try {\n let input_slpmsg = this.slp.parseSlpOutputScript(input_tx.outputs[0]._scriptBuffer);\n if (input_slpmsg.transactionType === SlpTransactionType.GENESIS) {\n input_slpmsg.tokenIdHex = input_txid;\n }\n if (input_slpmsg.tokenIdHex === slpmsg.tokenIdHex) {\n if (input_slpmsg.transactionType === SlpTransactionType.GENESIS || input_slpmsg.transactionType === SlpTransactionType.MINT) {\n if (txn.inputs[i].outputIndex === input_slpmsg.batonVout) {\n this.cachedValidations[txid].parents.push({\n txid: txn.inputs[i].prevTxId.toString(\"hex\"),\n vout: txn.inputs[i].outputIndex!,\n versionType: input_slpmsg.versionType,\n valid: null,\n inputQty: null,\n });\n }\n }\n }\n } catch (_) {}\n }", " if (this.cachedValidations[txid].parents.length < 1) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"MINT transaction must have at least 1 candidate baton parent input.\";", " return this.cachedValidations[txid].validity!;\n }\n }\n else if (slpmsg.transactionType === SlpTransactionType.SEND) {\n const tokenOutQty = slpmsg.sendOutputs!.reduce((t, v) => { return t.plus(v); }, new BigNumber(0));\n let tokenInQty = new BigNumber(0);\n for (let i = 0; i < txn.inputs.length; i++) {\n let input_txid = txn.inputs[i].prevTxId.toString(\"hex\");\n let input_txhex = await this.retrieveRawTransaction(input_txid);\n let input_tx: Bitcore.Transaction = new Bitcore.Transaction(input_txhex);\n try {\n let input_slpmsg = this.slp.parseSlpOutputScript(input_tx.outputs[0]._scriptBuffer);\n if (input_slpmsg.transactionType === SlpTransactionType.GENESIS) {\n input_slpmsg.tokenIdHex = input_txid;\n }\n if (input_slpmsg.tokenIdHex === slpmsg.tokenIdHex) {\n if (input_slpmsg.transactionType === SlpTransactionType.SEND) {\n if (txn.inputs[i].outputIndex! <= input_slpmsg.sendOutputs!.length - 1) {\n tokenInQty = tokenInQty.plus(input_slpmsg.sendOutputs![txn.inputs[i].outputIndex!]);\n this.cachedValidations[txid].parents.push({\n txid: txn.inputs[i].prevTxId.toString(\"hex\"),\n vout: txn.inputs[i].outputIndex!,\n versionType: input_slpmsg.versionType,\n valid: null,\n inputQty: input_slpmsg.sendOutputs![txn.inputs[i].outputIndex!]\n });\n }\n }\n else if (input_slpmsg.transactionType === SlpTransactionType.GENESIS || input_slpmsg.transactionType === SlpTransactionType.MINT) {\n if (txn.inputs[i].outputIndex === 1) {\n tokenInQty = tokenInQty.plus(input_slpmsg.genesisOrMintQuantity!);\n this.cachedValidations[txid].parents.push({\n txid: txn.inputs[i].prevTxId.toString(\"hex\"),\n vout: txn.inputs[i].outputIndex!,\n versionType: input_slpmsg.versionType,\n valid: null,\n inputQty: input_slpmsg.genesisOrMintQuantity\n });\n }\n }\n }\n } catch (_) {}\n }", " // Check token inputs are greater than token outputs (includes valid and invalid inputs)\n if (tokenOutQty.isGreaterThan(tokenInQty)) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Token outputs are greater than possible token inputs.\";\n return this.cachedValidations[txid].validity!;\n }\n }", " // Set validity validation-cache for parents, and handle MINT condition with no valid input\n // we don't need to check proper token id since we only added parents with same ID in above steps.\n const parentTxids = [...new Set(this.cachedValidations[txid].parents.map(p => p.txid))];", " for (const id of parentTxids) {\n const valid = await this.isValidSlpTxid(id);\n this.cachedValidations[txid].parents.filter(p => p.txid === id).map(p => p.valid = valid);\n }", " // Check MINT for exactly 1 valid MINT baton\n if (this.cachedValidations[txid].details!.transactionType === SlpTransactionType.MINT) {\n if (this.cachedValidations[txid].parents.filter(p => p.valid && p.inputQty === null).length !== 1) {", " this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"MINT transaction with invalid baton parent.\";\n return this.cachedValidations[txid].validity!;\n }\n }", " // Check valid inputs are greater than token outputs\n if (this.cachedValidations[txid].details!.transactionType === SlpTransactionType.SEND) {\n const validInputQty = this.cachedValidations[txid].parents.reduce((t, v) => { return v.valid ? t.plus(v.inputQty!) : t; }, new BigNumber(0));\n const tokenOutQty = slpmsg.sendOutputs!.reduce((t, v) => { return t.plus(v); }, new BigNumber(0));\n if (tokenOutQty.isGreaterThan(validInputQty)) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"Token outputs are greater than valid token inputs.\";\n return this.cachedValidations[txid].validity!;\n }\n }", " // Check versionType is not different from valid parents\n if (this.cachedValidations[txid].parents.filter(p => p.valid).length > 0) {\n const validVersionType = this.cachedValidations[txid].parents.find(p => p.valid!)!.versionType;\n if (this.cachedValidations[txid].details!.versionType !== validVersionType) {\n this.cachedValidations[txid].validity = false;\n this.cachedValidations[txid].waiting = false;\n this.cachedValidations[txid].invalidReason = \"SLP version/type mismatch from valid parent.\";\n return this.cachedValidations[txid].validity!;\n }\n }\n this.cachedValidations[txid].validity = true;\n this.cachedValidations[txid].waiting = false;\n return this.cachedValidations[txid].validity!;\n }", " public async validateSlpTransactions(txids: string[]): Promise<string[]> {\n const res = [];\n for (let i = 0; i < txids.length; i++) {\n res.push((await this.isValidSlpTxid(txids[i])) ? txids[i] : \"\");\n }\n return res.filter((id: string) => id.length > 0);\n }\n}" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [349], "buggy_code_start_loc": [285], "filenames": ["lib/localvalidator.ts"], "fixing_code_end_loc": [353], "fixing_code_start_loc": [285], "message": "SLPJS (npm package slpjs) before version 0.27.2, has a vulnerability where users could experience false-negative validation outcomes for MINT transaction operations. A poorly implemented SLP wallet could allow spending of the affected tokens which would result in the destruction of a user's minting baton. This is fixed in version 0.27.2.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:simpleledger:slpjs:*:*:*:*:*:node.js:*:*", "matchCriteriaId": "035AB245-62DC-434B-A63F-D1AC45D95DFC", "versionEndExcluding": "0.27.2", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "SLPJS (npm package slpjs) before version 0.27.2, has a vulnerability where users could experience false-negative validation outcomes for MINT transaction operations. A poorly implemented SLP wallet could allow spending of the affected tokens which would result in the destruction of a user's minting baton. This is fixed in version 0.27.2."}, {"lang": "es", "value": "SLPJS (paquete slpjs de npm) versiones anteriores a 0.27.2, presenta una vulnerabilidad donde los usuarios podr\u00edan experimentar resultados de comprobaci\u00f3n falsos negativos para las operaciones de transacci\u00f3n MINT. Una billetera SLP mal implementada podr\u00eda permitir el gasto de los tokens afectados, lo que resultar\u00eda en la destrucci\u00f3n minting baton del usuario. Esto es corrigido en la versi\u00f3n 0.27.2."}], "evaluatorComment": null, "id": "CVE-2020-11071", "lastModified": "2020-05-19T16:18:03.590", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "NETWORK", "authentication": "NONE", "availabilityImpact": "NONE", "baseScore": 5.0, "confidentialityImpact": "NONE", "integrityImpact": "PARTIAL", "vectorString": "AV:N/AC:L/Au:N/C:N/I:P/A:N", "version": "2.0"}, "exploitabilityScore": 10.0, "impactScore": 2.9, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "nvd@nist.gov", "type": "Primary", "userInteractionRequired": false}], "cvssMetricV30": null, "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "nvd@nist.gov", "type": "Primary"}, {"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "NONE", "baseScore": 8.6, "baseSeverity": "HIGH", "confidentialityImpact": "NONE", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "CHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:N/I:H/A:N", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 4.0, "source": "security-advisories@github.com", "type": "Secondary"}]}, "published": "2020-05-12T01:15:11.150", "references": [{"source": "security-advisories@github.com", "tags": ["Patch", "Tool Signature"], "url": "https://github.com/simpleledger/slpjs/commit/3671be2ffb6d4cfa94c00c6dc8649d1ba1d75754"}, {"source": "security-advisories@github.com", "tags": ["Tool Signature"], "url": "https://github.com/simpleledger/slpjs/security/advisories/GHSA-jc83-cpf9-q7c6"}], "sourceIdentifier": "security-advisories@github.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-697"}], "source": "nvd@nist.gov", "type": "Primary"}, {"description": [{"lang": "en", "value": "CWE-697"}], "source": "security-advisories@github.com", "type": "Secondary"}]}, "github_commit_url": "https://github.com/simpleledger/slpjs/commit/3671be2ffb6d4cfa94c00c6dc8649d1ba1d75754"}, "type": "CWE-697"}
40
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '../models/Location_History.php';", "", "", "// range of dates\nif ($dateFilter[0]) {", "\t$query .= \" AND start_date >= STR_TO_DATE('\" . htmlspecialchars($dateFilter[0]) . \"', '%m/%d/%Y')\";", "}", "if ($dateFilter[1]) {", "\t$query .= \" AND start_date <= STR_TO_DATE('\" . htmlspecialchars($dateFilter[1]) . \"', '%m/%d/%Y')\";", "}", "\n// filtered-out days\nif (isset($dayFilter)) {", "\t$query .= \" AND DAYOFWEEK(start_date) NOT IN (\" . htmlspecialchars($dayFilter) . \")\";", "}", "\n?>" ]
[ 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '../models/Location_History.php';", "", "", "// range of dates\nif ($dateFilter[0]) {", "\t$query .= \" AND start_date >= STR_TO_DATE('\" . $db->mysqli()->real_escape_string($dateFilter[0]) . \"', '%m/%d/%Y')\";", "}", "if ($dateFilter[1]) {", "\t$query .= \" AND start_date <= STR_TO_DATE('\" . $db->mysqli()->real_escape_string($dateFilter[1]) . \"', '%m/%d/%Y')\";", "}", "\n// filtered-out days\nif (isset($dayFilter)) {", "\t$query .= \" AND DAYOFWEEK(start_date) NOT IN (\" . $dayFilter . \")\";", "}", "\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '../models/Location_History.php';", "\n// limit number of results\n$limit = null;\nif ($_POST['limit']) {", "\t$limit = $_POST['limit'];", "}", "\n// select only a certain range of dates\n$dayFilter = null;\nif (isset($_POST['dayFilter'])) {", "\t$dayFilter = implode(',', $_POST['dayFilter']);", "}", "", "// filter out certain days of the week", "$dateFilter = array('', '');\nif (isset($_POST['dateFilter'])) {\n\t$dateFilter = $_POST['dateFilter'];\n}", "", "?>" ]
[ 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '../models/Location_History.php';", "\n// limit number of results\n$limit = null;\nif ($_POST['limit']) {", "\t$limit = $db->mysqli()->real_escape_string($_POST['limit']);", "}", "\n// select only a certain range of dates\n$dayFilter = null;\nif (isset($_POST['dayFilter'])) {", "\t$dayFilter = $db->mysqli()->real_escape_string(implode(',', $_POST['dayFilter']));", "}", "", "// filter out certain days of the week. the elements of this array are escaped in __build_query.php", "$dateFilter = array('', '');\nif (isset($_POST['dateFilter'])) {\n\t$dateFilter = $_POST['dateFilter'];\n}", "", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';", "", "\n// visits\n$query = \"SELECT\n\tCOUNT(gp.id) AS num, SUM(gp.duration) AS duration\n\tFROM grouped_point gp\n\tWHERE 1 = 1\";", "\n// CONSTRUCT WHERE CLAUSE\ninclude '__build_query.php';\n", "$visits = $db->rawQuery($query, null, false);", "", "\n// trips\n$query = \"SELECT\n\tCOUNT(t.id) AS num, SUM(t.duration) AS duration, SUM(t.distance) AS distance\n\tFROM trip t\n\tWHERE 1 = 1\";", "\n// CONSTRUCT WHERE CLAUSE\ninclude '__build_query.php';\n", "$trips = $db->rawQuery($query, null, false);", "", "echo json_encode(array(\"visits\" => $visits, \"trips\" => $trips));", "", "", "\n?>" ]
[ 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';", "", "\n// visits\n$query = \"SELECT\n\tCOUNT(gp.id) AS num, SUM(gp.duration) AS duration\n\tFROM grouped_point gp\n\tWHERE 1 = 1\";", "\n// CONSTRUCT WHERE CLAUSE\ninclude '__build_query.php';\n", "$visits = $db->rawQuery($query, null);", "", "\n// trips\n$query = \"SELECT\n\tCOUNT(t.id) AS num, SUM(t.duration) AS duration, SUM(t.distance) AS distance\n\tFROM trip t\n\tWHERE 1 = 1\";", "\n// CONSTRUCT WHERE CLAUSE\ninclude '__build_query.php';\n", "$trips = $db->rawQuery($query, null);", "", "echo json_encode(array(\"visits\" => $visits, \"trips\" => $trips));", "", "", "\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';", "", "// this cannot return meaningful results with a location id\nif (!$_POST['location_id']) {\n\treturn;\n}\n", "$location_id = $_POST['location_id'];", "", "\n// visits for location\n$query = \"SELECT\n\tDATE(start_date) AS date, SUM(duration) AS duration\n\tFROM grouped_point gp", "\tWHERE location_id = \" . htmlspecialchars($location_id);", "", "// CONSTRUCT WHERE CLAUSE\ninclude '__build_query.php';", "// group by comes after where clause\n$query .= \" GROUP BY DATE(start_date)\";\n", "$results = $db->rawQuery($query, null, false);", "", "// convert seconds to hours, and make sure that no day is longer than 24 hours, by rolling extra hours over to the next record\nforeach($results as $index => &$result) {\n\t$duration = $result['duration'];", "\tif ($duration > 86400) {\n\t\tif (isset($results[$index + 1])) {\n\t\t\t$results[$index + 1]['duration'] += $duration - 86400;\n\t\t}\n\t\t$duration = 86400;", "\t}", "\t$result['duration'] = round($duration / 3600, 1);\n}\nunset($value);", "\necho json_encode($results);", "", "\n?>" ]
[ 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';", "", "// this cannot return meaningful results with a location id\nif (!$_POST['location_id']) {\n\treturn;\n}\n", "", "\n// visits for location\n$query = \"SELECT\n\tDATE(start_date) AS date, SUM(duration) AS duration\n\tFROM grouped_point gp", "\tWHERE location_id = ?\";", "", "// CONSTRUCT WHERE CLAUSE\ninclude '__build_query.php';", "// group by comes after where clause\n$query .= \" GROUP BY DATE(start_date)\";\n", "$results = $db->rawQuery($query, Array($_POST['location_id']));", "", "// convert seconds to hours, and make sure that no day is longer than 24 hours, by rolling extra hours over to the next record\nforeach($results as $index => &$result) {\n\t$duration = $result['duration'];", "\tif ($duration > 86400) {\n\t\tif (isset($results[$index + 1])) {\n\t\t\t$results[$index + 1]['duration'] += $duration - 86400;\n\t\t}\n\t\t$duration = 86400;", "\t}", "\t$result['duration'] = round($duration / 3600, 1);\n}\nunset($value);", "\necho json_encode($results);", "", "\n?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';", "", "\n// this query also counts the grouped_points that contribute to each location, and gets the duration dynamically by summing the duration values from the grouped_points, which means this can respond to any filters specified by the user\n$query = \"SELECT\n\tl.id, SUM(gp.duration) AS duration, l.lat, l.lon, l.geocode_name, l.name, l.description, COUNT(l.id) AS visits\n\tFROM location l, grouped_point gp\n\tWHERE l.id = gp.location_id\";", "", "// CONSTRUCT WHERE CLAUSE\ninclude_once '__build_query.php';", "", "// group by and order by come after where clause\n$query .= \" GROUP BY l.id ORDER BY duration DESC\";", "\n// limit clause comes last\nif (isset($limit)) {", "\t$query .= \" LIMIT \" . htmlspecialchars($limit);", "}", "\n", "echo json_encode($db->rawQuery($query, null, false));", "", "", "", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';", "", "\n// this query also counts the grouped_points that contribute to each location, and gets the duration dynamically by summing the duration values from the grouped_points, which means this can respond to any filters specified by the user\n$query = \"SELECT\n\tl.id, SUM(gp.duration) AS duration, l.lat, l.lon, l.geocode_name, l.name, l.description, COUNT(l.id) AS visits\n\tFROM location l, grouped_point gp\n\tWHERE l.id = gp.location_id\";", "", "// CONSTRUCT WHERE CLAUSE\ninclude_once '__build_query.php';", "", "// group by and order by come after where clause\n$query .= \" GROUP BY l.id ORDER BY duration DESC\";", "\n// limit clause comes last\nif (isset($limit)) {", "\t$query .= \" LIMIT \" . $limit;", "}", "\n", "echo json_encode($db->rawQuery($query, null));", "", "", "", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';\ninclude_once '../models/Circular.php';", "\n// this cannot return meaningful results without a location id\nif (!$_POST['location_id']) {\n\treturn;\n}\n", "$location_id = htmlspecialchars($_POST['location_id']);", "", "", "", "/* trips starting at location\n–––––––––––––––––––––––––––––––––––––––––––––––––– */", " /* aggregate\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT COUNT(t.end_location_id) AS count_lid, t.end_location_id, l.name, AVG(t.duration) AS duration, 0 AS start_time, AVG(t.distance) AS distance\nFROM trip t, location l\nWHERE t.end_location_id = l.id\nAND t.start_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" GROUP BY t.end_location_id HAVING count_lid > 1 ORDER BY count_lid DESC\";", "$start_aggregate = $db->rawQuery($query, null, false);", "", "", " /* all\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT t.end_location_id, l.name, DATE(t.start_date) AS start_date, TIME(t.start_date) AS start_time, TIME_TO_SEC(t.start_date) AS start_time_sec, t.duration, t.distance\nFROM trip t, location l,\n\t(SELECT COUNT(t.end_location_id) AS count_lid, t.end_location_id\n\tFROM trip t\n\tWHERE t.start_location_id = \" . $location_id;", "include '__build_query.php';", "$query .= \" GROUP BY t.end_location_id) AS c\nWHERE t.end_location_id = l.id\nAND t.end_location_id = c.end_location_id\nAND t.start_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" ORDER BY c.count_lid DESC, t.end_location_id, t.start_date ASC\";", "$start_all = $db->rawQuery($query, null, false);", "", "", "/* trips ending at location\n–––––––––––––––––––––––––––––––––––––––––––––––––– */", " /* aggregate\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT COUNT(t.start_location_id) AS count_lid, t.start_location_id, l.name, AVG(t.duration) AS duration, 0 AS end_time, AVG(t.distance) AS distance\nFROM trip t, location l\nWHERE t.start_location_id = l.id\nAND t.end_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" GROUP BY t.start_location_id HAVING count_lid > 1 ORDER BY count_lid DESC\";", "$end_aggregate = $db->rawQuery($query, null, false);", "", "", " /* all\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT t.start_location_id, l.name, DATE(t.end_date) AS end_date, TIME(t.end_date) AS end_time, TIME_TO_SEC(t.end_date) AS end_time_sec, t.duration, t.distance\nFROM trip t, location l,\n\t(SELECT COUNT(t.start_location_id) AS count_lid, t.start_location_id\n\tFROM trip t\n\tWHERE t.end_location_id = \" . $location_id;", "include '__build_query.php';", "$query .= \" GROUP BY t.start_location_id) AS c\nWHERE t.start_location_id = l.id\nAND t.start_location_id = c.start_location_id\nAND t.end_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" ORDER BY c.count_lid DESC, t.start_location_id, t.end_date ASC\";", "$end_all = $db->rawQuery($query, null, false);", "", "", "", "/* all trips starting at and ending at this location\n–––––––––––––––––––––––––––––––––––––––––––––––––– */", "$query = \"SELECT ls.name AS start_name, le.name AS end_name, SQ.* FROM\n(SELECT t.start_location_id, t.end_location_id, DATE(t.start_date) AS start_date, TIME(t.start_date) AS start_time, t.duration, t.distance\nFROM trip t\nWHERE t.start_location_id = \" . $location_id . \" OR t.end_location_id = \" . $location_id;", "include '__build_query.php';", "$query .= \" ORDER BY t.start_date ASC) SQ, location ls, location le\nWHERE ls.id = SQ.start_location_id AND le.id = SQ.end_location_id\";\n", "$start_end_all = $db->rawQuery($query, null, false);", "", "", "", "", "", "function modify_avg_times($all, &$aggregate, $location_string = 'end', $time_string = 'start') {", "\t$old_id = '';\n\t$times = array();", "\tforeach ($all as $result) {\n\t\t$id = $result[$location_string . '_location_id'];", "\t\tif ($old_id !== $id) {\n\t\t\tif (isset($times[$old_id]) && count($times[$old_id]) == 1) {\n\t\t\t\tunset($times[$old_id]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$times[$id] = array();\n\t\t}", "\t\t$old_id = $id;\n\t\t$times[$id][] = $result[$time_string . '_time_sec'];\n\t}", "\n\tforeach ($aggregate as &$result) {\n\t\t$result[$time_string . '_time'] = round(circularMean(\n\t\t\t$times[$result[$location_string . '_location_id']]\n\t\t\t, 86400));\n\t}\n\tunset($result);\n}", "modify_avg_times($start_all, $start_aggregate);\nmodify_avg_times($end_all, $end_aggregate, 'start', 'end');", "\necho json_encode(array(\n\t\"start_aggregate\" => $start_aggregate,\n\t\"start_all\" => $start_all,\n\t\"end_aggregate\" => $end_aggregate,\n\t\"end_all\" => $end_all,\n\t\"start_end_all\" => $start_end_all\n\t));", "", "", "?>" ]
[ 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41
Determine whether the {function_name} code is vulnerable or not.
[ "<?php", "include_once '__parse_query.php';\ninclude_once '../models/Circular.php';", "\n// this cannot return meaningful results without a location id\nif (!$_POST['location_id']) {\n\treturn;\n}\n", "$location_id = $db->mysqli()->real_escape_string($_POST['location_id']);", "", "", "", "/* trips starting at location\n–––––––––––––––––––––––––––––––––––––––––––––––––– */", " /* aggregate\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT COUNT(t.end_location_id) AS count_lid, t.end_location_id, l.name, AVG(t.duration) AS duration, 0 AS start_time, AVG(t.distance) AS distance\nFROM trip t, location l\nWHERE t.end_location_id = l.id\nAND t.start_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" GROUP BY t.end_location_id HAVING count_lid > 1 ORDER BY count_lid DESC\";", "$start_aggregate = $db->rawQuery($query, null);", "", "", " /* all\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT t.end_location_id, l.name, DATE(t.start_date) AS start_date, TIME(t.start_date) AS start_time, TIME_TO_SEC(t.start_date) AS start_time_sec, t.duration, t.distance\nFROM trip t, location l,\n\t(SELECT COUNT(t.end_location_id) AS count_lid, t.end_location_id\n\tFROM trip t\n\tWHERE t.start_location_id = \" . $location_id;", "include '__build_query.php';", "$query .= \" GROUP BY t.end_location_id) AS c\nWHERE t.end_location_id = l.id\nAND t.end_location_id = c.end_location_id\nAND t.start_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" ORDER BY c.count_lid DESC, t.end_location_id, t.start_date ASC\";", "$start_all = $db->rawQuery($query, null);", "", "", "/* trips ending at location\n–––––––––––––––––––––––––––––––––––––––––––––––––– */", " /* aggregate\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT COUNT(t.start_location_id) AS count_lid, t.start_location_id, l.name, AVG(t.duration) AS duration, 0 AS end_time, AVG(t.distance) AS distance\nFROM trip t, location l\nWHERE t.start_location_id = l.id\nAND t.end_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" GROUP BY t.start_location_id HAVING count_lid > 1 ORDER BY count_lid DESC\";", "$end_aggregate = $db->rawQuery($query, null);", "", "", " /* all\n –––––––––––––––––––––––––––––– */\n$query = \"SELECT t.start_location_id, l.name, DATE(t.end_date) AS end_date, TIME(t.end_date) AS end_time, TIME_TO_SEC(t.end_date) AS end_time_sec, t.duration, t.distance\nFROM trip t, location l,\n\t(SELECT COUNT(t.start_location_id) AS count_lid, t.start_location_id\n\tFROM trip t\n\tWHERE t.end_location_id = \" . $location_id;", "include '__build_query.php';", "$query .= \" GROUP BY t.start_location_id) AS c\nWHERE t.start_location_id = l.id\nAND t.start_location_id = c.start_location_id\nAND t.end_location_id = \" . $location_id;", "include '__build_query.php';\n$query .= \" ORDER BY c.count_lid DESC, t.start_location_id, t.end_date ASC\";", "$end_all = $db->rawQuery($query, null);", "", "", "", "/* all trips starting at and ending at this location\n–––––––––––––––––––––––––––––––––––––––––––––––––– */", "$query = \"SELECT ls.name AS start_name, le.name AS end_name, SQ.* FROM\n(SELECT t.start_location_id, t.end_location_id, DATE(t.start_date) AS start_date, TIME(t.start_date) AS start_time, t.duration, t.distance\nFROM trip t\nWHERE t.start_location_id = \" . $location_id . \" OR t.end_location_id = \" . $location_id;", "include '__build_query.php';", "$query .= \" ORDER BY t.start_date ASC) SQ, location ls, location le\nWHERE ls.id = SQ.start_location_id AND le.id = SQ.end_location_id\";\n", "$start_end_all = $db->rawQuery($query, null);", "", "", "", "", "", "function modify_avg_times($all, &$aggregate, $location_string = 'end', $time_string = 'start') {", "\t$old_id = '';\n\t$times = array();", "\tforeach ($all as $result) {\n\t\t$id = $result[$location_string . '_location_id'];", "\t\tif ($old_id !== $id) {\n\t\t\tif (isset($times[$old_id]) && count($times[$old_id]) == 1) {\n\t\t\t\tunset($times[$old_id]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t$times[$id] = array();\n\t\t}", "\t\t$old_id = $id;\n\t\t$times[$id][] = $result[$time_string . '_time_sec'];\n\t}", "\n\tforeach ($aggregate as &$result) {\n\t\t$result[$time_string . '_time'] = round(circularMean(\n\t\t\t$times[$result[$location_string . '_location_id']]\n\t\t\t, 86400));\n\t}\n\tunset($result);\n}", "modify_avg_times($start_all, $start_aggregate);\nmodify_avg_times($end_all, $end_aggregate, 'start', 'end');", "\necho json_encode(array(\n\t\"start_aggregate\" => $start_aggregate,\n\t\"start_all\" => $start_all,\n\t\"end_aggregate\" => $end_aggregate,\n\t\"end_all\" => $end_all,\n\t\"start_end_all\" => $start_end_all\n\t));", "", "", "?>" ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
PreciseBugs
{"buggy_code_end_loc": [20, 21, 33, 30, 33, 113, 48, 210], "buggy_code_start_loc": [6, 9, 18, 12, 27, 12, 12, 210], "filenames": ["location_history/controllers/__build_query.php", "location_history/controllers/__parse_query.php", "location_history/controllers/global.php", "location_history/controllers/graph.php", "location_history/controllers/main.php", "location_history/controllers/trips.php", "location_history/controllers/visits.php", "location_history/css/style.css"], "fixing_code_end_loc": [19, 21, 33, 27, 33, 113, 42, 215], "fixing_code_start_loc": [5, 9, 18, 11, 27, 12, 11, 211], "message": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951.", "other": {"cve": {"cisaActionDue": null, "cisaExploitAdd": null, "cisaRequiredAction": null, "cisaVulnerabilityName": null, "configurations": [{"nodes": [{"cpeMatch": [{"criteria": "cpe:2.3:a:dronfelipe_project:dronfelipe:*:*:*:*:*:*:*:*", "matchCriteriaId": "FA0A8188-6479-47FB-A14B-243F0A987A14", "versionEndExcluding": "2015-12-15", "versionEndIncluding": null, "versionStartExcluding": null, "versionStartIncluding": null, "vulnerable": true}], "negate": false, "operator": "OR"}], "operator": null}], "descriptions": [{"lang": "en", "value": "A vulnerability was found in kylebebak dronfelipe. It has been declared as critical. Affected by this vulnerability is an unknown functionality. The manipulation leads to sql injection. The name of the patch is 87405b74fe651892d79d0dff62ed17a7eaef6a60. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-217951."}], "evaluatorComment": null, "id": "CVE-2015-10036", "lastModified": "2023-01-18T18:00:00.897", "metrics": {"cvssMetricV2": [{"acInsufInfo": false, "baseSeverity": "MEDIUM", "cvssData": {"accessComplexity": "LOW", "accessVector": "ADJACENT_NETWORK", "authentication": "SINGLE", "availabilityImpact": "PARTIAL", "baseScore": 5.2, "confidentialityImpact": "PARTIAL", "integrityImpact": "PARTIAL", "vectorString": "AV:A/AC:L/Au:S/C:P/I:P/A:P", "version": "2.0"}, "exploitabilityScore": 5.1, "impactScore": 6.4, "obtainAllPrivilege": false, "obtainOtherPrivilege": false, "obtainUserPrivilege": false, "source": "cna@vuldb.com", "type": "Secondary", "userInteractionRequired": false}], "cvssMetricV30": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "ADJACENT_NETWORK", "availabilityImpact": "LOW", "baseScore": 5.5, "baseSeverity": "MEDIUM", "confidentialityImpact": "LOW", "integrityImpact": "LOW", "privilegesRequired": "LOW", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.0/AV:A/AC:L/PR:L/UI:N/S:U/C:L/I:L/A:L", "version": "3.0"}, "exploitabilityScore": 2.1, "impactScore": 3.4, "source": "cna@vuldb.com", "type": "Secondary"}], "cvssMetricV31": [{"cvssData": {"attackComplexity": "LOW", "attackVector": "NETWORK", "availabilityImpact": "HIGH", "baseScore": 9.8, "baseSeverity": "CRITICAL", "confidentialityImpact": "HIGH", "integrityImpact": "HIGH", "privilegesRequired": "NONE", "scope": "UNCHANGED", "userInteraction": "NONE", "vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H", "version": "3.1"}, "exploitabilityScore": 3.9, "impactScore": 5.9, "source": "nvd@nist.gov", "type": "Primary"}]}, "published": "2023-01-11T07:15:10.743", "references": [{"source": "cna@vuldb.com", "tags": ["Patch", "Third Party Advisory"], "url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?ctiid.217951"}, {"source": "cna@vuldb.com", "tags": ["Third Party Advisory"], "url": "https://vuldb.com/?id.217951"}], "sourceIdentifier": "cna@vuldb.com", "vendorComments": null, "vulnStatus": "Analyzed", "weaknesses": [{"description": [{"lang": "en", "value": "CWE-89"}], "source": "cna@vuldb.com", "type": "Primary"}]}, "github_commit_url": "https://github.com/kylebebak/dronfelipe/commit/87405b74fe651892d79d0dff62ed17a7eaef6a60"}, "type": "CWE-89"}
41