First Upload
This commit is contained in:
674
LICENSE.txt
Normal file
674
LICENSE.txt
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
405
README.md
Normal file
405
README.md
Normal file
@@ -0,0 +1,405 @@
|
||||
<!-- References:
|
||||
https://www.twilio.com/blog/get-started-docker-laravel
|
||||
https://laravel-for-newbie.kejyun.com/en/advanced/scheduling/docker/
|
||||
https://github.com/mohammadain/laravel-docker-cron/blob/master/Dockerfile -->
|
||||
|
||||
<!-- Improved compatibility of back to top link: See: https://github.com/othneildrew/Best-README-Template/pull/73 -->
|
||||
|
||||
<a name="readme-top"></a>
|
||||
|
||||
<!-- PROJECT LOGO -->
|
||||
<br />
|
||||
<div align="center">
|
||||
<a href="https://github.com/rconfig/rconfig">
|
||||
<img src="https://www.rconfig.com/images/rConfig_logos/new/blue/hex_logo_blue_horizontal_96.png" alt="rConfig Logo" />
|
||||
</a>
|
||||
|
||||
<h3 align="center">rConfig v6 Core</h3>
|
||||
|
||||
<p align="center">
|
||||
rConfig v6 Core is a free, open source, community edition of rConfig v6. It is a fully functional version of rConfig v6, with all the core features of rConfig v6 Professional, but with some limitations. Check out our features list <a href="https://www.rconfig.com/features"><strong>www.rconfig.com/features</strong></a> to learn more.
|
||||
<br />
|
||||
<br />
|
||||
<a href="https://www.rconfig.com/docs"><strong>Explore the docs »</strong></a>
|
||||
<br />
|
||||
<br />
|
||||
<a href="#intro">Intro</a>
|
||||
·
|
||||
<a href="#setup">Installation</a>
|
||||
·
|
||||
<a href="#update">Updating</a>
|
||||
·
|
||||
<a href="#contributing">Contributing</a>
|
||||
·
|
||||
<a href="#license">License</a>
|
||||
·
|
||||
<a href="#support">Support</a>
|
||||
</p>
|
||||
|
||||
[](https://github.com/eliashaeussler/typo3-badges/actions/workflows/tests.yaml)
|
||||
[](LICENSE) [](https://nodejs.org 'Go to Node.js homepage')
|
||||
[](https://packagist.org/packages/pugx/badge-poser)
|
||||
|
||||
<img src="https://img.shields.io/badge/-Vue3-4FC08D?logo=vue.js&logoColor=white&style=flat"/>
|
||||
<img src="https://img.shields.io/badge/-Laravel-FF2D20?logo=laravel&logoColor=white&style=flat"/>
|
||||
<!-- <img src="https://img.shields.io/badge/-Tailwind%20CSS-06B6D4?logo=tailwind-css&logoColor=white&style=flat"/> -->
|
||||
<img src="https://img.shields.io/badge/-ViteJs-6e37a0?logo=vite&logoColor=white&style=flat"/>
|
||||
<img src="https://img.shields.io/badge/-PatternFly-004285?logo=Ghost&logoColor=white&style=flat"/>
|
||||
<img src="https://img.shields.io/badge/-mySQL-4479A1?logo=mysql&logoColor=white&style=flat"/>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Intro -->
|
||||
|
||||
<a name="intro"></a>
|
||||
|
||||
## Intro
|
||||
|
||||
rConfig v6 is an enterprise grade Network Configuration Management (NCM) software package with superior NCM features and capabilities to help you easily manage configurations on large and small heterogenous networks. rConfig v6 is our flagship professional version of rConfig aimed at high value networks and business operations. rConfig v6 runs natively on many variants of Linux. Within this repo, is the code base for rConfig v6 Core, and a set of scripts to help you get started with rConfig v6 Core.
|
||||
|
||||
If you are looking for rConfig V6 professional, please visit `https://www.rconfig.com/`.
|
||||
|
||||
Supported OS
|
||||
|
||||
- Rocky Linux 8/9+
|
||||
- RHEL Linux 8/9+
|
||||
- CentOS Linux 8/9+
|
||||
- Ubuntu 20.04+
|
||||
- Docker (Linux)(not yet ready)
|
||||
|
||||
rConfig v6 core is completely free, you do not need an API key from rConfig to download and use this version. Please follow the instructions below to get started.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- Installation -->
|
||||
|
||||
<a name="setup"></a>
|
||||
|
||||
## Installation
|
||||
|
||||
We have made it super easy to get started with rConfig v6. Follow the steps below to get started. Check out our youtube channel for a video walkthrough of the installation process.
|
||||
|
||||
[https://www.youtube.com/channel/rconfigV6Core](https://www.youtube.com/playlist?list=PL8dpV2hQIDLR04p5RuJEVcdhQY1gXKOgU)
|
||||
|
||||
> [!NOTE]
|
||||
> Do not follow the installation steps to update existing rConfig installations. You must skip to the <a href="#update">Updating</a> section below.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Setup a server with one of the supported OS's listed above. We recommend using a fresh install of the OS. If you are using a server that has been in production, we recommend you backup the server before proceeding.
|
||||
|
||||
You will need to install the following software on your server:
|
||||
Git 2.25+
|
||||
PHP 8.1+
|
||||
Composer 2.4+
|
||||
Apache 2.4+
|
||||
MySQL 5.7+ or MariaDB 10.5+
|
||||
nodejs 14.17+
|
||||
Supervisor 4.2+
|
||||
|
||||
We have conveniently provided scripts to help you install the required software. Head over to [https://docs.rconfig.com/getstarted/os-setup](https://docs.rconfig.com/getstarted/os-setup) to find the correct script for your OS. If you are using a different OS, you will need to install the required software manually.
|
||||
|
||||
> **Note**
|
||||
> You will need to be logged in as root when running the scripts.
|
||||
|
||||
### Database Setup
|
||||
|
||||
1. Login to your database server as root
|
||||
2. Create a new database
|
||||
|
||||
```sh
|
||||
mysql -u root -p
|
||||
CREATE DATABASE rconfig;
|
||||
```
|
||||
|
||||
3. Create a new user if required (do not use the credentials below in production). This is likely required for Ubutnu 20.04+. If you are using a different OS, you may not need to create a new user, and you can use the root account, though this is not recommended.
|
||||
|
||||
```sh
|
||||
|
||||
CREATE USER 'user1'@'localhost' IDENTIFIED BY 'password1';
|
||||
GRANT ALL PRIVILEGES ON rconfig.* TO 'user1'@'localhost';
|
||||
FLUSH PRIVILEGES;
|
||||
```
|
||||
|
||||
4. Exit the database
|
||||
|
||||
```sh
|
||||
exit
|
||||
```
|
||||
|
||||
### rConfig Setup Steps
|
||||
|
||||
1. Login as root
|
||||
2. Clone the repo
|
||||
|
||||
```sh
|
||||
cd /var/www/html
|
||||
git clone https://github.com/rconfig/rconfig.git
|
||||
```
|
||||
|
||||
3. Change directory to the repo
|
||||
|
||||
```sh
|
||||
cd rconfig
|
||||
```
|
||||
|
||||
4. Create the .env file
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
5. Edit the .env file and update the following variables:
|
||||
|
||||
```sh
|
||||
APP_URL="https://SERVER.DOMAIN.LOCAL"
|
||||
APP_DIR_PATH=/var/www/html/rconfig
|
||||
DB_HOST=DBHOST
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=DBNAME
|
||||
DB_USERNAME=DBUSER
|
||||
DB_PASSWORD=DBPASS
|
||||
```
|
||||
|
||||
6. Install the required PHP packages
|
||||
|
||||
```sh
|
||||
export COMPOSER_ALLOW_SUPERUSER=1
|
||||
composer self-update --2
|
||||
yes | composer install --no-dev
|
||||
```
|
||||
|
||||
7. Install apache and supervisor
|
||||
|
||||
```sh
|
||||
chmod +x setup_apache.sh
|
||||
./setup_apache.sh
|
||||
```
|
||||
|
||||
8. Install supervisor
|
||||
|
||||
```sh
|
||||
chmod +x setup_supervisor.sh
|
||||
./setup_supervisor.sh
|
||||
```
|
||||
|
||||
9. Run the installation script. This will install the required packages, setup the database, and configure the web server. The script will take a few minutes to complete.
|
||||
|
||||
> [!WARNING]
|
||||
> Do not run the next command on existing rConfig deployments in an attempt to update. You must follow the instructions in the <a href="#update">Updating</a> section below. The command below is for new installations only.
|
||||
|
||||
```sh
|
||||
php artisan install
|
||||
```
|
||||
|
||||
If you area asked 'Add a cron entry for task scheduling?', type `yes` and press enter.
|
||||
|
||||
The output from the above should look like this:
|
||||
|
||||
```sh
|
||||
|
||||
|
||||
APPLICATION INSTALL.
|
||||
|
||||
|
||||
Packages discovery ...................................................................... 5ms DONE
|
||||
|
||||
command key:generate .................................................................... 2ms DONE
|
||||
command migrate
|
||||
....................................................................... 387ms DONE
|
||||
command passport:install ............................................................ 1,839ms DONE
|
||||
command rconfig:clear-all
|
||||
No config updates to processes
|
||||
|
||||
|
||||
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
|
||||
Generated optimized autoload files containing 6960 classes
|
||||
........................................................... 7,036ms DONE
|
||||
command rconfig:sync-tasks .............................................................. 5ms DONE
|
||||
script cache .......................................................................... 57ms DONE
|
||||
|
||||
Assets publishing ....................................................................... 7ms DONE
|
||||
|
||||
Add a cron entry for task scheduling? (yes/no) [no]
|
||||
❯ yes
|
||||
|
||||
INFO Entry was added [* * * * * cd /var/www/html/rconfig && php artisan schedule:run >> /dev/null 2>&1].
|
||||
|
||||
INFO Install done!
|
||||
|
||||
```
|
||||
|
||||
8. Update apache config file for correct server name.
|
||||
|
||||
```sh
|
||||
# CentOS/RHEL
|
||||
sudo vi /etc/httpd/conf.d/rconfig-vhost.conf
|
||||
```
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
sudo vi /etc/apache2/sites-enabled/rconfig-vhost.conf
|
||||
```
|
||||
|
||||
Update the `ServerName` to match your server's domain name.
|
||||
|
||||
```sh
|
||||
ServerName YourServerName.domain.local
|
||||
ServerAlias YourServerName.domain.local
|
||||
```
|
||||
|
||||
9. Restart apache
|
||||
|
||||
```sh
|
||||
# CENTOS/RHEL
|
||||
sudo systemctl restart httpd
|
||||
```
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
sudo systemctl restart apache2
|
||||
```
|
||||
|
||||
10. Clear the cache & reset permissions
|
||||
|
||||
```sh
|
||||
# CENTOS/RHEL
|
||||
cd /var/www/html/rconfig
|
||||
chown -R apache storage bootstrap/cache
|
||||
php artisan rconfig:clear-all
|
||||
```
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
cd /var/www/html/rconfig
|
||||
chown -R www-data storage bootstrap/cache
|
||||
php artisan rconfig:clear-all
|
||||
```
|
||||
|
||||
11. Open your browser and navigate to your server's domain name. You should see the rConfig login page. The default system credentials are below. Please change or remove these as soon as a new admin user is created.
|
||||
|
||||
Username: admin@domain.com
|
||||
Password: admin
|
||||
|
||||
Check out our docs `docs.rconfig.com` to learn more.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- Updating -->
|
||||
|
||||
<a name="update"></a>
|
||||
|
||||
## Updating
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Your advised to backup your database, .env file and storage directory at a minimum before proceeding. You should also backup your entire server if possible.
|
||||
|
||||
Instruction on how to update your installation of rConfig v6 Core are below. You should run the commands below as root, and you may need to use sudo if installed on Ubuntu.
|
||||
|
||||
> [!WARNING]
|
||||
> If you edit any of the files in the rConfig directory, you may need to resolve conflicts when you run the `git pull` command. You should be familiar with git and how to resolve conflicts. If you are not, you should not edit any of the files in the rConfig directory. If you get a warning about conflicts, you can try a `git stash` and `git pull` to resolve the conflicts. If you are not familiar with git, you should seek help from a professional.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> As of Feb 2024, you will need to update PHP to version 8.3 when updating rConfig Core V6. You will also need to update the composer version to 2.4. You can do this by running the following commands:
|
||||
|
||||
```sh
|
||||
# Update PHP CentOS/RHEL/ Rocky
|
||||
cd /home
|
||||
yum -y install wget
|
||||
wget https://www.rconfig.com/downloads/php-updates/centos-php8-update.sh -O /home/centos-php8-update.sh
|
||||
chmod +x centos-php8-update.sh
|
||||
./centos-php8-update.sh
|
||||
|
||||
# Update PHP Ubuntu
|
||||
cd /home
|
||||
sudo apt-get install wget
|
||||
wget https://www.rconfig.com/downloads/php-updates/ubuntu-php8-update.sh -O /home/ubuntu-php8-update.sh
|
||||
chmod +x ubuntu-php8-update.sh
|
||||
./ubuntu-php8-update.sh
|
||||
```
|
||||
|
||||
rConfig V7 professional subscribers should follow the instructions in the rConfig V7 professional documentation. As the installation and update process is different.
|
||||
|
||||
```sh
|
||||
# Centos/Rocky/RHEL
|
||||
cd /var/www/html/rconfig
|
||||
git pull
|
||||
php artisan migrate
|
||||
php artisan rconfig:sync-tasks
|
||||
composer install
|
||||
systemctl restart httpd
|
||||
php artisan rconfig:clear-all
|
||||
```
|
||||
|
||||
```sh
|
||||
# Ubuntu
|
||||
cd /var/www/html/rconfig
|
||||
git pull
|
||||
php artisan migrate
|
||||
php artisan rconfig:sync-tasks
|
||||
composer install
|
||||
systemctl restart apache2
|
||||
php artisan rconfig:clear-all
|
||||
```
|
||||
|
||||
<!-- CONTRIBUTING -->
|
||||
|
||||
<a name="contributing"></a>
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. We are pretty strict on code quality and style. Please follow the best practices. You should also have a strong working knowledge of PHP, Laravel, and VueJS.
|
||||
|
||||
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
|
||||
Don't forget to give the project a star! Thanks again!
|
||||
|
||||
1. Fork the Project
|
||||
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
||||
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
||||
4. Push to the Branch (`git push origin feature/AmazingFeature`)
|
||||
5. Open a Pull Request for approval to merge into the `develop` branch
|
||||
|
||||
#### How to run tests
|
||||
|
||||
1. Create a new database for testing
|
||||
2. Copy the `.env.example` file to `.env.testing`
|
||||
3. php artisan key:generate --env=testing
|
||||
4. change the `APP_ENV` variable in the `.env.testing` file to `testing`
|
||||
5. Update the `.env.testing` file with the correct database credentials
|
||||
6. Run the tests with `php artisan test`
|
||||
|
||||
Front end development requires `npm install --include=dev`, and `npm run dev` to compile the assets with vite.
|
||||
|
||||
If you get a 'connect ENETUNREACH on npm' command, export the following env var
|
||||
export NODE_OPTIONS="--dns-result-order=ipv4first"
|
||||
You can add this to the ~./bashrc file
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- LICENSE -->
|
||||
|
||||
<a name="license"></a>
|
||||
|
||||
## License
|
||||
|
||||
This code base for this repository's code is distributed under License from rConfig. See `LICENSE.txt` for more information. rConfig v6 Professional is excluded from this license and repository.
|
||||
|
||||
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
||||
|
||||
<!-- https://github.com/othneildrew/Best-README-Template/blob/master/README.md -->
|
||||
|
||||
<a name="support"></a>
|
||||
|
||||
## Support
|
||||
|
||||
Although we provide this code free and open source, rConfig v6 core is based best effort support basis. You may open issues in the issue section here at github. We will try to address issues in a timely manner, but without guarantees. For prompt support and business critical environments, you should take out a subscription for rCOnfig v6 Professional. rConfig Professional subscribers should open a ticket via our normal support channels.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Inspiration, code snippets, etc.
|
||||
|
||||
- [Laravel](https://www.laravel.com)
|
||||
- [vuejs](https://vuejs.org/)
|
||||
- [patternfly v4](https://www.patternfly.org/v4/)
|
||||
|
||||
See composer.json and package.json for a full list of dependencies, and their licenses.
|
23503
_ide_helper.php
Normal file
23503
_ide_helper.php
Normal file
File diff suppressed because it is too large
Load Diff
38
app/Casts/EncryptStringCast.php
Normal file
38
app/Casts/EncryptStringCast.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Casts;
|
||||
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
|
||||
class EncryptStringCast implements CastsAttributes
|
||||
{
|
||||
//https://github.com/laravel/framework/pull/34937/commits/cf6768bddb9f616d60b931ddc82fc140c18a2aec
|
||||
// Bug #100 - v5 Passwords are not displaying correctly after upgrading to v6
|
||||
|
||||
public function get($model, string $key, $value, array $attributes)
|
||||
{
|
||||
$value = ! is_null($value) ? \Crypt::decryptString($value) : null;
|
||||
|
||||
if ($this->is_serialized($value)) {
|
||||
$value = unserialize($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function set($model, string $key, $value, array $attributes)
|
||||
{
|
||||
return [$key => ! is_null($value) ? \Crypt::encryptString($value) : null];
|
||||
}
|
||||
|
||||
private function is_serialized($string)
|
||||
{
|
||||
try {
|
||||
unserialize($string);
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
195
app/Console/Commands/EnvironmentSetCommand.php
Normal file
195
app/Console/Commands/EnvironmentSetCommand.php
Normal file
@@ -0,0 +1,195 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
|
||||
class EnvironmentSetCommand extends Command
|
||||
{
|
||||
public const COMMAND_NAME = 'env:set';
|
||||
|
||||
public const ARGUMENT_KEY = 'key';
|
||||
|
||||
public const ARGUMENT_VALUE = 'value';
|
||||
|
||||
public const ARGUMENT_ENV_FILE = 'env_file';
|
||||
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature
|
||||
= self::COMMAND_NAME
|
||||
.' {'.self::ARGUMENT_KEY.' : Key or "key=value" pair}'
|
||||
.' {'.self::ARGUMENT_VALUE.'? : Value}'
|
||||
.' {'.self::ARGUMENT_ENV_FILE.'? : Optional path to the .env file}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Set and save an environment variable in the .env file';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): void
|
||||
{
|
||||
try {
|
||||
// Parse key and value arguments.
|
||||
[$key, $value, $envFilePath] = $this->parseCommandArguments(
|
||||
$this->argument(self::ARGUMENT_KEY),
|
||||
$this->argument(self::ARGUMENT_VALUE),
|
||||
$this->argument(self::ARGUMENT_ENV_FILE)
|
||||
);
|
||||
|
||||
// Use system env file path if the argument env file path is not provided.
|
||||
$envFilePath = $envFilePath ?? App::environmentFilePath();
|
||||
$this->info("The following environment file is used: '".$envFilePath."'");
|
||||
} catch (InvalidArgumentException $e) {
|
||||
$this->error($e->getMessage());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$content = file_get_contents($envFilePath);
|
||||
[$newEnvFileContent, $isNewVariableSet] = $this->setEnvVariable($content, $key, $value);
|
||||
|
||||
if ($isNewVariableSet) {
|
||||
$this->info("A new environment variable with key '{$key}' has been set to '{$value}'");
|
||||
} else {
|
||||
[$_, $oldValue] = explode('=', $this->readKeyValuePair($content, $key), 2);
|
||||
$this->info("Environment variable with key '{$key}' has been changed from '{$oldValue}' to '{$value}'");
|
||||
}
|
||||
|
||||
$this->writeFile($envFilePath, $newEnvFileContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set or update env-variable.
|
||||
*
|
||||
* @param string $envFileContent Content of the .env file.
|
||||
* @param string $key Name of the variable.
|
||||
* @param string $value Value of the variable.
|
||||
* @return array [string newEnvFileContent, bool isNewVariableSet].
|
||||
*/
|
||||
public function setEnvVariable(string $envFileContent, string $key, string $value): array
|
||||
{
|
||||
$oldPair = $this->readKeyValuePair($envFileContent, $key);
|
||||
|
||||
// Wrap values that have a space or equals in quotes to escape them
|
||||
if (preg_match('/\s/', $value) || strpos($value, '=') !== false) {
|
||||
$value = '"'.$value.'"';
|
||||
}
|
||||
|
||||
$newPair = $key.'='.$value;
|
||||
|
||||
// For existed key.
|
||||
if ($oldPair !== null) {
|
||||
$replaced = preg_replace('/^'.preg_quote($oldPair, '/').'$/uimU', $newPair, $envFileContent);
|
||||
|
||||
return [$replaced, false];
|
||||
}
|
||||
|
||||
// For a new key.
|
||||
return [$envFileContent."\n".$newPair."\n", true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the "key=value" string of a given key from an environment file.
|
||||
* This function returns original "key=value" string and doesn't modify it.
|
||||
*
|
||||
* @param string $envFileContent
|
||||
* @param string $key
|
||||
* @return string|null Key=value string or null if the key is not exists.
|
||||
*/
|
||||
public function readKeyValuePair(string $envFileContent, string $key): ?string
|
||||
{
|
||||
// Match the given key at the beginning of a line
|
||||
if (preg_match("#^ *{$key} *= *[^\r\n]*$#uimU", $envFileContent, $matches)) {
|
||||
return $matches[0];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse key, value and path to .env-file from command line arguments.
|
||||
*
|
||||
* @param string $_key
|
||||
* @param string|null $_value
|
||||
* @param string|null $_envFilePath
|
||||
* @return string[] [string KEY, string value, ?string envFilePath].
|
||||
*/
|
||||
public function parseCommandArguments(string $_key, ?string $_value, ?string $_envFilePath): array
|
||||
{
|
||||
$key = null;
|
||||
$value = null;
|
||||
$envFilePath = null;
|
||||
|
||||
// Parse "key=value" key argument.
|
||||
if (preg_match('#^([^=]+)=(.*)$#umU', $_key, $matches)) {
|
||||
[1 => $key, 2 => $value] = $matches;
|
||||
|
||||
// Use second argument as path to env file:
|
||||
if ($_value !== null) {
|
||||
$envFilePath = $_value;
|
||||
}
|
||||
} else {
|
||||
$key = $_key;
|
||||
$value = $_value;
|
||||
}
|
||||
|
||||
// If the path to env file is not set, use third argument or return null (default system path).
|
||||
if ($envFilePath === null) {
|
||||
$envFilePath = $_envFilePath;
|
||||
}
|
||||
|
||||
$this->assertKeyIsValid($key);
|
||||
|
||||
// If the value contains spaces but not is not enclosed in quotes.
|
||||
if (preg_match('#^[^\'"].*\s+.*[^\'"]$#umU', $value)) {
|
||||
$value = '"'.$value.'"';
|
||||
}
|
||||
|
||||
return [strtoupper($key), $value, ($envFilePath === null ? null : realpath($envFilePath))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert a given string is valid as an environment variable key.
|
||||
*
|
||||
* @param string $key
|
||||
* @return bool Is key is valid.
|
||||
*/
|
||||
public function assertKeyIsValid(string $key): bool
|
||||
{
|
||||
if (Str::contains($key, '=')) {
|
||||
throw new InvalidArgumentException('Invalid environment key '.$key
|
||||
."! Environment key should not contain '='");
|
||||
}
|
||||
|
||||
if (! preg_match('/^[a-zA-Z_]+$/', $key)) {
|
||||
throw new InvalidArgumentException('Invalid environment key '.$key
|
||||
.'! Only use letters and underscores');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrite the contents of a file.
|
||||
*
|
||||
* @param string $path
|
||||
* @param string $contents
|
||||
* @return bool
|
||||
*/
|
||||
protected function writeFile(string $path, string $contents): bool
|
||||
{
|
||||
return (bool) file_put_contents($path, $contents, LOCK_EX);
|
||||
}
|
||||
}
|
45
app/Console/Commands/MonitoredTaskSync.php
Normal file
45
app/Console/Commands/MonitoredTaskSync.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\MonitoredScheduledTasks;
|
||||
use App\Models\Task;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class MonitoredTaskSync extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:sync-tasks';
|
||||
|
||||
public $description = 'Sync the schedule of the app with the schedule monitor';
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$this->info('Syncing tasks...');
|
||||
|
||||
$this->syncScheduledTasksWithDatabase();
|
||||
|
||||
$monitoredScheduledTasksCount = MonitoredScheduledTasks::count();
|
||||
|
||||
$this->info('Syncing '.$monitoredScheduledTasksCount.' tasks...');
|
||||
}
|
||||
|
||||
protected function syncScheduledTasksWithDatabase(): self
|
||||
{
|
||||
$this->info('Start syncing schedule with database...');
|
||||
|
||||
$monitoredScheduledTasks = Task::all();
|
||||
foreach ($monitoredScheduledTasks as $task) {
|
||||
MonitoredScheduledTasks::updateOrCreate(
|
||||
['task_id' => $task->id],
|
||||
[
|
||||
'task_id' => $task->id,
|
||||
'name' => $task->task_name,
|
||||
'cron_expression' => implode(' ', $task->task_cron),
|
||||
'type' => $task->task_command,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
75
app/Console/Commands/purgeFailedConfigs.php
Normal file
75
app/Console/Commands/purgeFailedConfigs.php
Normal file
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Config;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class purgeFailedConfigs extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:purge-failedconfigs
|
||||
{deviceid?*}
|
||||
{--all}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Purge failed configs for some or all devices';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$deviceids = $this->argument('deviceid');
|
||||
$all = $this->option('all');
|
||||
|
||||
if (empty($deviceids) && $all === false) {
|
||||
$this->error('You must enter device IDs, or use the --all switch.');
|
||||
exit();
|
||||
}
|
||||
|
||||
if (empty($deviceids) && $all === true) {
|
||||
$configs = Config::where('download_status', '!=', 1)->orWhereNull('download_status')->get();
|
||||
} else {
|
||||
$configs = Config::whereIn('device_id', $deviceids)->where('download_status', '!=', 1)->orWhereNull('download_status')->get();
|
||||
}
|
||||
|
||||
if (count($configs) === 0) {
|
||||
$this->info('Nothing to purge! Thanks!');
|
||||
}
|
||||
|
||||
foreach ($configs as $config) {
|
||||
if ($config->config_location != null) {
|
||||
File::delete($config->config_location);
|
||||
}
|
||||
Config::destroy($config->id);
|
||||
}
|
||||
|
||||
$logmsg = count($configs) . ' invalid or failed configurations purged!';
|
||||
$this->info($logmsg);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'devices', '', '', 'config', $deviceids);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
86
app/Console/Commands/rConfigActivityLogArchive.php
Normal file
86
app/Console/Commands/rConfigActivityLogArchive.php
Normal file
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\ActivityLog;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rConfigActivityLogArchive extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:archive-logs {--days=*} {--rows=*}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Will archive x amount of activity log rows or days';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$days = $this->option('days');
|
||||
$rows = $this->option('rows');
|
||||
$logmsg = null;
|
||||
|
||||
if (empty($days) && empty($rows)) {
|
||||
$this->error('Must add options: --days=x or --rows=x');
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!empty($rows)) {
|
||||
$count = $rows;
|
||||
ActivityLog::all()->take($count[0])
|
||||
->each(function ($oldRecord) {
|
||||
$newRecord = $oldRecord->replicate();
|
||||
$newRecord['original_id'] = $oldRecord->id;
|
||||
$newRecord['original_created_at'] = $oldRecord->created_at; // convert to datetime object form mutated created_at
|
||||
$newRecord['original_updated_at'] = $oldRecord->updated_at;
|
||||
$newRecord->setTable('activity_log_archives');
|
||||
$newRecord->save();
|
||||
$oldRecord->delete();
|
||||
});
|
||||
$logmsg = $count[0] . ' logs entries sent to activity log archive table!';
|
||||
}
|
||||
|
||||
if (!empty($days)) {
|
||||
$count = $days;
|
||||
|
||||
ActivityLog::query()
|
||||
->where('created_at', '<=', now()->subDays($days[0])->toDateTimeString())->get()
|
||||
->each(function ($oldRecord) {
|
||||
$newRecord = $oldRecord->replicate();
|
||||
$newRecord['original_id'] = $oldRecord->id;
|
||||
$newRecord['original_created_at'] = $oldRecord->created_at; // convert to datetime object form mutated created_at
|
||||
$newRecord['original_updated_at'] = $oldRecord->updated_at;
|
||||
$newRecord->setTable('activity_log_archives');
|
||||
$newRecord->save();
|
||||
$oldRecord->delete();
|
||||
});
|
||||
$logmsg = 'logs older than ' . $count[0] . ' days sent to activity log archive table';
|
||||
}
|
||||
|
||||
$this->info($logmsg);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'logs', '', '', '', []);
|
||||
}
|
||||
}
|
51
app/Console/Commands/rConfigClearHorizon.php
Normal file
51
app/Console/Commands/rConfigClearHorizon.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
class rConfigClearHorizon extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:clear-horizon';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Clear Horizon Queue History';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->call('queue:flush');
|
||||
$this->call('queue:restart');
|
||||
Redis::connection()
|
||||
->del([config('horizon.prefix').'failed:*']);
|
||||
$this->info('each individual failed job flushed');
|
||||
Redis::connection()
|
||||
->del([config('horizon.prefix').'failed_jobs']);
|
||||
$this->info('failed_jobs flushed');
|
||||
Redis::command('flushdb');
|
||||
}
|
||||
}
|
51
app/Console/Commands/rConfigCloneTemplates.php
Normal file
51
app/Console/Commands/rConfigCloneTemplates.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class rConfigCloneTemplates extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:clone-templates';
|
||||
|
||||
protected $hidden = true;
|
||||
|
||||
protected $description = 'Clone templates from git repo https://github.com/rconfig/rconfig-templates';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$dstDir = templates_path().'rConfig-templates';
|
||||
|
||||
if (is_dir($dstDir)) {
|
||||
File::deleteDirectory($dstDir);
|
||||
}
|
||||
|
||||
if (! is_dir($dstDir)) {
|
||||
mkdir($dstDir);
|
||||
$gitCmd = 'git -C '.templates_path().' clone https://github.com/rconfig/rConfig-templates.git';
|
||||
// dd($gitCmd);
|
||||
exec($gitCmd);
|
||||
|
||||
if (count(File::allFiles($dstDir))) {
|
||||
$msg = 'Clone from https://github.com/rconfig/rconfig-templates successful!';
|
||||
$this->info($msg);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $msg, 'clone');
|
||||
} else {
|
||||
$msg = 'Clone from https://github.com/rconfig/rconfig-templates unsuccessful! Check the application logs!';
|
||||
$this->error($msg);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $msg, 'clone');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
61
app/Console/Commands/rConfigReportLastDownload.php
Normal file
61
app/Console/Commands/rConfigReportLastDownload.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Config;
|
||||
use App\Models\Device;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rConfigReportLastDownload extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:report-lastDownload';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Output report of all devices latest downloaded configs';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$devices = Device::select('id', 'device_name', 'device_ip')->orderBy('id', 'asc')->get();
|
||||
|
||||
$collection = collect();
|
||||
foreach ($devices as $key => $value) {
|
||||
$uniqueCommandsCount = Config::select('command')->where('device_id', $value->id)->distinct('command')->count();
|
||||
$collection->push(Config::all()->where('device_id', $value->id)->sortByDesc('created_at')->take($uniqueCommandsCount));
|
||||
}
|
||||
|
||||
$flattenedCollection = $collection->flatten();
|
||||
$dataOutput = collect();
|
||||
foreach ($flattenedCollection as $key => $value) {
|
||||
$dataOutput->push($value->only('id', 'device_id', 'device_name', 'device_category', 'command', 'config_filesize', 'created_at'));
|
||||
}
|
||||
|
||||
$headers = ['ID', 'DEVICE ID', 'DEVICE_NAME', 'CATEGORY', 'COMMAND', 'FILE SZIE', 'CREATED DATE'];
|
||||
|
||||
$this->info('Results for Latest Configs List:');
|
||||
$this->table($headers, $dataOutput);
|
||||
}
|
||||
}
|
75
app/Console/Commands/rconfigCatDownload.php
Normal file
75
app/Console/Commands/rconfigCatDownload.php
Normal file
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\CustomClasses\DeviceDownloadClass;
|
||||
use App\CustomClasses\FilterArgsForCommnds;
|
||||
use App\CustomClasses\GetAndCheckCategoryIds;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigCatDownload extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:download-category
|
||||
{catid*}
|
||||
{--d|debug : rConfig debugging output}';
|
||||
|
||||
protected $eventtype = 'rconfig:download-category';
|
||||
|
||||
protected $description = 'Download configurations for one or multiple categories of devices';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
// get ids from command
|
||||
$ids = (new FilterArgsForCommnds)->filterArgs($this->argument('catid'));
|
||||
$debug = $this->option('debug');
|
||||
|
||||
$this->info('Start ' . $this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
|
||||
$logmsg = 'CLI Download Started for ' . ($this->eventtype . 'IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
// get the records from the DB
|
||||
$categoryrecords = (new GetAndCheckCategoryIds($ids))->GetCategoryRecords();
|
||||
|
||||
// error if none returned
|
||||
if (count($categoryrecords) === 0) {
|
||||
$this->info('No category records returned. Download will now terminate!');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($categoryrecords as $categoryrecord) {
|
||||
// error if none returned
|
||||
if (count($categoryrecord->device) === 0) {
|
||||
$this->error('No devices returned for this category with ID: ' . $categoryrecord->id . '. Downloader will try next category in the list, or terminate!');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// run the DeviceDownloadClass for all devices, and print output to this classes output
|
||||
$output = (new DeviceDownloadClass($categoryrecord->device, $this->eventtype, $debug))->downloadDevices();
|
||||
foreach ($output as $output_type => $values) {
|
||||
// $key == info or error
|
||||
foreach ($values as $key1 => $value1) {
|
||||
$this->$output_type($value1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isDocker()) {
|
||||
if (app()->runningInConsole()) {
|
||||
custom_chown(storage_path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$logmsg = 'CLI Download ended for ' . ($this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
$this->info('End ' . $this->eventtype . '');
|
||||
}
|
||||
}
|
47
app/Console/Commands/rconfigCatList.php
Normal file
47
app/Console/Commands/rconfigCatList.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Category;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigCatList extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:list-categories';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'List all category IDs and names in rConfig';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$headers = ['ID', 'CATEGORY NAME'];
|
||||
$items = Category::select('id', 'categoryName')->orderBy('id', 'asc')->get();
|
||||
$data = $items->toArray();
|
||||
$this->info('Results for Categories List:');
|
||||
$this->table($headers, $data);
|
||||
}
|
||||
}
|
79
app/Console/Commands/rconfigClearAll.php
Normal file
79
app/Console/Commands/rconfigClearAll.php
Normal file
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Artisan;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigClearAll extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:clear-all {--npm : Include NPM Clear out}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Clear all cache and config elements for Laravel, NPM and other dependencies';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$this->info(' ------ Begin rConfig Laravel Clear Out! ------');
|
||||
// echo exec('printf "hello\nworld\n"');
|
||||
// echo exec('echo -e "This is line 1\r\nThis is line 2"');
|
||||
Artisan::call('config:clear');
|
||||
$this->info('------ Config Cleared! ------');
|
||||
Artisan::call('cache:clear');
|
||||
$this->info('------ Cache Cleared! ------');
|
||||
Artisan::call('route:clear');
|
||||
$this->info('------ Routes Cleared! ------');
|
||||
Artisan::call('view:clear');
|
||||
$this->info('------ Views Cleared! ------');
|
||||
Artisan::call('config:cache');
|
||||
$this->info('------ Config Cached! ------');
|
||||
Artisan::call('route:cache');
|
||||
$this->info('------ Routes Cached! ------');
|
||||
Artisan::call('view:cache');
|
||||
$this->info('------ Views Cached! ------');
|
||||
Artisan::call('optimize');
|
||||
$this->info('------ Optimized! ------');
|
||||
Artisan::call('queue:restart');
|
||||
$this->info('------ Queues Restarted! ------');
|
||||
|
||||
if (!getenv('IS_DOCKER')) {
|
||||
echo exec('sudo supervisorctl update') . PHP_EOL;
|
||||
echo exec('sudo supervisorctl reread') . PHP_EOL;
|
||||
echo exec('if [ -f /etc/redhat-release ]; then systemctl restart supervisord; fi;') . PHP_EOL;
|
||||
echo exec('if [ -f /etc/lsb-release ]; then systemctl restart supervisor; fi;') . PHP_EOL;
|
||||
|
||||
custom_chown(rconfig_appdir_path());
|
||||
}
|
||||
if ( getenv('IS_DOCKER') === "true") {
|
||||
chmod('/var/www/html/storage', 0777);
|
||||
}
|
||||
|
||||
$this->info('------ Permissions Updated! ------');
|
||||
echo exec('composer dump-autoload') . PHP_EOL;
|
||||
$this->info(config('app.name') . ' application settings have been cleared!');
|
||||
}
|
||||
}
|
65
app/Console/Commands/rconfigDeviceDownload.php
Normal file
65
app/Console/Commands/rconfigDeviceDownload.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\CustomClasses\DeviceDownloadClass;
|
||||
use App\CustomClasses\FilterArgsForCommnds;
|
||||
use App\CustomClasses\GetAndCheckDeviceIds;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigDeviceDownload extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:download-device
|
||||
{deviceid*}
|
||||
{--d|debug : rConfig debugging output}';
|
||||
|
||||
protected $eventtype = 'rconfig:download-device';
|
||||
|
||||
protected $description = 'Download configurations for one or multiple devices via the CLI';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
// get ids from command
|
||||
$ids = (new FilterArgsForCommnds)->filterArgs($this->argument('deviceid'));
|
||||
$debug = $this->option('debug');
|
||||
|
||||
$this->info('Start ' . $this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
|
||||
$logmsg = 'CLI Download Started for ' . ($this->eventtype . 'IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
// get the records from the DB
|
||||
$this->devicerecords = (new GetAndCheckDeviceIds($ids))->GetDeviceRecords();
|
||||
|
||||
// error if none returned
|
||||
if (count($this->devicerecords) === 0) {
|
||||
$this->info('No device records returned. Download will now terminate!');
|
||||
|
||||
return;
|
||||
}
|
||||
// run the DeviceDownloadClass for all devices, and print output to this classes output
|
||||
$output = (new DeviceDownloadClass($this->devicerecords, $this->eventtype, $debug))->downloadDevices();
|
||||
foreach ($output as $output_type => $values) {
|
||||
// $key == info or error
|
||||
foreach ($values as $key1 => $value1) {
|
||||
$this->$output_type($value1);
|
||||
}
|
||||
}
|
||||
|
||||
$logmsg = 'CLI Download ended for ' . ($this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
$this->info('End ' . $this->eventtype . '');
|
||||
|
||||
if (!isDocker()) {
|
||||
if (app()->runningInConsole()) {
|
||||
custom_chown(storage_path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
47
app/Console/Commands/rconfigDeviceList.php
Normal file
47
app/Console/Commands/rconfigDeviceList.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Device;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigDeviceList extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:list-devices';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'List all tag IDs and names in rConfig';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$headers = ['ID', 'DEVICE NAME', 'DEVICE IP'];
|
||||
$items = Device::select('id', 'device_name', 'device_ip')->orderBy('id', 'asc')->get();
|
||||
$data = $items->toArray();
|
||||
$this->info('Results for Devices List:');
|
||||
$this->table($headers, $data);
|
||||
}
|
||||
}
|
97
app/Console/Commands/rconfigSearchConfigs.php
Normal file
97
app/Console/Commands/rconfigSearchConfigs.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\CustomClasses\ConfigSearch;
|
||||
use App\Models\Category;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigSearchConfigs extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:search-configs
|
||||
{Category : The Category of devices to search.}
|
||||
{SearchString : The search string. If searching multiple words, wrap in double-quotes.}
|
||||
{--lines=0 : Number of lines to display before/ after matches.}
|
||||
{--l : Include latest downloaded files in the search only}';
|
||||
|
||||
protected $description = 'Search all config files for a given string';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$arguments = $this->arguments();
|
||||
$options = $this->options();
|
||||
|
||||
$validCategories = \Cache::remember('search.categories', 604800, function () {
|
||||
return $this->getCategories();
|
||||
});
|
||||
|
||||
if (! in_array($arguments['Category'], $validCategories->toArray())) {
|
||||
$this->error('"'.$arguments['Category'].'" is an invalid category!');
|
||||
$this->error('You can check valid categories by running "php artisan rconfig:list-categories"');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! is_numeric($options['lines'])) {
|
||||
$this->error('Invalid lines input');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$results = (new ConfigSearch($arguments['Category'], $arguments['SearchString'], $options['lines'], $options['l']))->search();
|
||||
|
||||
if (empty($results['search_results'])) {
|
||||
$this->error('No results returned. Refine your search parameters!');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($results['search_results'] as $key => $result) {
|
||||
$this->info($result);
|
||||
}
|
||||
$this->error('Duration: '.$results['duration']);
|
||||
$this->error('Line Count: '.$results['lineCount']);
|
||||
$this->error('Match Count: '.$results['matchCount']);
|
||||
$this->error('File Count: '.$results['fileCount']);
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
private function getCategories()
|
||||
{
|
||||
return Category::all()->pluck('categoryName');
|
||||
}
|
||||
}
|
||||
|
||||
// $command = "find storage/app/rconfig/data/Routers/router1/ -type f -exec grep -n " . escapeshellarg($arguments['SearchString']) ." /dev/null {} +";
|
||||
// $command1 = 'find storage/app/rconfig/data/Routers/router1/ -name "showrun*" | xargs grep -il '.$grepNumLineStr.' ' . escapeshellarg($arguments['SearchString']) . '| while read file ; do echo File:"$file"; grep ' . $grepNumLineStr . ' ' . escapeshellarg($arguments['SearchString']) . ' "$file" ; done';
|
||||
// $command2 = "find storage/app/rconfig/data/Routers/router1/ -type f | xargs grep -n -h -C2 ".escapeshellarg($arguments['SearchString'])."";
|
||||
// $command3 = "find storage/app/rconfig/data/Routers/router1/ -type f | xargs grep -n -C2 ".escapeshellarg($arguments['SearchString'])."";
|
||||
// $command4 = 'find storage/app/rconfig/data/Routers/router1/ -type f | xargs grep -n -C4 '.escapeshellarg($arguments['SearchString']).' | while read file ; do echo File:"$file"; grep ' . $grepNumLineStr . ' ' . escapeshellarg($arguments['SearchString']) . ' "$file" ; done';
|
||||
// $countMatches = "find storage/app/rconfig/data/Routers/router1/ -type f -printf 'echo \"$(grep -o \"ha\" %p | wc -l) %p\";' | sh";
|
||||
|
||||
// //SilverSearcher
|
||||
// $ag1 = "ag -c ".escapeshellarg($arguments['SearchString'])." storage/app/rconfig/data/Routers/router1";
|
||||
// $ag2 = "ag -c ".escapeshellarg($arguments['SearchString'])." storage/app/rconfig/data/Routers/router1 --stats";
|
||||
// $ag3 = "ag -c -t ".escapeshellarg($arguments['SearchString'])." storage/app/rconfig/data/Routers/router1 --column";
|
||||
// $ag4 = 'ag -il '.escapeshellarg($arguments['SearchString']).' storage/app/rconfig/data/Routers/router1 --stats | while read file ; do echo File:"$file"; grep ' . $grepNumLineStr . ' ' . escapeshellarg($arguments['SearchString']) . ' "$file" ; done';
|
||||
// // $countMatches = 'grep -o '.escapeshellarg($arguments['SearchString']).' storage/app/rconfig/data/Routers/router1/ | wc -l';
|
||||
// $ag5 = "ag ".escapeshellarg($arguments['SearchString'])." storage/app/rconfig/data/Routers/router1 | xargs cat file | while read line ; do grep -lr ". escapeshellarg($arguments['SearchString']) ." * ; done";
|
||||
|
||||
// $awkcommand1 = "find storage/app/rconfig/data/Routers/router1/ -type f | xargs grep -n ".escapeshellarg($arguments['SearchString']). " | awk -f search.awk";
|
||||
//next find all instances of the search term under the specific cat/dir
|
||||
// $command = 'find /home/rconfig/data' . $subDir . escapeshellarg($nodeId) . ' -name ' . escapeshellarg($catCommand) . ' | xargs grep -il ' . $grepNumLineStr . ' ' . $searchTerm . ' | while read file ; do echo File:"$file"; grep ' . $grepNumLineStr . ' ' . $searchTerm . ' "$file" ; done';
|
||||
// // echo $command;die();
|
||||
// exec(escapeshellarg($command), $searchArr);
|
||||
|
||||
// dd(escapeshellcmd($arguments['SearchString']));
|
||||
// $headers = ['ID', 'DEVICE NAME', 'DEVICE IP'];
|
||||
// $items = Device::select('id', 'device_name', 'device_ip')->orderBy('id', 'asc')->get();
|
||||
// $data = $items->toArray();
|
||||
// $this->info('Results for Devices List:');
|
||||
// $this->table($headers, $data);
|
75
app/Console/Commands/rconfigTagDownload.php
Normal file
75
app/Console/Commands/rconfigTagDownload.php
Normal file
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\CustomClasses\DeviceDownloadClass;
|
||||
use App\CustomClasses\FilterArgsForCommnds;
|
||||
use App\CustomClasses\GetAndCheckTagIds;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigTagDownload extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:download-tag
|
||||
{tagid*}
|
||||
{--d|debug : rConfig debugging output}';
|
||||
|
||||
protected $eventtype = 'rconfig:download-tag';
|
||||
|
||||
protected $description = 'Download configurations for devices with one or multiple tags';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
// get ids from command
|
||||
$ids = (new FilterArgsForCommnds)->filterArgs($this->argument('tagid'));
|
||||
$debug = $this->option('debug');
|
||||
|
||||
$this->info('Start ' . $this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
|
||||
$logmsg = 'CLI Download Started for ' . ($this->eventtype . 'IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
// get the records from the DB
|
||||
$tagrecords = (new GetAndCheckTagIds($ids))->GetTagRecords();
|
||||
|
||||
// error if none returned
|
||||
if (count($tagrecords) === 0) {
|
||||
$this->info('No tag records returned. Download will now terminate!');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($tagrecords as $tagrecord) {
|
||||
// error if none returned
|
||||
if (count($tagrecord->device) === 0) {
|
||||
$this->error('No devices returned for this category with ID: ' . $tagrecord->id . '. Downloader will try next category in the list, or terminate!');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// run the DeviceDownloadClass for all devices, and print console output to this classes console output
|
||||
$output = (new DeviceDownloadClass($tagrecord->device, $this->eventtype, $debug))->downloadDevices();
|
||||
foreach ($output as $output_type => $values) {
|
||||
// $key == info or error
|
||||
foreach ($values as $key1 => $value1) {
|
||||
$this->$output_type($value1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isDocker()) {
|
||||
if (app()->runningInConsole()) {
|
||||
custom_chown(storage_path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$logmsg = 'CLI Download ended for ' . ($this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
$this->info('End ' . $this->eventtype . '');
|
||||
}
|
||||
}
|
47
app/Console/Commands/rconfigTagList.php
Normal file
47
app/Console/Commands/rconfigTagList.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tag;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigTagList extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:list-tags';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'List all tag IDs and names in rConfig';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$headers = ['ID', 'TAGNAME'];
|
||||
$items = Tag::select('id', 'tagname')->orderBy('id', 'asc')->get();
|
||||
$data = $items->toArray();
|
||||
$this->info('Results for Tags List:');
|
||||
$this->table($headers, $data);
|
||||
}
|
||||
}
|
236
app/Console/Commands/rconfigTaskDownload.php
Normal file
236
app/Console/Commands/rconfigTaskDownload.php
Normal file
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\CustomClasses\DeviceDownloadClass;
|
||||
use App\CustomClasses\FilterArgsForCommnds;
|
||||
use App\CustomClasses\GetAndCheckCategoryIds;
|
||||
use App\CustomClasses\GetAndCheckDeviceIds;
|
||||
use App\CustomClasses\GetAndCheckTagIds;
|
||||
use App\CustomClasses\GetAndCheckTaskIds;
|
||||
use App\Jobs\DeviceDownloadJob;
|
||||
use App\Jobs\SendTaskReportNotificationJob;
|
||||
use App\Jobs\TaskCompleteNotificationJob;
|
||||
use App\Jobs\TaskReportJob;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Bus\Batch;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class rconfigTaskDownload extends Command
|
||||
{
|
||||
protected $signature = 'rconfig:download-task
|
||||
{taskid*}
|
||||
{--d|debug : rConfig debugging output}';
|
||||
|
||||
protected $eventtype = 'rconfig:download-task';
|
||||
|
||||
protected $description = 'Download configurations for devices with one or multiple tasks';
|
||||
|
||||
protected $report_data;
|
||||
|
||||
protected $devicerecords;
|
||||
|
||||
protected $debug;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$this->error('This operation can take some time, depending on how many devices are configured for this task!!!');
|
||||
|
||||
// get ids from command
|
||||
$ids = (new FilterArgsForCommnds)->filterArgs($this->argument('taskid'));
|
||||
$this->debug = $this->option('debug');
|
||||
|
||||
$this->info('Start ' . $this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
|
||||
$logmsg = 'CLI Download Started for ' . ($this->eventtype . 'IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
$tasks = (new GetAndCheckTaskIds($ids))->GetTaskRecords();
|
||||
|
||||
// error if none returned
|
||||
if (count($tasks) === 0) {
|
||||
$this->info('No task records returned. Download will now terminate!');
|
||||
|
||||
return;
|
||||
}
|
||||
$this->report_data = collect();
|
||||
foreach ($tasks as $task) {
|
||||
|
||||
$this->report_data->report_id = (string) Str::uuid();
|
||||
$this->report_data->task_type = 'Task Download Report';
|
||||
$this->report_data->task = $task;
|
||||
$this->report_data->start_time = Carbon::now();
|
||||
|
||||
//CATEGORY BELOW HERE
|
||||
if ($task->category->count() > 0) {
|
||||
$categoryrecords = (new GetAndCheckCategoryIds($task->category->pluck('id')->toArray()))->GetCategoryRecords();
|
||||
|
||||
if (!$this->checkRecordCount(count($categoryrecords))) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($categoryrecords as $categoryrecord) {
|
||||
$this->devicerecords = $categoryrecord->device;
|
||||
if ($this->debug) {
|
||||
$this->runDeviceManualJobs();
|
||||
} else {
|
||||
$this->runDeviceBatchJob($task->task_name, 'Category: ' . $categoryrecord->categoryName . ' [' . $categoryrecord->id . ']');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//TAGS BELOW HERE
|
||||
if ($task->tag->count() > 0) {
|
||||
$tagrecords = (new GetAndCheckTagIds($task->tag->pluck('id')->toArray()))->GetTagRecords();
|
||||
if (!$this->checkRecordCount(count($tagrecords))) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($tagrecords as $tagrecord) {
|
||||
$this->devicerecords = $tagrecord->device;
|
||||
if ($this->debug) {
|
||||
$this->runDeviceManualJobs();
|
||||
} else {
|
||||
$this->runDeviceBatchJob($task->task_name, 'Tag: ' . $tagrecord->tagname . ' [' . $tagrecord->id . ']');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//DEVICES BELOW HERE
|
||||
if ($task->device->count() > 0) {
|
||||
$this->devicerecords = (new GetAndCheckDeviceIds($task->device->pluck('id')->toArray()))->GetDeviceRecords();
|
||||
if (!$this->checkRecordCount(count($this->devicerecords))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->debug) {
|
||||
$this->runDeviceManualJobs();
|
||||
} else {
|
||||
$this->runDeviceBatchJob($task->task_name, 'Devices [Count: ' . $task->device->count() . ']');
|
||||
}
|
||||
}
|
||||
|
||||
if (!isDocker()) {
|
||||
if (app()->runningInConsole()) {
|
||||
custom_chown(storage_path());
|
||||
}
|
||||
}
|
||||
|
||||
$this->create_report();
|
||||
|
||||
$logmsg = 'CLI Download ended for ' . ($this->eventtype . ' IDs:' . implode(' ', $ids));
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype, $ids);
|
||||
|
||||
$this->info('');
|
||||
$this->info('End ' . $this->eventtype . '');
|
||||
}
|
||||
}
|
||||
|
||||
private function runDeviceManualJobs()
|
||||
{
|
||||
$output = (new DeviceDownloadClass($this->devicerecords, $this->eventtype, $this->debug, $this->report_data->report_id))->downloadDevices();
|
||||
foreach ($output as $output_type => $values) {
|
||||
foreach ($values as $key1 => $value1) {
|
||||
$this->$output_type($value1); // cli output type and value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function runDeviceBatchJob($taskname, $jobname = '')
|
||||
{
|
||||
|
||||
$jobs = [];
|
||||
foreach ($this->devicerecords as $devicerecord) {
|
||||
|
||||
$jobs[] = new DeviceDownloadJob($devicerecord, $this->eventtype, $this->debug, $this->report_data->report_id);
|
||||
}
|
||||
|
||||
$batch = Bus::batch($jobs)->then(function (Batch $batch) {
|
||||
// All jobs completed successfully...
|
||||
$msg = 'Batch [' . $batch->id . ']/[' . $batch->name . '] has been finished successfully';
|
||||
info($msg);
|
||||
activity('info')->log($msg);
|
||||
})->catch(function (Batch $batch, \Throwable $e) {
|
||||
// First batch job failure detected...
|
||||
$msg = 'Batch [' . $batch->id . ']/[' . $batch->name . '] failed to process all jobs';
|
||||
info($msg);
|
||||
activity('error')->log($msg);
|
||||
activity('error')->log($e->getMessage());
|
||||
})->finally(function (Batch $batch) {
|
||||
// The batch has finished executing...
|
||||
$msg = 'Batch [' . $batch->id . ']/[' . $batch->name . '] finished processing';
|
||||
info($msg);
|
||||
activity('info')->log($msg);
|
||||
DB::table('job_batches')->where('id', $batch->id)->update(['finished_at' => now()->timestamp]); // need this as allowFailures( does not write finished_at)
|
||||
})->name('Process TestBatchJob')
|
||||
->allowFailures()
|
||||
->onQueue('downloadqueue')
|
||||
->name('download-task: ' . $taskname . ' (' . $jobname . ')')
|
||||
->dispatch();
|
||||
|
||||
$progress = $this->output->createProgressBar(100);
|
||||
$this->info('Total device download jobs: ' . $batch->totalJobs);
|
||||
$this->info('');
|
||||
|
||||
if (!\App::runningUnitTests()) {
|
||||
while (($batch = $batch->fresh()) && !$batch->finished()) {
|
||||
// dump('Pending: ' . $batch->pendingJobs);
|
||||
// dump('Status: ' . $batch->finished());
|
||||
$progress->setProgress($batch->progress());
|
||||
sleep(3);
|
||||
}
|
||||
}
|
||||
|
||||
$progress->finish();
|
||||
$this->info('');
|
||||
}
|
||||
|
||||
private function create_report()
|
||||
{
|
||||
|
||||
activity('info')->log('Creating report for ' . $this->report_data->task->task_name);
|
||||
$this->report_data->end_time = Carbon::now();
|
||||
$this->report_data->file_name = $this->report_data->report_id . '.html';
|
||||
$this->report_data->report_path = report_path() . $this->report_data->file_name;
|
||||
|
||||
if (App::runningUnitTests()) { // required for testing
|
||||
dispatch(new TaskReportJob($this->report_data))->onConnection('sync');
|
||||
} else {
|
||||
dispatch(new TaskReportJob($this->report_data));
|
||||
}
|
||||
|
||||
if ($this->report_data->task->task_email_notify == 1) {
|
||||
dispatch(new TaskCompleteNotificationJob($this->report_data));
|
||||
}
|
||||
|
||||
if ($this->report_data->task->download_report_notify == 1) {
|
||||
\Log::info('Sending report notification: SendTaskReportNotificationJob');
|
||||
dispatch(new SendTaskReportNotificationJob($this->report_data));
|
||||
}
|
||||
|
||||
activity('info')->log('Report completed for ' . $this->report_data->task->task_name);
|
||||
}
|
||||
|
||||
private function checkRecordCount($count)
|
||||
{
|
||||
$status = true;
|
||||
if ($count === 0) {
|
||||
$logmsg = 'No category/ task or tag records returned. Download will now terminate!';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'connection', '', '', $this->eventtype);
|
||||
$this->info($logmsg);
|
||||
$status = false;
|
||||
}
|
||||
|
||||
return $status;
|
||||
}
|
||||
}
|
47
app/Console/Commands/rconfigTaskList.php
Normal file
47
app/Console/Commands/rconfigTaskList.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Task;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class rconfigTaskList extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'rconfig:list-tasks';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'List all task IDs and names in rConfig';
|
||||
|
||||
/**
|
||||
* Create a new command instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$headers = ['ID', 'NAME', 'DESCRIPTION'];
|
||||
$items = Task::select('id', 'task_name', 'task_desc')->orderBy('id', 'asc')->get();
|
||||
$data = $items->map->only('id', 'task_name', 'task_desc')->toArray();
|
||||
$this->info('Results for Tasks List:');
|
||||
$this->table($headers, $data);
|
||||
}
|
||||
}
|
123
app/Console/Kernel.php
Normal file
123
app/Console/Kernel.php
Normal file
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use App\Models\Task;
|
||||
use App\Traits\LogsTaskActivity;
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Spatie\Health\Commands\RunHealthChecksCommand;
|
||||
use Spatie\Health\Commands\ScheduleCheckHeartbeatCommand;
|
||||
|
||||
class Kernel extends ConsoleKernel
|
||||
{
|
||||
use LogsTaskActivity;
|
||||
|
||||
protected $schedule;
|
||||
|
||||
/**
|
||||
* The Artisan commands provided by your application.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $commands = [
|
||||
Commands\rconfigTagList::class,
|
||||
Commands\rconfigTagDownload::class,
|
||||
Commands\rconfigCatList::class,
|
||||
Commands\rconfigCatDownload::class,
|
||||
Commands\rconfigDeviceList::class,
|
||||
Commands\rconfigDeviceDownload::class,
|
||||
Commands\rconfigTaskList::class,
|
||||
Commands\rconfigTaskDownload::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*
|
||||
* @param \Illuminate\Console\Scheduling\Schedule $schedule
|
||||
* @return void
|
||||
*/
|
||||
protected function schedule(Schedule $schedule)
|
||||
{
|
||||
$this->schedule = $schedule;
|
||||
//running this to fix logging permissions issue every day in case of issues
|
||||
$this->schedule->exec('chown -R apache /var/www/html')
|
||||
->dailyAt('8:00')
|
||||
->after(function () {
|
||||
$logmsg = 'Exec Command chown -R apache was run on html dir';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'cron_scheduler');
|
||||
});
|
||||
|
||||
if (Schema::hasTable('tasks')) {
|
||||
// Get all tasks from the database
|
||||
$tasks = Task::all();
|
||||
|
||||
// Go through each task to dynamically set them up.
|
||||
foreach ($tasks as $task) {
|
||||
// Use the scheduler to add the task at its desired frequency
|
||||
$executionStartTime = microtime(true);
|
||||
if ($task->task_command === 'rconfig:purge-configs') {
|
||||
$this->purge_configs($executionStartTime, $task);
|
||||
} else {
|
||||
// everything other than backup jobs
|
||||
$this->download_task($executionStartTime, $task);
|
||||
}
|
||||
// exec('chown -R apache /var/www/html');
|
||||
}
|
||||
}
|
||||
|
||||
$schedule->command(RunHealthChecksCommand::class)->everyFiveMinutes();
|
||||
$schedule->command(ScheduleCheckHeartbeatCommand::class)->everyFiveMinutes();
|
||||
$schedule->command('queue:prune-batches --hours=48 --unfinished=72')->daily();
|
||||
$schedule->command('model:prune', ['--model' => MonitoredScheduledTaskLogItem::class])->daily();
|
||||
$schedule->command('model:prune', ['--model' => \Spatie\Health\Models\HealthCheckResultHistoryItem::class])->daily();
|
||||
}
|
||||
|
||||
private function download_task($executionStartTime, $task)
|
||||
{
|
||||
// Tasks Commands are stored in DB as the items in the $download_commands array. But they actually need to run as rconfig:download:task
|
||||
// Next transforms the $download_commands, to download-task commands. - Bit Hacky
|
||||
$download_commands = ['rconfig:download-device', 'rconfig:download-tag', 'rconfig:download-category'];
|
||||
if (in_array($task->task_command, $download_commands)) {
|
||||
$task->task_command = 'rconfig:download-task';
|
||||
}
|
||||
$this->schedule->command($task->task_command . ' ' . $task->id)
|
||||
->cron(implode(' ', $task->task_cron))
|
||||
->before(function () use ($task) {
|
||||
$this->logTaskStarted($task->id);
|
||||
})
|
||||
->appendOutputTo(storage_path() . '/logs/laravel.log')
|
||||
->after(function () use ($task, $executionStartTime) {
|
||||
$logmsg = 'Task command "' . $task->task_command . ' ' . $task->id . '" was run with ID:' . $task->id;
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'cron_scheduler');
|
||||
$this->logTaskFinished($task->id);
|
||||
});
|
||||
}
|
||||
|
||||
private function afterTaskRunActions($task, $executionStartTime)
|
||||
{
|
||||
$logmsg = 'Task command "' . $task->task_command . ' ' . $task->id . '" was run with ID:' . $task->id;
|
||||
$this->logTaskFinished($task->id);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'cron_scheduler');
|
||||
}
|
||||
|
||||
private function onTaskFailureActions($task, $executionStartTime)
|
||||
{
|
||||
$logmsg = 'Task command "' . $task->task_command . ' ' . $task->id . '" failed. See logs for more information.';
|
||||
$this->logTaskFailed($task->id);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'cron_scheduler');
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function commands()
|
||||
{
|
||||
$this->load(__DIR__ . '/Commands');
|
||||
|
||||
require base_path('routes/console.php');
|
||||
}
|
||||
}
|
104
app/CustomClasses/ConfigSearch.php
Normal file
104
app/CustomClasses/ConfigSearch.php
Normal file
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Category;
|
||||
use App\Models\Config;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ConfigSearch
|
||||
{
|
||||
protected $categoryId;
|
||||
|
||||
protected $categoryName;
|
||||
|
||||
protected $string;
|
||||
|
||||
protected $linecount;
|
||||
|
||||
protected $latestOnly;
|
||||
|
||||
public function __construct($categoryId, $string, $linecount, $latestOnly)
|
||||
{
|
||||
$this->categoryId = $categoryId;
|
||||
$this->string = $string;
|
||||
$this->linecount = $linecount;
|
||||
$this->latestOnly = isset($latestOnly) ? $latestOnly : false;
|
||||
}
|
||||
|
||||
public function search()
|
||||
{
|
||||
$results = null;
|
||||
if ($this->latestOnly === false) {
|
||||
$results = $this->globalSearch();
|
||||
} elseif ($this->latestOnly === true) {
|
||||
$results = $this->latestSearch();
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
private function latestSearch()
|
||||
{
|
||||
$this->categoryName = Category::where('id', $this->categoryId)->first()->categoryName;
|
||||
$deviceIdsForGivenCat = Config::where('device_category', $this->categoryName)->distinct()->pluck('device_id');
|
||||
|
||||
$latestConfigsArray = [];
|
||||
foreach ($deviceIdsForGivenCat as $device) {
|
||||
$created_at = DB::table('configs')->where('device_id', $device)->max('created_at');
|
||||
$latestConfigsArray[] = Config::where('created_at', $created_at)->get();
|
||||
}
|
||||
$latestConfigsArray = Arr::flatten($latestConfigsArray);
|
||||
|
||||
$allResultsArr = [];
|
||||
$matchCount = 0;
|
||||
foreach ($latestConfigsArray as $latestConfigItem) {
|
||||
$grepSearchCommand = 'grep '.escapeshellarg($this->string).' '.$latestConfigItem->config_location.' -C'.$this->linecount;
|
||||
exec($grepSearchCommand, $searchresults);
|
||||
//$searchresults0 & 1 are intended to mimic the output from the $searchresults arary in the globalSearch func
|
||||
if (! empty($searchresults)) {
|
||||
array_unshift($searchresults, '', '-::'.$latestConfigItem->config_location.'::-'); // move these to the top of the array
|
||||
$allResultsArr[] = $searchresults;
|
||||
$matchCount++;
|
||||
}
|
||||
unset($searchresults);
|
||||
}
|
||||
|
||||
$allResultsArr = Arr::flatten($allResultsArr);
|
||||
|
||||
$results = [];
|
||||
$start_time = Carbon::now();
|
||||
$results['lineCount'] = count($allResultsArr); // take away duration & linecount keys
|
||||
$results['matchCount'] = $matchCount;
|
||||
|
||||
$results['fileCount'] = $matchCount;
|
||||
$end_time = Carbon::now();
|
||||
$results['duration'] = $start_time->diffInMilliseconds($end_time).'ms';
|
||||
$results['search_results'] = $allResultsArr;
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
public function globalSearch()
|
||||
{
|
||||
$awkSearchCommand = 'find '.config_data_path().$this->categoryName.' -type f -name "*.txt" | xargs grep -n -C'.$this->linecount.' '.escapeshellarg($this->string).' | awk -f '.rconfig_app_path().'search.awk';
|
||||
|
||||
$totalMatchesCommand = 'grep -ro '.escapeshellarg($this->string).' '.config_data_path().'/ | wc -l ';
|
||||
$results = [];
|
||||
$start_time = Carbon::now();
|
||||
exec($awkSearchCommand, $searchresults);
|
||||
exec($totalMatchesCommand, $matchCount);
|
||||
$results['lineCount'] = count($searchresults); // take away duration & linecount keys
|
||||
$results['matchCount'] = (int) $matchCount[0]; // take away duration & linecount keys
|
||||
$results['fileCount'] = count(array_filter($searchresults, function ($v) {
|
||||
return substr($v, 0, 3) === '-::';
|
||||
}));
|
||||
$end_time = Carbon::now();
|
||||
$results['duration'] = $start_time->diffInMilliseconds($end_time).'ms';
|
||||
$results['search_results'] = $searchresults;
|
||||
|
||||
return $results;
|
||||
}
|
||||
}
|
40
app/CustomClasses/CreateTaskReport.php
Normal file
40
app/CustomClasses/CreateTaskReport.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Taskdownloadreport;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class CreateTaskReport
|
||||
{
|
||||
public $report_data;
|
||||
|
||||
public function __construct($report_data)
|
||||
{
|
||||
$this->report_data = $report_data;
|
||||
}
|
||||
|
||||
public function saveReport()
|
||||
{
|
||||
$this->report_data->duration = $this->report_data->end_time->diffInSeconds($this->report_data->start_time);
|
||||
|
||||
File::put(
|
||||
$this->report_data->report_path,
|
||||
view('report_templates.task_report')
|
||||
->with(['report_data' => $this->report_data])
|
||||
->render()
|
||||
);
|
||||
|
||||
$model = new Taskdownloadreport;
|
||||
$model->report_id = $this->report_data->report_id;
|
||||
$model->task_type = $this->report_data->task_type;
|
||||
$model->task_id = $this->report_data->task->id;
|
||||
$model->task_name = $this->report_data->task->task_name;
|
||||
$model->task_desc = $this->report_data->task->task_desc;
|
||||
$model->file_name = $this->report_data->file_name;
|
||||
$model->start_time = $this->report_data->start_time->toDateTimeString();
|
||||
$model->end_time = $this->report_data->end_time->toDateTimeString();
|
||||
$model->duration = $this->report_data->duration;
|
||||
$model->save();
|
||||
}
|
||||
}
|
1404
app/CustomClasses/CronSchedule.php
Normal file
1404
app/CustomClasses/CronSchedule.php
Normal file
File diff suppressed because it is too large
Load Diff
32
app/CustomClasses/Debug.php
Normal file
32
app/CustomClasses/Debug.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Setting;
|
||||
|
||||
class Debug
|
||||
{
|
||||
private $_debugState;
|
||||
|
||||
public function __construct($debugState = false)
|
||||
{
|
||||
$this->_debugState = $debugState;
|
||||
}
|
||||
|
||||
public function debugDump($message)
|
||||
{
|
||||
if (\Request::segment(1) == 'web') {
|
||||
return;
|
||||
} // no debug on web invokation
|
||||
|
||||
$debugging = Setting::find(1)->value('deviceDebugging');
|
||||
if ($this->debugcheck() == 1 || $this->_debugState == true) {
|
||||
dump($message);
|
||||
}
|
||||
}
|
||||
|
||||
public function debugcheck()
|
||||
{
|
||||
return Setting::find(1)->value('deviceDebugging');
|
||||
}
|
||||
}
|
96
app/CustomClasses/DeviceDownloadClass.php
Normal file
96
app/CustomClasses/DeviceDownloadClass.php
Normal file
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Http\Controllers\Connections\MainConnectionManager;
|
||||
use App\Models\User;
|
||||
use App\Notifications\DBDeviceConnectionFailureNotification;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
class DeviceDownloadClass extends Command
|
||||
{
|
||||
protected $output;
|
||||
|
||||
protected $eventtype;
|
||||
|
||||
protected $devicerecords;
|
||||
|
||||
protected $debug;
|
||||
|
||||
protected $report_id;
|
||||
|
||||
protected $parent_function;
|
||||
|
||||
protected $parent_class;
|
||||
|
||||
public function __construct($devicerecords, $eventtype, $debug, $report_id = null)
|
||||
{
|
||||
$this->output = [];
|
||||
$this->eventtype = $eventtype;
|
||||
$this->devicerecords = $devicerecords;
|
||||
$this->debug = $debug;
|
||||
$this->report_id = $report_id;
|
||||
$this->parent_class = get_parent_class();
|
||||
$this->parent_function = debug_backtrace()[1]['function'];
|
||||
}
|
||||
|
||||
public function downloadDevices()
|
||||
{
|
||||
// start the download
|
||||
foreach ($this->devicerecords as $devicerecord) {
|
||||
$devicerecord['start_time'] = Carbon::now();
|
||||
|
||||
$logmsg = 'Start device download for ' . ($devicerecord['device_name'] . ' ID:' . $devicerecord['id']);
|
||||
activityLogIt($this->parent_class, $this->parent_function, 'info', $logmsg, 'connection', $devicerecord['device_name'], $devicerecord['id'], $this->eventtype, $devicerecord['id']);
|
||||
$this->output['info'][] = $logmsg;
|
||||
|
||||
$devicerecord = (new DeviceRecordPrepare($devicerecord))->DeviceRecordToArray();
|
||||
$connectionObj = new MainConnectionManager($devicerecord, $this->debug);
|
||||
$configsArray = $connectionObj->setupConnectAndReturnOutput();
|
||||
|
||||
// throw and error if configsArray is false
|
||||
if ($configsArray === false || isset($configsArray['failure'])) {
|
||||
$devicerecord['end_time'] = Carbon::now();
|
||||
$logmsg = 'No config data returned for ' . ($devicerecord['device_name'] . ' - ID:' . $devicerecord['id'] . '. Check your logs for more information');
|
||||
Notification::send(User::all(), new DBDeviceConnectionFailureNotification($logmsg, $devicerecord['id']));
|
||||
|
||||
$configSaveResult = (new SaveConfigsToDiskAndDb('device_download', 'Failed config download', 0, $devicerecord, $this->report_id))->saveConfigs();
|
||||
|
||||
$this->output['error'][] = $logmsg;
|
||||
activityLogIt($this->parent_class, $this->parent_function, 'error', $logmsg, 'connection', $devicerecord['device_name'], $devicerecord['id'], $this->eventtype, $devicerecord['id']);
|
||||
|
||||
(new SetDeviceStatus($devicerecord['id'], 0))->setDeviceStatus();
|
||||
|
||||
continue; // continue looping around if more devices
|
||||
}
|
||||
(new SetDeviceStatus($devicerecord['id'], 1))->setDeviceStatus();
|
||||
$logmsg = 'End device download for ' . ($devicerecord['device_name'] . ' ID:' . $devicerecord['id']);
|
||||
activityLogIt($this->parent_class, $this->parent_function, 'info', $logmsg, 'connection', $devicerecord['device_name'], $devicerecord['id'], $this->eventtype, $devicerecord['id']);
|
||||
|
||||
if (isset($configsArray['failure'])) {
|
||||
$this->output['error'][] = $configsArray['failure'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($configsArray as $commandName => $configArray) {
|
||||
$devicerecord['end_time'] = Carbon::now();
|
||||
$configSaveResult = (new SaveConfigsToDiskAndDb('device_download', $commandName, $configArray, $devicerecord, $this->report_id))->saveConfigs();
|
||||
$configresultText = $configSaveResult['success'] === true ? ' was successful' : ' failed';
|
||||
$logmsg = 'Config downloaded for ' . $devicerecord['device_name'] . ' with command: "' . $configSaveResult['commandName'] . '"' . $configresultText;
|
||||
$this->output['info'][] = $logmsg;
|
||||
activityLogIt($this->parent_class, $this->parent_function, 'info', $logmsg, 'connection', $devicerecord['device_name'], $devicerecord['id'], 'device');
|
||||
}
|
||||
|
||||
// dd($configCheckResult);
|
||||
}
|
||||
if (isset($devicerecord)) {
|
||||
Redis::set('download-now-' . $devicerecord['id'], 'false');
|
||||
}
|
||||
|
||||
return $this->output;
|
||||
}
|
||||
}
|
38
app/CustomClasses/DeviceRecordPrepare.php
Normal file
38
app/CustomClasses/DeviceRecordPrepare.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Category;
|
||||
|
||||
class DeviceRecordPrepare
|
||||
{
|
||||
protected $devicerecord;
|
||||
|
||||
public function __construct(object $devicerecord)
|
||||
{
|
||||
$this->devicerecord = $devicerecord;
|
||||
}
|
||||
|
||||
public function DeviceRecordToArray()
|
||||
{
|
||||
$commands = $this->_getCommands($this->devicerecord->device_category_id);
|
||||
|
||||
if ($commands->isEmpty()) {
|
||||
// this is useful for some tests or when a devices category has no commands
|
||||
return $commands[0] = [];
|
||||
}
|
||||
|
||||
$devicerecordArr = $this->devicerecord->toArray();
|
||||
|
||||
foreach ($commands[0]->command as $command) {
|
||||
$devicerecordArr['commands'][$command->id] = $command->command;
|
||||
}
|
||||
|
||||
return $devicerecordArr;
|
||||
}
|
||||
|
||||
private function _getCommands($device_category_id)
|
||||
{
|
||||
return Category::with('command')->where('id', $device_category_id)->get();
|
||||
}
|
||||
}
|
19
app/CustomClasses/FilterArgsForCommnds.php
Normal file
19
app/CustomClasses/FilterArgsForCommnds.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
class FilterArgsForCommnds
|
||||
{
|
||||
private $args;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public function filterArgs($args)
|
||||
{
|
||||
$this->args = $args;
|
||||
|
||||
return array_filter($this->args, 'ctype_digit');
|
||||
}
|
||||
}
|
20
app/CustomClasses/GetAndCheckCategoryIds.php
Normal file
20
app/CustomClasses/GetAndCheckCategoryIds.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Category;
|
||||
|
||||
class GetAndCheckCategoryIds
|
||||
{
|
||||
protected $ids;
|
||||
|
||||
public function __construct(array $ids)
|
||||
{
|
||||
$this->ids = $ids;
|
||||
}
|
||||
|
||||
public function GetCategoryRecords()
|
||||
{
|
||||
return Category::with('device')->whereIn('id', $this->ids)->get();
|
||||
}
|
||||
}
|
20
app/CustomClasses/GetAndCheckDeviceIds.php
Normal file
20
app/CustomClasses/GetAndCheckDeviceIds.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Device;
|
||||
|
||||
class GetAndCheckDeviceIds
|
||||
{
|
||||
protected $ids;
|
||||
|
||||
public function __construct(array $ids)
|
||||
{
|
||||
$this->ids = $ids;
|
||||
}
|
||||
|
||||
public function GetDeviceRecords()
|
||||
{
|
||||
return Device::with('category')->whereIn('id', $this->ids)->get();
|
||||
}
|
||||
}
|
20
app/CustomClasses/GetAndCheckTagIds.php
Normal file
20
app/CustomClasses/GetAndCheckTagIds.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Tag;
|
||||
|
||||
class GetAndCheckTagIds
|
||||
{
|
||||
protected $ids;
|
||||
|
||||
public function __construct(array $ids)
|
||||
{
|
||||
$this->ids = $ids;
|
||||
}
|
||||
|
||||
public function GetTagRecords()
|
||||
{
|
||||
return Tag::with('device')->whereIn('id', $this->ids)->get();
|
||||
}
|
||||
}
|
20
app/CustomClasses/GetAndCheckTaskIds.php
Normal file
20
app/CustomClasses/GetAndCheckTaskIds.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Task;
|
||||
|
||||
class GetAndCheckTaskIds
|
||||
{
|
||||
protected $ids;
|
||||
|
||||
public function __construct(array $ids)
|
||||
{
|
||||
$this->ids = $ids;
|
||||
}
|
||||
|
||||
public function GetTaskRecords()
|
||||
{
|
||||
return Task::with('device', 'tag', 'category')->whereIn('id', $this->ids)->get();
|
||||
}
|
||||
}
|
69
app/CustomClasses/PurgeOperations.php
Normal file
69
app/CustomClasses/PurgeOperations.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Notifications\DBPurgeOperationNotification;
|
||||
use App\Notifications\MailPurgeOperationNotification;
|
||||
use File;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Validator;
|
||||
|
||||
class PurgeOperations
|
||||
{
|
||||
public function purge(Request $request)
|
||||
{
|
||||
Validator::make($request->all(), [
|
||||
'days' => 'required|integer|gt:0',
|
||||
])->validate();
|
||||
|
||||
switch ($request->purgetype) {
|
||||
case 'backup':
|
||||
$files = File::allFiles(backup_path());
|
||||
break;
|
||||
case 'settings':
|
||||
$files = File::allFiles(storage_path().'/logs');
|
||||
break;
|
||||
}
|
||||
|
||||
if (! empty($files)) {
|
||||
$purgeSeconds = 86400 * $request->days;
|
||||
$limit = time() - $purgeSeconds;
|
||||
$purgelist = [];
|
||||
foreach ($files as $file) {
|
||||
if ($file->getMtime() < $limit) {
|
||||
$purgelist[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
File::delete($purgelist);
|
||||
|
||||
$msg = $request->purgetype.' files older than '.$request->days.' days are now purged.';
|
||||
$output = [
|
||||
'success' => true,
|
||||
'data' => '',
|
||||
'msg' => $msg,
|
||||
];
|
||||
|
||||
// send notification
|
||||
try {
|
||||
Notification::send(User::allUsersAndRecipients(), new MailPurgeOperationNotification($msg, $this->username));
|
||||
Notification::send(User::all(), new DBPurgeOperationNotification($msg, $this->username));
|
||||
|
||||
$responseArray = ['success' => 200, 'msg' => $msg];
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'warn', $responseArray['msg'], 'purge');
|
||||
} catch (\Exception $e) {
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $e->getMessage(), 'purge');
|
||||
}
|
||||
} else {
|
||||
//LOGGING
|
||||
$output = [
|
||||
'success' => false,
|
||||
'msg' => 'No files found!',
|
||||
];
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
}
|
74
app/CustomClasses/SaveConfigsToDiskAndDb.php
Normal file
74
app/CustomClasses/SaveConfigsToDiskAndDb.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Category;
|
||||
use App\Models\Config;
|
||||
use App\Services\Config\FileOperations;
|
||||
|
||||
class SaveConfigsToDiskAndDb
|
||||
{
|
||||
public $configsArray;
|
||||
|
||||
public $type;
|
||||
|
||||
public $commandName;
|
||||
|
||||
public $devicerecord;
|
||||
|
||||
public $report_id;
|
||||
|
||||
public function __construct($type, $commandName, $configsArray, $devicerecord, $report_id = null)
|
||||
{
|
||||
$this->type = $type;
|
||||
$this->commandName = $commandName;
|
||||
$this->configsArray = $configsArray;
|
||||
$this->devicerecord = $devicerecord;
|
||||
$this->report_id = $report_id;
|
||||
}
|
||||
|
||||
public function saveConfigs()
|
||||
{
|
||||
$savedFileInfo = null;
|
||||
$device_category = Category::where('id', $this->devicerecord['device_category_id'])->pluck('categoryName')->first();
|
||||
$duration = $this->devicerecord['end_time']->diffInSeconds($this->devicerecord['start_time']);
|
||||
|
||||
if ($this->configsArray != 0) {
|
||||
$fileops =
|
||||
new FileOperations(
|
||||
$this->commandName,
|
||||
$device_category,
|
||||
$this->devicerecord['device_name'],
|
||||
$this->devicerecord['id'],
|
||||
config_data_path(),
|
||||
$this->type
|
||||
);
|
||||
$savedFileInfo = $fileops->saveFile($this->configsArray);
|
||||
}
|
||||
|
||||
$model = new Config;
|
||||
$model->device_id = $this->devicerecord['id'];
|
||||
$model->device_name = $this->devicerecord['device_name'];
|
||||
$model->device_category = $device_category;
|
||||
$model->command = $this->commandName;
|
||||
$model->type = $this->type;
|
||||
if ($this->configsArray === 0 || $this->configsArray === null) {
|
||||
$model->download_status = 0;
|
||||
} else {
|
||||
$model->config_location = $savedFileInfo['filepath'];
|
||||
$model->config_filename = $savedFileInfo['filename'];
|
||||
$model->config_filesize = $savedFileInfo['filesize'];
|
||||
$model->download_status = $savedFileInfo['download_status'];
|
||||
}
|
||||
$model->report_id = $this->report_id;
|
||||
$model->start_time = $this->devicerecord['start_time']->toDateTimeString();
|
||||
$model->end_time = $this->devicerecord['end_time']->toDateTimeString();
|
||||
$model->duration = $duration;
|
||||
$model->save();
|
||||
if ($model->save() && !empty($savedFileInfo)) {
|
||||
return ['success' => true, 'commandName' => $this->commandName];
|
||||
}
|
||||
|
||||
return ['success' => false, 'commandName' => $this->commandName];
|
||||
}
|
||||
}
|
27
app/CustomClasses/SetDeviceStatus.php
Normal file
27
app/CustomClasses/SetDeviceStatus.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\CustomClasses;
|
||||
|
||||
use App\Models\Device;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class SetDeviceStatus
|
||||
{
|
||||
protected $status;
|
||||
|
||||
protected $deviceid;
|
||||
|
||||
public function __construct($deviceid, $status)
|
||||
{
|
||||
$this->status = $status;
|
||||
$this->deviceid = $deviceid;
|
||||
}
|
||||
|
||||
public function setDeviceStatus()
|
||||
{
|
||||
$device = Device::findOrFail($this->deviceid);
|
||||
$device->last_seen = Carbon::now()->toDateTimeString();
|
||||
$device->status = $this->status;
|
||||
$device->save();
|
||||
}
|
||||
}
|
14
app/DataTransferObjects/StoreCategoryDTO.php
Normal file
14
app/DataTransferObjects/StoreCategoryDTO.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreCategoryDTO extends DataTransferObject
|
||||
{
|
||||
public string $categoryName;
|
||||
|
||||
public string $categoryDescription;
|
||||
}
|
15
app/DataTransferObjects/StoreCommandDTO.php
Normal file
15
app/DataTransferObjects/StoreCommandDTO.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreCommandDTO extends DataTransferObject
|
||||
{
|
||||
public string $command;
|
||||
|
||||
public string $description;
|
||||
// public array $categoryArray;
|
||||
}
|
50
app/DataTransferObjects/StoreDeviceDTO.php
Normal file
50
app/DataTransferObjects/StoreDeviceDTO.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreDeviceDTO extends DataTransferObject
|
||||
{
|
||||
public string $device_name;
|
||||
|
||||
public string $device_ip;
|
||||
|
||||
public $device_port_override;
|
||||
|
||||
public $device_vendor;
|
||||
|
||||
public $device_default_creds_on;
|
||||
|
||||
public string $device_username;
|
||||
|
||||
public $device_password;
|
||||
|
||||
public $device_enable_password;
|
||||
|
||||
public $device_cred_id;
|
||||
|
||||
public $ssh_key_id;
|
||||
|
||||
public string $device_main_prompt;
|
||||
|
||||
public $device_enable_prompt;
|
||||
|
||||
public $device_category_id;
|
||||
|
||||
public $device_template;
|
||||
|
||||
public $device_tags;
|
||||
|
||||
public string $device_model;
|
||||
|
||||
public $device_version;
|
||||
|
||||
public $device_added_by;
|
||||
|
||||
public $status;
|
||||
|
||||
public $last_seen;
|
||||
}
|
12
app/DataTransferObjects/StoreSettingsBannerDTO.php
Normal file
12
app/DataTransferObjects/StoreSettingsBannerDTO.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreSettingsBannerDTO extends DataTransferObject
|
||||
{
|
||||
public string $login_banner;
|
||||
}
|
28
app/DataTransferObjects/StoreSettingsEmailDTO.php
Normal file
28
app/DataTransferObjects/StoreSettingsEmailDTO.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreSettingsEmailDTO extends DataTransferObject
|
||||
{
|
||||
public string $mail_host;
|
||||
|
||||
public int $mail_port;
|
||||
|
||||
public string $mail_from_email;
|
||||
|
||||
public string $mail_to_email;
|
||||
|
||||
public $mail_authcheck;
|
||||
|
||||
public $mail_username;
|
||||
|
||||
public $mail_password;
|
||||
|
||||
public $mail_driver;
|
||||
|
||||
public $mail_encryption;
|
||||
}
|
12
app/DataTransferObjects/StoreSettingsTimezoneDTO.php
Normal file
12
app/DataTransferObjects/StoreSettingsTimezoneDTO.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreSettingsTimezoneDTO extends DataTransferObject
|
||||
{
|
||||
public string $timezone;
|
||||
}
|
14
app/DataTransferObjects/StoreTagDTO.php
Normal file
14
app/DataTransferObjects/StoreTagDTO.php
Normal file
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreTagDTO extends DataTransferObject
|
||||
{
|
||||
public string $tagname;
|
||||
|
||||
public string $tagDescription;
|
||||
}
|
35
app/DataTransferObjects/StoreTaskDTO.php
Normal file
35
app/DataTransferObjects/StoreTaskDTO.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreTaskDTO extends DataTransferObject
|
||||
{
|
||||
|
||||
public $download_report_notify;
|
||||
|
||||
public $task_categories;
|
||||
|
||||
public $task_devices;
|
||||
|
||||
public $task_email_notify;
|
||||
|
||||
public $task_tags;
|
||||
|
||||
public $verbose_download_report_notify;
|
||||
|
||||
public $id;
|
||||
|
||||
public int $is_system;
|
||||
|
||||
public string $task_command;
|
||||
|
||||
public string $task_cron;
|
||||
|
||||
public string $task_desc;
|
||||
|
||||
public string $task_name;
|
||||
}
|
16
app/DataTransferObjects/StoreTemplateDTO.php
Normal file
16
app/DataTransferObjects/StoreTemplateDTO.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreTemplateDTO extends DataTransferObject
|
||||
{
|
||||
public string $fileName;
|
||||
|
||||
public string $templateName;
|
||||
|
||||
public string $description;
|
||||
}
|
20
app/DataTransferObjects/StoreUserDTO.php
Normal file
20
app/DataTransferObjects/StoreUserDTO.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreUserDTO extends DataTransferObject
|
||||
{
|
||||
public string $name;
|
||||
|
||||
public $username;
|
||||
|
||||
public string $email;
|
||||
|
||||
public string $password;
|
||||
|
||||
public string $role;
|
||||
}
|
12
app/DataTransferObjects/StoreVendorDTO.php
Normal file
12
app/DataTransferObjects/StoreVendorDTO.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataTransferObjects;
|
||||
|
||||
use Spatie\DataTransferObject\DataTransferObject;
|
||||
|
||||
final class StoreVendorDTO extends DataTransferObject
|
||||
{
|
||||
public string $vendorName;
|
||||
}
|
70
app/Exceptions/Handler.php
Normal file
70
app/Exceptions/Handler.php
Normal file
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* A list of the exception types that are not reported.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $dontReport = [
|
||||
//
|
||||
];
|
||||
|
||||
/**
|
||||
* A list of the inputs that are never flashed for validation exceptions.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register()
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
//
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Report or log an exception.
|
||||
*
|
||||
* @param \Exception $exception
|
||||
* @return void
|
||||
*/
|
||||
public function report(Throwable $exception)
|
||||
{
|
||||
parent::report($exception);
|
||||
}
|
||||
|
||||
public function render($request, Throwable $exception)
|
||||
{
|
||||
if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
|
||||
return response()->json(['message' => 'Not Found!'], 404);
|
||||
}
|
||||
|
||||
if (
|
||||
strpos($request->getRequestUri(), '/api/', 0) === 0 &&
|
||||
get_class($exception) === NotFoundHttpException::class
|
||||
) {
|
||||
return response()->json(['message' => 'Not Found!'], 404);
|
||||
}
|
||||
|
||||
return parent::render($request, $exception);
|
||||
}
|
||||
}
|
92
app/Http/Controllers/Api/ActivityLogController.php
Normal file
92
app/Http/Controllers/Api/ActivityLogController.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Models\ActivityLog;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ActivityLogController extends ApiBaseController
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function __construct(ActivityLog $model, $modelname = 'ActivityLog')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['description', 'log_name'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\ActivityLog $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\ActivityLog $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function getLast5($id)
|
||||
{
|
||||
return ActivityLog::where('device_id', $id)->latest()->take(5)->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\ActivityLog $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function showStatsByDeviceId($id)
|
||||
{
|
||||
return DB::table('activity_log')
|
||||
->select('log_name', DB::raw('count(*) as total'))
|
||||
->where('device_id', $id)
|
||||
->groupBy('log_name')
|
||||
->get();
|
||||
}
|
||||
|
||||
public function clearLogsByDeviceId($id)
|
||||
{
|
||||
|
||||
DB::table('activity_log')
|
||||
->where('device_id', $id)
|
||||
->delete();
|
||||
|
||||
return $this->successResponse('Logs cleared successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' deleted successfully!');
|
||||
}
|
||||
}
|
178
app/Http/Controllers/Api/ApiBaseController.php
Normal file
178
app/Http/Controllers/Api/ApiBaseController.php
Normal file
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller as Controller;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ApiBaseController extends Controller
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
protected $query;
|
||||
|
||||
protected $model;
|
||||
|
||||
protected $modelname;
|
||||
|
||||
protected $matchThese;
|
||||
|
||||
public function __construct(Model $model, $modelname)
|
||||
{
|
||||
$this->query;
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols, $relationship = null, $withCount = null)
|
||||
{
|
||||
$sortCol = $request->sortCol != '' ? $request->sortCol : 'created_at';
|
||||
$sortOrd = $request->sortOrd != '' ? $request->sortOrd : 'desc';
|
||||
|
||||
$this->query = $this->model::query();
|
||||
$this->query->orderBy($sortCol, $sortOrd);
|
||||
|
||||
if ($relationship != null) {
|
||||
foreach ($relationship as $rel) {
|
||||
$this->query->with($rel);
|
||||
}
|
||||
}
|
||||
|
||||
if ($withCount != null) {
|
||||
foreach ($withCount as $rel) {
|
||||
$this->query->withCount($rel);
|
||||
}
|
||||
}
|
||||
|
||||
if ($request->filter != null) {
|
||||
$this->return_filtered_data($request->filter, $searchCols);
|
||||
}
|
||||
|
||||
$data = $this->query->paginate($request->perPage);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
protected function return_filtered_data($filter, $searchCols)
|
||||
{
|
||||
// for filtering objects contained within the filter parameter:: filter={%22device_id%22:%221001%22}
|
||||
if ($this->is_valid_json($filter)) {
|
||||
$filter = json_decode($filter);
|
||||
$key = key((array) ($filter));
|
||||
|
||||
if ($key === 'category' || $key === 'vendor' || $key === 'tag') {
|
||||
$this->query->whereRelation($key, 'id', $filter->$key)->get();
|
||||
} else {
|
||||
$this->query->where($key, $filter->$key);
|
||||
}
|
||||
} else {
|
||||
foreach ($searchCols as $col) {
|
||||
$this->matchThese[] = [$col, 'like', '%' . $filter . '%'];
|
||||
}
|
||||
//Add Conditions
|
||||
foreach ($this->matchThese as $key => $matchThis) {
|
||||
if ($key === array_key_first($this->matchThese)) {
|
||||
$this->query->where($matchThis[0], $matchThis[1], $matchThis[2]);
|
||||
} else {
|
||||
$this->query->orWhere($matchThis[0], $matchThis[1], $matchThis[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
* In order to avoid an inherant bug in laravel, we need to pass the request array directly to a newly name method.
|
||||
* Thats why this is called StoreResource instead of Store.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function storeResource($request, $return = 0)
|
||||
{
|
||||
$model = $this->model::create($request);
|
||||
if ($return === 1) {
|
||||
return $model;
|
||||
}
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' created successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\User $user
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
$this->query = $this->model::query();
|
||||
$this->query->findOrFail($id);
|
||||
|
||||
if ($relationship != null) {
|
||||
foreach ($relationship as $rel) {
|
||||
$this->query->with($rel);
|
||||
}
|
||||
}
|
||||
|
||||
if ($withCount != null) {
|
||||
foreach ($withCount as $rel) {
|
||||
$this->query->withCount($rel);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->query->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
* In order to avoid an inherant bug in laravel, we need to pass the request array directly to a newly name method.
|
||||
* Thats why this is called UpdateResource instead of Update.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\User $user
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function updateResource($id, $request, $return = 0)
|
||||
{
|
||||
$model = $this->model::find($id);
|
||||
$model = tap($model)->update($request); // tap returns model instead of boolean
|
||||
|
||||
if ($return === 1) {
|
||||
return $model;
|
||||
}
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' edited successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = $this->model::find($id);
|
||||
$model = tap($model)->delete(); // tap returns model instead of boolean
|
||||
|
||||
if ($return === 1) {
|
||||
return $model;
|
||||
}
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' deleted successfully!');
|
||||
}
|
||||
|
||||
private function is_valid_json($string)
|
||||
{
|
||||
return is_object(json_decode($string));
|
||||
}
|
||||
}
|
73
app/Http/Controllers/Api/CategoryController.php
Normal file
73
app/Http/Controllers/Api/CategoryController.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreCategoryRequest;
|
||||
use App\Models\Category;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class CategoryController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Category $model, $modelname = 'category')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['categoryName'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols, ['command'], ['device']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreCategoryRequest $request)
|
||||
{
|
||||
return parent::storeResource($request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Category $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id, ['command'], ['device']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Category $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreCategoryRequest $request)
|
||||
{
|
||||
return parent::updateResource($id, $request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
return parent::destroy($id);
|
||||
}
|
||||
}
|
88
app/Http/Controllers/Api/CommandController.php
Normal file
88
app/Http/Controllers/Api/CommandController.php
Normal file
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreCommandRequest;
|
||||
use App\Models\Command;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CommandController extends ApiBaseController
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function __construct(Command $model, $modelname = 'command')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['command'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols, ['category']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreCommandRequest $request)
|
||||
{
|
||||
$model = parent::storeResource($request->toDTO()->toArray(), 1);
|
||||
|
||||
$model->Category()->attach($request->categoryArray);
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' created successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Command $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id, ['category']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Command $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreCommandRequest $request)
|
||||
{
|
||||
$model = parent::updateResource($id, $request->toDTO()->toArray(), 1);
|
||||
$model->Category()->sync($request->categoryArray);
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' edited successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
$model->Category()->detach();
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' deleted successfully!');
|
||||
}
|
||||
}
|
47
app/Http/Controllers/Api/ConfigActionsController.php
Normal file
47
app/Http/Controllers/Api/ConfigActionsController.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Jobs\DownloadConfigNow;
|
||||
use App\Jobs\PurgeFailedConfigsJob;
|
||||
use App\Models\Config;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class ConfigActionsController extends ApiBaseController
|
||||
{
|
||||
|
||||
protected $model;
|
||||
protected $modelname;
|
||||
|
||||
public function __construct(Config $model, $modelname = 'config')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
public function downloadNow(Request $request)
|
||||
{
|
||||
$username = Auth::user()->name;
|
||||
|
||||
if (App()->environment('testing')) { // required for testing
|
||||
dispatch(new DownloadConfigNow($request->device_id, $username))->onConnection('sync');
|
||||
} else {
|
||||
dispatch(new DownloadConfigNow($request->device_id, $username))->onQueue('downloadqueue');
|
||||
}
|
||||
|
||||
return $this->successResponse('Download started');
|
||||
}
|
||||
|
||||
|
||||
public function purgeFailed(Request $request)
|
||||
{
|
||||
if (App()->environment('testing')) { // required for testing
|
||||
dispatch(new PurgeFailedConfigsJob($request->device_id))->onConnection('sync');
|
||||
} else {
|
||||
dispatch(new PurgeFailedConfigsJob($request->device_id))->onQueue('lastqueue');
|
||||
}
|
||||
|
||||
return $this->successResponse('Purge started');
|
||||
}
|
||||
}
|
233
app/Http/Controllers/Api/ConfigController.php
Normal file
233
app/Http/Controllers/Api/ConfigController.php
Normal file
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Models\Config;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Response;
|
||||
|
||||
class ConfigController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Config $model, $modelname = 'config')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = [''];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Command $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
if (File::exists($model->config_location)) {
|
||||
File::delete($model->config_location);
|
||||
$logmsg = 'Config File : '.$model->config_location.' was deleted';
|
||||
} else {
|
||||
$logmsg = 'Unable to find file from path: '.$model->config_location;
|
||||
$this->failureResponse($logmsg);
|
||||
}
|
||||
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'warn', $logmsg, 'config', '', $model->device_id, 'device');
|
||||
|
||||
return $this->successResponse($logmsg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource for a given device ID.
|
||||
*
|
||||
* @param \App\Models\Request $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function getAllById($id, $status, Request $request)
|
||||
{
|
||||
$sortCol = $request->sortCol != '' ? $request->sortCol : 'created_at';
|
||||
$sortOrd = $request->sortOrd != '' ? $request->sortOrd : 'desc';
|
||||
|
||||
$searchCols = ['command'];
|
||||
|
||||
$perPage = (int) $request->perPage;
|
||||
// dd($perPage);
|
||||
|
||||
$this->query = $this->model::query();
|
||||
$this->query->orderBy($sortCol, $sortOrd);
|
||||
|
||||
if ($id != 0) {
|
||||
$this->query->where('device_id', $id);
|
||||
}
|
||||
|
||||
if (! $status || $status != 'all') {
|
||||
$this->query->where('download_status', $status);
|
||||
}
|
||||
if ($request->filter != null) {
|
||||
$this->return_filtered_data($request->filter, $searchCols);
|
||||
}
|
||||
|
||||
return $this->query->orderBy('created_at', 'desc')->paginate($perPage);
|
||||
}
|
||||
|
||||
public function getLatestById($id)
|
||||
{
|
||||
$results = DB::select('select * from configs WHERE id IN (SELECT MAX(id) FROM configs WHERE device_id = ? GROUP BY command)', [$id]);
|
||||
|
||||
return $this->successResponse('Success', $results);
|
||||
}
|
||||
|
||||
public function getSingleConfigFile($id)
|
||||
{
|
||||
if (! $id) {
|
||||
return $this->failureResponse('No ID provided');
|
||||
}
|
||||
|
||||
$config_location = Config::find($id)->config_location;
|
||||
|
||||
if ($config_location) {
|
||||
$content = File::get($config_location);
|
||||
$utf8_string = mb_convert_encoding($content, 'UTF-8');
|
||||
|
||||
return $this->successResponse('Success', $utf8_string);
|
||||
} else {
|
||||
return $this->failureResponse('No config file found');
|
||||
}
|
||||
}
|
||||
|
||||
public function getDistinctCommands($id)
|
||||
{
|
||||
if ($id == 0) {
|
||||
$result = Config::distinct()->get(['command']);
|
||||
} else {
|
||||
$result = Config::where('device_id', $id)->distinct()->get(['command']);
|
||||
}
|
||||
|
||||
return $this->successResponse('Success', $result);
|
||||
}
|
||||
|
||||
// public function getOneById(Request $request)
|
||||
// {
|
||||
// $model = Config::find($request->id);
|
||||
// return $model;
|
||||
// }
|
||||
|
||||
// public function getAllInvalid(Request $request)
|
||||
// {
|
||||
// $perPage = (int) $request->items;
|
||||
// $data = Config::orderBy('created_at', 'desc')->where('download_status', 0)->orderBy('created_at', 'desc')->paginate($perPage);
|
||||
// return response()->json($data);
|
||||
// }
|
||||
|
||||
// public function getAllInvalidById(Request $request)
|
||||
// {
|
||||
// $perPage = (int) $request->items;
|
||||
// $data = Config::where('device_id', $request->device_id)->where('download_status', null)->orWhere('download_status', '=', 0)->orderBy('created_at', 'desc')->orderBy('created_at', 'desc')->paginate($perPage);
|
||||
// return response()->json($data);
|
||||
// }
|
||||
|
||||
// public function getAllByCommandString($command, Request $request)
|
||||
// {
|
||||
// $perPage = (int) $request->items;
|
||||
// if ($request->filter != 'null') {
|
||||
// $data = $this->return_filtered_data_by_id($request->filter, $perPage, $request->device_id);
|
||||
// } else {
|
||||
// $data = Config::where('device_id', $request->device_id)->where('command', $command)->orderBy('created_at', 'desc')->paginate($perPage);
|
||||
// }
|
||||
// return response()->json($data);
|
||||
// }
|
||||
|
||||
// public function getOneById(Request $request)
|
||||
// {
|
||||
// $model = Config::find($request->id);
|
||||
// return $model;
|
||||
// }
|
||||
|
||||
// public function getLatestConfigDate()
|
||||
// {
|
||||
// return Config::select('created_at')->latest()->first();
|
||||
// }
|
||||
|
||||
// public function getConfigsStatsByDeviceId(Request $request)
|
||||
// {
|
||||
// $resultArr['count_valid'] = Config::where('device_id', $request->id)->where('download_status', 1)->count();
|
||||
// $invalid_collection = Config::where('device_id', $request->id)->get();
|
||||
// $resultArr['count_invalid'] = $invalid_collection->where('download_status', null)->where('download_status', 0)->count();
|
||||
// $resultArr['latest_download'] = Config::select('start_time')->where('device_id', $request->id)->orderBy('created_at', 'desc')->first();
|
||||
// $resultArr['latest_download'] = $resultArr['count_valid'] != null ? $resultArr['count_valid'] : 'NULL';
|
||||
// return $resultArr;
|
||||
// }
|
||||
|
||||
// public function getConfigsInfoByDeviceId(Request $request)
|
||||
// {
|
||||
// $resultArr = array();
|
||||
// $uniqueCommands = Config::select('command')->where('device_id', $request->id)->distinct('command')->get();
|
||||
// $timezone = \Config::get('app.timezone');
|
||||
// $now = Carbon::now($timezone);
|
||||
|
||||
// $i = 0;
|
||||
// foreach ($uniqueCommands as $uniqueCommand) {
|
||||
// $latestCommand = Config::select('id', 'download_status', 'start_time')
|
||||
// ->where('command', $uniqueCommand->command)
|
||||
// ->where('device_id', $request->id)
|
||||
|
||||
// ->orderBy('created_at', 'desc')
|
||||
// ->first();
|
||||
// // $initialCommand = Config::select('id', 'download_status', 'start_time')->where('command', $uniqueCommand->command)->where('device_id', $request->id)->orderBy('created_at', 'asc')->first();
|
||||
// $count = Config::where('command', $uniqueCommand->command)->where('device_id', $request->id)->where('download_status', 1)->count();
|
||||
// $resultArr['commands'][$i]['id'] = $latestCommand->id;
|
||||
// $resultArr['commands'][$i]['command'] = $uniqueCommand->command;
|
||||
// $resultArr['commands'][$i]['count'] = $count;
|
||||
// $resultArr['commands'][$i]['latest_config_time'] = Carbon::createFromTimestamp(strtotime($latestCommand->start_time))
|
||||
// ->addHours($timezone)
|
||||
// ->format('M d, Y G:iA');
|
||||
// // $resultArr['commands'][$i]['initial_config_time'] = Carbon::createFromTimestamp(strtotime($initialCommand->start_time))
|
||||
// // ->addHours($timezone)
|
||||
// // ->format('M d, Y G:iA');
|
||||
// $resultArr['commands'][$i]['download_status'] = $latestCommand->download_status;
|
||||
// $i++;
|
||||
// }
|
||||
// return $resultArr;
|
||||
// }
|
||||
|
||||
// private function return_filtered_data($filter, $perPage)
|
||||
// {
|
||||
// return Config::orderBy('created_at', 'desc')
|
||||
// ->where('command', 'like', '%' . $filter . '%')
|
||||
// ->paginate($perPage);
|
||||
// }
|
||||
|
||||
// private function return_filtered_data_by_id($filter, $perPage, $id)
|
||||
// {
|
||||
// return Config::orderBy('created_at', 'desc')
|
||||
// ->where('device_id', $id)
|
||||
// ->where('command', 'like', '%' . $filter . '%')
|
||||
// ->paginate($perPage);
|
||||
// }
|
||||
}
|
53
app/Http/Controllers/Api/ConfigSearchController.php
Normal file
53
app/Http/Controllers/Api/ConfigSearchController.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\CustomClasses\ConfigSearch;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ConfigSearchController extends Controller
|
||||
{
|
||||
public function search(Request $request)
|
||||
{
|
||||
Validator::make($request->all(), [
|
||||
'category' => 'required|exists:categories,id',
|
||||
'line_count' => 'required',
|
||||
'search_string' => 'required',
|
||||
])->validate();
|
||||
|
||||
$searchArr = (new ConfigSearch($request['category'], $request['search_string'], $request['line_count'], isset($request['latestOnly']) ? $request['latestOnly'] : false))->search();
|
||||
$searchArr['search_results'] = $this->recursive($searchArr['search_results']);
|
||||
|
||||
return json_encode($searchArr);
|
||||
}
|
||||
|
||||
private function recursive($in_array)
|
||||
{
|
||||
$array = [];
|
||||
$tmpArray = [];
|
||||
$k = 0;
|
||||
foreach ($in_array as $key => $value) {
|
||||
if (Str::startsWith($value, '-::')) {
|
||||
if (isset($tmpArray)) {
|
||||
unset($tmpArray);
|
||||
}
|
||||
$k++;
|
||||
$value = Str::replaceFirst('-::', '', $value);
|
||||
$value = Str::replaceFirst('::-', '', $value);
|
||||
$value = array_reverse(explode('/', $value));
|
||||
$tmpArray[0] = $value;
|
||||
} else {
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
$tmpArray[] = $value;
|
||||
}
|
||||
$array[$k] = $tmpArray;
|
||||
}
|
||||
|
||||
return $array;
|
||||
}
|
||||
}
|
170
app/Http/Controllers/Api/DashboardController.php
Normal file
170
app/Http/Controllers/Api/DashboardController.php
Normal file
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Device;
|
||||
use App\Models\Task;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function getSysInfo()
|
||||
{
|
||||
return Cache::remember('dashboard.sysinfo', 604800, function () {
|
||||
return $this->Sysinfo();
|
||||
});
|
||||
}
|
||||
|
||||
public function getConfigInfo()
|
||||
{
|
||||
$deviceCount = DB::table('devices')->count();
|
||||
$deviceDownCount = DB::table('devices')->where('status', 0)->count();
|
||||
$configTotalCount = DB::table('configs')->count();
|
||||
$configDownCount = DB::table('configs')->where('download_status', 0)->count();
|
||||
|
||||
$data = [
|
||||
'deviceCount' => $deviceCount,
|
||||
'deviceDownCount' => $deviceDownCount,
|
||||
'configTotalCount' => $configTotalCount,
|
||||
'configDownCount' => $configDownCount,
|
||||
];
|
||||
|
||||
return $this->successResponse('Success', $data);
|
||||
}
|
||||
|
||||
private function Sysinfo()
|
||||
{
|
||||
$this->checkAppUrl();
|
||||
|
||||
$osVersion = getOSInformation()['pretty_name'];
|
||||
$osVersion = str_replace('(Core)', '', $osVersion);
|
||||
$osVersion = str_replace('Linux', '', $osVersion);
|
||||
|
||||
$serverInfos = []; // array for Server Info Table
|
||||
$serverInfos['OSVersion'] = $osVersion;
|
||||
$serverInfos['localIp'] = gethostbyname(gethostname());
|
||||
$serverInfos['PublicIP'] = trim(shell_exec('dig +short myip.opendns.com @resolver1.opendns.com'));
|
||||
$serverInfos['ServerName'] = gethostname();
|
||||
$serverInfos['PHPVersion'] = phpversion() . ' / ' . app()->version();
|
||||
$serverInfos['RedisVersion'] = $this->redisVersion();
|
||||
$serverInfos['MySQLVersion'] = $this->mysqlversion();
|
||||
|
||||
return $serverInfos;
|
||||
}
|
||||
|
||||
private function getBatchJobData()
|
||||
{
|
||||
$result['q_total_count'] = DB::table('job_batches')->count();
|
||||
$result['q_failed_count'] = DB::table('job_batches')->where('failed_jobs', '>=', '0')->count();
|
||||
$result['q_last_job'] = DB::table('job_batches')->latest('created_at')->first();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function mysqlversion()
|
||||
{
|
||||
|
||||
$mysqlVersionNumber = DB::select(DB::raw('SHOW VARIABLES LIKE "%version%"')->getValue(DB::connection()->getQueryGrammar()));
|
||||
|
||||
return $mysqlVersionNumber[1]->Value;
|
||||
}
|
||||
|
||||
private function redisVersion()
|
||||
{
|
||||
$redis_info = Redis::info();
|
||||
|
||||
return $redis_info['Server']['redis_version'];
|
||||
}
|
||||
|
||||
private function systemUptime()
|
||||
{
|
||||
// uptime
|
||||
$get_uptime = file_get_contents('/proc/uptime');
|
||||
$uptime = explode(' ', $get_uptime);
|
||||
$uptime_days = floor($uptime[0] / 86400);
|
||||
$uptime_hours = floor(($uptime[0] / 3600) % 24);
|
||||
$uptime_minutes = floor(($uptime[0] / 60) % 60);
|
||||
$uptime_seconds = ($uptime[0] % 60);
|
||||
|
||||
return $uptime_days . ' Days ' . $uptime_hours . ':' . $uptime_minutes;
|
||||
}
|
||||
|
||||
private function memInfo()
|
||||
{
|
||||
// mem usage
|
||||
$get_meminfo = file('/proc/meminfo');
|
||||
$meminfo_total = filter_var($get_meminfo[0], FILTER_SANITIZE_NUMBER_INT);
|
||||
$meminfo_cached = filter_var($get_meminfo[2], FILTER_SANITIZE_NUMBER_INT);
|
||||
$meminfo_free = filter_var($get_meminfo[1], FILTER_SANITIZE_NUMBER_INT);
|
||||
if ($meminfo_total >= 10485760) {
|
||||
$mem_total = round(($meminfo_total / 1048576), 0) . ' MB';
|
||||
$mem_cached = round(($meminfo_cached / 1048576), 0) . ' MB';
|
||||
$mem_free = round((($meminfo_free + $meminfo_cached) / 1048576), 0) . ' MB';
|
||||
$mem_multiple = 'GB';
|
||||
} else {
|
||||
$mem_total = round(($meminfo_total / 1024), 0) . ' MB';
|
||||
$mem_cached = round(($meminfo_cached / 1024), 0) . ' MB';
|
||||
$mem_free = round((($meminfo_free + $meminfo_cached) / 1024), 0) . ' MB';
|
||||
$mem_multiple = 'MB';
|
||||
}
|
||||
$mem = [
|
||||
'total' => $mem_total,
|
||||
// 'Memory cached' => $mem_cached,
|
||||
'free' => $mem_free,
|
||||
];
|
||||
|
||||
return $mem;
|
||||
}
|
||||
|
||||
private function cpuLoad()
|
||||
{
|
||||
// cpu load
|
||||
$loads = sys_getloadavg();
|
||||
$core_nums = trim(shell_exec("grep -P '^processor' /proc/cpuinfo|wc -l"));
|
||||
$load = round($loads[0] / ($core_nums + 1) * 100, 2);
|
||||
|
||||
return $load;
|
||||
}
|
||||
|
||||
private function diskInfo()
|
||||
{
|
||||
/* get disk space free (in bytes) */
|
||||
$df = disk_free_space('/');
|
||||
/* and get disk space total (in bytes) */
|
||||
$dt = disk_total_space('/');
|
||||
/* now we calculate the disk space used (in bytes) */
|
||||
// $du = $dt - $df;
|
||||
/* percentage of disk used - this will be used to also set the width % of the progress bar */
|
||||
// $dp = sprintf('%.2f',($du / $dt) * 100);
|
||||
|
||||
/* and we formate the size from bytes to MB, GB, etc. */
|
||||
|
||||
$df = formatSize($df);
|
||||
// $du = formatSize($du);
|
||||
$dt = formatSize($dt);
|
||||
|
||||
$disk = [
|
||||
'free' => $df,
|
||||
// 'Disk Used Space' => $du,
|
||||
'total' => $dt,
|
||||
// 'Disk Percent Used' => $dp . '%'
|
||||
];
|
||||
|
||||
return $disk;
|
||||
}
|
||||
|
||||
private function checkAppUrl()
|
||||
{
|
||||
if (config('app.url') === '') {
|
||||
if ($this->checkOrSetAppUrlNotification()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
130
app/Http/Controllers/Api/DeviceController.php
Normal file
130
app/Http/Controllers/Api/DeviceController.php
Normal file
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreDeviceRequest;
|
||||
use App\Jobs\DownloadConfigNow;
|
||||
use App\Models\Device;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class DeviceController extends ApiBaseController
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function __construct(Device $model, $modelname = 'device')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['id', 'device_name', 'device_ip', 'device_model'];
|
||||
$result = parent::index($request, $searchCols, ['vendor', 'category', 'category.command', 'tag', 'template', 'lastConfig'], ['config_good', 'config_bad', 'config_unknown']);
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreDeviceRequest $request)
|
||||
{
|
||||
$model = parent::storeResource($request->toDTO()->toArray(), 1);
|
||||
|
||||
$model->Tag()->attach($request->device_tags);
|
||||
$model->Vendor()->attach($request->device_vendor);
|
||||
$model->Category()->attach($request->device_category_id);
|
||||
$model->Template()->attach($request->device_template);
|
||||
|
||||
$this->dispatch(new DownloadConfigNow($model->id));
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' created successfully!', ['id' => $model->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Device $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
$results = parent::show($id, ['vendor', 'category', 'category.command', 'tag', 'template', 'lastConfig'], ['config_good', 'config_bad', 'config_unknown']);
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Device $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreDeviceRequest $request)
|
||||
{
|
||||
$model = parent::updateResource($id, $request->toDTO()->toArray(), 1);
|
||||
|
||||
$model->Tag()->sync($request->device_tags);
|
||||
$model->Vendor()->sync($request->device_vendor);
|
||||
$model->Category()->sync($request->device_category_id);
|
||||
$model->Template()->sync($request->device_template);
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' edited successfully!', ['id' => $model->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
$model->delete();
|
||||
$model->Tag()->detach();
|
||||
$model->Vendor()->detach();
|
||||
$model->Category()->detach();
|
||||
$model->Template()->detach();
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' deleted successfully!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unique list of all devices models in the table
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function getDeviceModels()
|
||||
{
|
||||
$collection = Device::select('device_model')->whereNotNull('device_model')->groupBy('device_model')->get();
|
||||
$plucked = $collection->pluck('device_model');
|
||||
|
||||
return $this->successResponse('All Device Models!', $plucked);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get unique list of all devices models in the table
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function allDeviceNames()
|
||||
{
|
||||
$collection = Device::select('id', 'device_name')->get();
|
||||
|
||||
return $this->successResponse('All Device Names!', $collection);
|
||||
}
|
||||
}
|
24
app/Http/Controllers/Api/LicenseInfoController.php
Normal file
24
app/Http/Controllers/Api/LicenseInfoController.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
|
||||
class LicenseInfoController extends Controller
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function index()
|
||||
{
|
||||
$license = [
|
||||
'version' => config('app.version'),
|
||||
'sub_id' => config('app.rconfig_sub_id'),
|
||||
'sub_name' => config('app.rconfig_sub_name'),
|
||||
'status' => config('app.rconfig_sub_status'),
|
||||
'expiry' => config('app.rconfig_sub_expiry'),
|
||||
];
|
||||
|
||||
return $this->successResponse('Success', $license);
|
||||
}
|
||||
}
|
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Models\MonitoredScheduledTaskLogItems;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class MonitoredScheduledTaskLogItemController extends ApiBaseController
|
||||
{
|
||||
public function __construct(MonitoredScheduledTaskLogItems $model, $modelname = 'MonitoredScheduledTaskLogItems')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
return response()->json(parent::index($request, $searchCols));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\MonitoredScheduledTaskLogItems $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return $this->model::where('task_id', $id)->orderBy('id', 'desc')->paginate();
|
||||
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
return parent::destroy($id);
|
||||
}
|
||||
}
|
38
app/Http/Controllers/Api/SettingBannerController.php
Normal file
38
app/Http/Controllers/Api/SettingBannerController.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreSettingsBannerRequest;
|
||||
use App\Models\Setting;
|
||||
|
||||
class SettingBannerController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Setting $model, $modelname = 'setting')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreSettingsBannerRequest $request)
|
||||
{
|
||||
return parent::updateResource($id, $request->toDTO()->toArray());
|
||||
}
|
||||
}
|
102
app/Http/Controllers/Api/SettingEmailController.php
Normal file
102
app/Http/Controllers/Api/SettingEmailController.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreSettingsEmailRequest;
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use App\Notifications\TestMailNotification;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SettingEmailController extends ApiBaseController
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function __construct(Setting $model, $modelname = 'setting')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreSettingsEmailRequest $request)
|
||||
{
|
||||
parent::updateResource($id, $request->toDTO()->toArray(), 1);
|
||||
|
||||
if (!App()->environment('testing')) {
|
||||
Artisan::call('config:cache'); // cannot to a config:cache when testing
|
||||
}
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' edited successfully!');
|
||||
}
|
||||
|
||||
public function TestMailNotifications()
|
||||
{
|
||||
try {
|
||||
$users = $this->makeRecipients();
|
||||
foreach ($users as $user) {
|
||||
Notification::send($user, new TestMailNotification());
|
||||
}
|
||||
|
||||
return $this->successResponse('Test notification sent successfully!');
|
||||
} catch (\Exception $exception) {
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $exception->getMessage(), 'Test Notifications');
|
||||
|
||||
return $this->failureResponse($exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function TestMail()
|
||||
{
|
||||
try {
|
||||
$users = $this->makeRecipients();
|
||||
foreach ($users as $user) {
|
||||
Mail::send('emails.test-mail', [], function ($message) use ($user) {
|
||||
$message->to($user->email)->subject('rConfig Test Mail');
|
||||
});
|
||||
}
|
||||
|
||||
return $this->successResponse('Email settings tested successfully, please check your email for the test message!');
|
||||
} catch (\Exception $exception) {
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $exception->getMessage(), 'Test Mail');
|
||||
|
||||
return $this->failureResponse($exception->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function makeRecipients()
|
||||
{
|
||||
if (!$this->show(1)->mail_to_email) {
|
||||
return $this->failureResponse('Invalid recipient email address');
|
||||
}
|
||||
|
||||
$recipientsArr = explode(';', trim($this->show(1)->mail_to_email, ';'));
|
||||
|
||||
foreach ($recipientsArr as $recipient) {
|
||||
$users[] = User::make(['email' => trim($recipient)]);
|
||||
}
|
||||
|
||||
return $users;
|
||||
}
|
||||
}
|
50
app/Http/Controllers/Api/SettingTimezoneController.php
Normal file
50
app/Http/Controllers/Api/SettingTimezoneController.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreSettingsTimezoneRequest;
|
||||
use App\Models\Setting;
|
||||
use Artisan;
|
||||
|
||||
class SettingTimezoneController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Setting $model, $modelname = 'setting')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
public function getTimezoneList()
|
||||
{
|
||||
return require 'timezone_list.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreSettingsTimezoneRequest $request)
|
||||
{
|
||||
$timezone = str_replace('/', '\/\\', $request->timezone);
|
||||
Artisan::call('env:set TIMEZONE="'.$timezone.'"');
|
||||
if (! App()->environment('testing')) {
|
||||
Artisan::call('config:cache'); // cannot to a config:cache when testing
|
||||
}
|
||||
|
||||
return parent::updateResource($id, $request->toDTO()->toArray());
|
||||
}
|
||||
}
|
30
app/Http/Controllers/Api/SettingsSupportInfoController.php
Normal file
30
app/Http/Controllers/Api/SettingsSupportInfoController.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
|
||||
class SettingsSupportInfoController
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Setting $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index($id, $relationship = null)
|
||||
{
|
||||
$result = [
|
||||
'version' => Config::get('app.version'),
|
||||
'rconfig_sub_id' => Config::get('rconfig_sub_id'),
|
||||
'rconfig_sub_name' => Config::get('rconfig_sub_name'),
|
||||
'rconfig_sub_status' => Config::get('rconfig_sub_status'),
|
||||
'rconfig_sub_expiry' => Config::get('rconfig_sub_expiry'),
|
||||
];
|
||||
|
||||
return $this->successResponse('License Information', $result);
|
||||
}
|
||||
}
|
40
app/Http/Controllers/Api/SystemHealthController.php
Normal file
40
app/Http/Controllers/Api/SystemHealthController.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Spatie\Health\Models\HealthCheckResultHistoryItem;
|
||||
use Spatie\Health\ResultStores\StoredCheckResults\StoredCheckResult;
|
||||
|
||||
class SystemHealthController extends Controller
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function healthLatest()
|
||||
{
|
||||
|
||||
if (!$latestItem = (HealthCheckResultHistoryItem::latest()->first())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var Collection<int, StoredCheckResult> $storedCheckResults */
|
||||
$storedCheckResults = (HealthCheckResultHistoryItem::query()
|
||||
->where('batch', $latestItem->batch)
|
||||
->get()
|
||||
->map(function (HealthCheckResultHistoryItem $item) {
|
||||
return new StoredCheckResult(
|
||||
$item->check_name,
|
||||
$item->check_label,
|
||||
$item->status,
|
||||
$item->notification_message,
|
||||
$item->short_summary === 'reachable' ? 'rconfig.com reachable' : $item->short_summary,
|
||||
$item->meta,
|
||||
$item->ended_at
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
return $this->successResponse('Success', $storedCheckResults);
|
||||
}
|
||||
}
|
73
app/Http/Controllers/Api/TagController.php
Normal file
73
app/Http/Controllers/Api/TagController.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreTagRequest;
|
||||
use App\Models\Tag;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TagController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Tag $model, $modelname = 'tag')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['tagname'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols, null, ['device'], ['device']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreTagRequest $request)
|
||||
{
|
||||
return parent::storeResource($request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Tag $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id, null, ['device'], ['device']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Tag $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreTagRequest $request)
|
||||
{
|
||||
return parent::updateResource($id, $request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
return parent::destroy($id);
|
||||
}
|
||||
}
|
145
app/Http/Controllers/Api/TaskController.php
Normal file
145
app/Http/Controllers/Api/TaskController.php
Normal file
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreTaskRequest;
|
||||
use App\Http\Requests\UpdateTaskRequest;
|
||||
use App\Models\MonitoredScheduledTasks;
|
||||
use App\Models\Task;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Lorisleiva\CronTranslator\CronTranslator;
|
||||
|
||||
class TaskController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Task $model, $modelname = 'task')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['id', 'task_name'];
|
||||
$result = parent::index($request, $searchCols); // relationships are pulled from the model using 'protected $with' now
|
||||
|
||||
$result->map(function ($item) {
|
||||
$item['cron_plain'] = CronTranslator::translate(implode(' ', $item['task_cron']));
|
||||
|
||||
return $item;
|
||||
});
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreTaskRequest $request)
|
||||
{
|
||||
$model = parent::storeResource($request->toDTO()->toArray(), 1);
|
||||
|
||||
$model->tag()->attach($request->tag);
|
||||
$model->device()->attach($request->device);
|
||||
$model->category()->attach($request->category);
|
||||
|
||||
$this->SyncToMonitoredTasks($model);
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' created successfully!', ['id' => $model->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function validateTask(StoreTaskRequest $request)
|
||||
{
|
||||
$model = $request->toDTO()->toArray();
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' validated successfully!');
|
||||
}
|
||||
|
||||
// get failed tasks
|
||||
public function failedJobsLast24HrsCount()
|
||||
{
|
||||
$res = DB::table('failed_jobs')->where('failed_at', '>=', Carbon::now()->subDays(1))->count();
|
||||
|
||||
return $this->successResponse('Success', $res);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Task $user
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id); // relationships are pulled from the model using 'protected $with' now
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Task $user
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, UpdateTaskRequest $request)
|
||||
{
|
||||
$model = parent::updateResource($id, $request->toDTO()->toArray(), 1);
|
||||
$model->id = $id;
|
||||
|
||||
$model->tag()->sync($request->tag);
|
||||
$model->device()->sync($request->device);
|
||||
$model->category()->sync($request->category);
|
||||
|
||||
$this->SyncToMonitoredTasks($model);
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' edited successfully!', ['id' => $model->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
$model->delete();
|
||||
$model->tag()->detach();
|
||||
$model->category()->detach();
|
||||
$model->tag()->detach();
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname) . ' deleted successfully!');
|
||||
}
|
||||
|
||||
private function SyncToMonitoredTasks($model)
|
||||
{
|
||||
MonitoredScheduledTasks::updateOrCreate(
|
||||
['task_id' => $model->id],
|
||||
[
|
||||
'task_id' => $model->id,
|
||||
'name' => $model->task_name,
|
||||
'cron_expression' => implode(' ', $model->task_cron),
|
||||
'type' => $model->task_command,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
77
app/Http/Controllers/Api/TaskManualRunController.php
Normal file
77
app/Http/Controllers/Api/TaskManualRunController.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\ArchiveLogsJob;
|
||||
use App\Jobs\BackupRun;
|
||||
use App\Jobs\TaskDownloadRun;
|
||||
use App\Models\Task;
|
||||
use App\Models\User;
|
||||
use App\Notifications\DBNotification;
|
||||
use App\Notifications\MailTaskRunNotification;
|
||||
use App\Traits\LogsTaskActivity;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class TaskManualRunController extends Controller
|
||||
{
|
||||
use LogsTaskActivity, RespondsWithHttpStatus;
|
||||
|
||||
protected $monitoredTask;
|
||||
|
||||
/**
|
||||
* Run the specified task.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function runManualTask(Request $request)
|
||||
{
|
||||
$executionStartTime = microtime(true);
|
||||
try {
|
||||
$task = Task::FindOrFail($request->id)->toArray();
|
||||
} catch (\Exception $e) {
|
||||
return $this->failureResponse($e->getMessage());
|
||||
}
|
||||
|
||||
$this->logTaskStarted($task['id']);
|
||||
|
||||
$download_commands = ['rconfig:download-device', 'rconfig:download-tag', 'rconfig:download-category'];
|
||||
if (in_array($task['task_command'], $download_commands)) {
|
||||
$task['task_command'] = 'rconfig:download-task';
|
||||
|
||||
dispatch(new TaskDownloadRun($task));
|
||||
$executionEndTime = microtime(true);
|
||||
|
||||
$this->logTaskFinished($task['id']);
|
||||
|
||||
return $this->successResponse('TaskDownloadRun task pushed to queues successfully.');
|
||||
}
|
||||
|
||||
$this->logTaskFinished($task['id']);
|
||||
|
||||
return $this->failureResponse('Something went wrong, as no tasks were sent to the queues!');
|
||||
}
|
||||
|
||||
private function logTheTask($task)
|
||||
{
|
||||
$logmsg = 'Task command "' . $task['task_command'] . ' ' . $task['id'] . '" was run with ID:' . $task['id'];
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $logmsg, 'cron_scheduler');
|
||||
|
||||
$this->logTaskFinished($task['id']);
|
||||
}
|
||||
|
||||
private function _notifyTaskSend($executionStartTime, $task)
|
||||
{
|
||||
if ($task['task_email_notify'] == 1) {
|
||||
$seconds = round(microtime(true) - $executionStartTime, 2);
|
||||
Notification::send(User::all(), new MailTaskRunNotification($seconds, $task));
|
||||
Notification::send(User::all(), new DBNotification('Scheduled Task Completed', 'Task ID ' . $task['id'] . ' - "' . $task['task_name'] . '" was completed in ' . $executionStartTime, 'system', 'info', 'pficon-info'));
|
||||
}
|
||||
}
|
||||
}
|
85
app/Http/Controllers/Api/TaskReportController.php
Normal file
85
app/Http/Controllers/Api/TaskReportController.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Models\Taskdownloadreport;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class TaskReportController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Taskdownloadreport $model, $modelname = 'taskdownloadreport')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['report_id', 'task_id', 'task_name', 'task_type'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Command $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
$reportfile = report_path().$id.'.html';
|
||||
|
||||
if (File::exists($reportfile)) {
|
||||
return File::get($reportfile);
|
||||
} else {
|
||||
$this->failureResponse('File not found');
|
||||
}
|
||||
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
if (File::exists($model->config_location)) {
|
||||
File::delete($model->config_location);
|
||||
$logmsg = 'Config File : '.$model->config_location.' was deleted';
|
||||
} else {
|
||||
$logmsg = 'Unable to find file from path: '.$model->config_location;
|
||||
$this->failureResponse($logmsg);
|
||||
}
|
||||
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'warn', $logmsg, 'config', '', $model->device_id, 'device');
|
||||
|
||||
return $this->successResponse($logmsg);
|
||||
}
|
||||
|
||||
public function getReport(Request $request)
|
||||
{
|
||||
$reportfile = report_path().$request->id.'.html';
|
||||
|
||||
if (File::exists($reportfile)) {
|
||||
return File::get($reportfile);
|
||||
} else {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'msg' => 'Error',
|
||||
'errors' => 'File not found!',
|
||||
], 422);
|
||||
}
|
||||
}
|
||||
}
|
152
app/Http/Controllers/Api/TemplateController.php
Normal file
152
app/Http/Controllers/Api/TemplateController.php
Normal file
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreTemplateRequest;
|
||||
use App\Models\Template;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
class TemplateController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Template $model, $modelname = 'template')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['fileName', 'templateName'];
|
||||
$result = parent::index($request, $searchCols);
|
||||
|
||||
$result->getCollection()->transform(function ($item) {
|
||||
$item->fileName = basename($item['fileName']);
|
||||
|
||||
return $item;
|
||||
});
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreTemplateRequest $request)
|
||||
{
|
||||
$filedata = $this->prepareYamlFile($request);
|
||||
|
||||
$request['fileName'] = '/app/rconfig/templates/'.$filedata['fileName'];
|
||||
$request['templateName'] = $filedata['templateName'];
|
||||
$request['description'] = $filedata['description'];
|
||||
|
||||
File::put($filedata['filePath'], $request->code);
|
||||
if (! File::exists($filedata['filePath'])) {
|
||||
throw new \Exception('Could create file or write to templates location: '.$filedata['filePath'].PHP_EOL);
|
||||
}
|
||||
|
||||
return parent::storeResource($request->toDTO()->toArray(), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Template $template
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
$result = parent::show($id);
|
||||
$result['code'] = File::get(storage_path().$result['fileName']);
|
||||
$result['fileName'] = basename($result['fileName']);
|
||||
|
||||
return response()->json($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Template $template
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreTemplateRequest $request)
|
||||
{
|
||||
$filedata = $this->prepareYamlFile($request);
|
||||
|
||||
if (File::exists($filedata['filePath'])) {
|
||||
File::delete($filedata['filePath']);
|
||||
}
|
||||
|
||||
File::put($filedata['filePath'], $request->code);
|
||||
if (! File::exists($filedata['filePath'])) {
|
||||
throw new \Exception('Could create file or write to templates location: '.$filedata['filePath'].PHP_EOL);
|
||||
}
|
||||
|
||||
$request['fileName'] = '/app/rconfig/templates/'.$filedata['fileName'];
|
||||
|
||||
$request['templateName'] = $filedata['templateName'];
|
||||
$request['description'] = $filedata['description'];
|
||||
|
||||
return parent::updateResource($id, $request->toDTO()->toArray(), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
$model = parent::destroy($id, 1);
|
||||
|
||||
$filePath = $model->fileName;
|
||||
|
||||
$model->delete();
|
||||
|
||||
if (File::exists(storage_path().$filePath)) {
|
||||
File::delete(storage_path().$filePath);
|
||||
}
|
||||
|
||||
return $this->successResponse(Str::ucfirst($this->modelname).' deleted successfully!');
|
||||
}
|
||||
|
||||
public function getDefaultTemplate()
|
||||
{
|
||||
if (File::exists(storage_path().'/app/rconfig/templates/default.yml')) {
|
||||
return File::get(storage_path().'/app/rconfig/templates/default.yml');
|
||||
}
|
||||
|
||||
return $this->failureResponse('Could not read default.yml file from the path: '.storage_path().'/app/rconfig/templates/default.yml');
|
||||
}
|
||||
|
||||
private function prepareYamlFile($request)
|
||||
{
|
||||
$yamlContents = Yaml::parse($request->code);
|
||||
$fileName = str_replace(' ', '_', $request->fileName);
|
||||
$fileNameArr = pathinfo($fileName);
|
||||
if (! isset($fileNameArr['extension']) || $fileNameArr['extension'] != 'yml') {
|
||||
$fileName = $fileName.'.yml';
|
||||
}
|
||||
$storage_dir = storage_path().'/app/rconfig/templates/';
|
||||
$filePath = $storage_dir.$fileName;
|
||||
|
||||
return $filedata = [
|
||||
'filePath' => $filePath,
|
||||
'fileName' => $fileName,
|
||||
'templateName' => $yamlContents['main']['name'],
|
||||
'description' => $yamlContents['main']['desc'],
|
||||
];
|
||||
}
|
||||
}
|
138
app/Http/Controllers/Api/TemplateGithubController.php
Normal file
138
app/Http/Controllers/Api/TemplateGithubController.php
Normal file
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
class TemplateGithubController extends Controller
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
private $username;
|
||||
|
||||
private $repo;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->username = Config::get('github.git.rconfig-username');
|
||||
$this->repo = Config::get('github.git.rconfig-template-repo');
|
||||
}
|
||||
|
||||
public function import_github_templates()
|
||||
{
|
||||
Artisan::call('rconfig:clone-templates');
|
||||
$result = Artisan::output();
|
||||
$arr = explode("\n", $result);
|
||||
|
||||
if (count($arr) > 0) {
|
||||
$result = 'Successfully downloaded ' . count(File::allFiles(templates_path() . 'rConfig-templates')) . ' templates from \'github.com/rconfig/rconfig-templates\' Github repo';
|
||||
|
||||
return $this->successResponse('Success', $result);
|
||||
} else {
|
||||
$result = 'Exception thrown: Could not connect to repo ';
|
||||
|
||||
return $this->failureResponse($result);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_github_repo_connection()
|
||||
{
|
||||
try {
|
||||
// https://api.github.com/repos/OWNER/REPO/contents/PATH
|
||||
$response = Http::get('https://api.github.com/repos/' . $this->username . '/' . $this->repo . '/contents/')->throw();
|
||||
// dd($response->json());
|
||||
$result['data'] = $response->json();
|
||||
$result['msg'] = 'Successfully connected to rConfig Templates Github repo';
|
||||
|
||||
return $this->successResponse('Success', $result);
|
||||
} catch (\Exception $e) {
|
||||
$result['data'] = '';
|
||||
$result['msg'] = 'Exception thrown: Could not connect to repo - ' . $e->getMessage();
|
||||
|
||||
return $this->failureResponse($result);
|
||||
}
|
||||
}
|
||||
|
||||
public function list_template_repo_folders()
|
||||
{
|
||||
$dirsArray = [];
|
||||
$dstDir = templates_path() . 'rConfig-templates';
|
||||
|
||||
if (is_dir($dstDir)) {
|
||||
$origdirsArray = File::directories($dstDir);
|
||||
foreach ($origdirsArray as $key => $file) {
|
||||
$dirsArray[$key]['path'] = $file;
|
||||
$dirsArray[$key]['name'] = basename($file);
|
||||
}
|
||||
|
||||
$result['data'] = $dirsArray;
|
||||
$result['msg'] = 'Found cloned templates repo folder!';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $result['msg'], 'templates');
|
||||
|
||||
return $this->successResponse('Success', $result);
|
||||
} else {
|
||||
$result['msg'] = 'rConfig-templates is empty, or does not exist. Clone from "https://github.com/rconfig/rconfig-templates" may have failed! Try importing the templates again.!';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $result['msg'], 'templates');
|
||||
|
||||
return $this->failureResponse($result);
|
||||
}
|
||||
}
|
||||
|
||||
public function list_repo_folders_contents(Request $request)
|
||||
{
|
||||
$origListofTemplateFiles = File::glob("{$request->directory}/*.yml");
|
||||
|
||||
// get README.md file
|
||||
File::exists("{$request->directory}/README.md") ? $readmeFile = File::glob("{$request->directory}/README.md") : $readmeFile = [];
|
||||
|
||||
if (count($origListofTemplateFiles) > 0) {
|
||||
foreach ($origListofTemplateFiles as $key => $file) {
|
||||
$listofFiles[$key]['path'] = $file;
|
||||
$listofFiles[$key]['name'] = basename($file);
|
||||
}
|
||||
$result['data'] = $listofFiles;
|
||||
$result['msg'] = 'List of yml templates returned!';
|
||||
|
||||
if (count($readmeFile) > 0) {
|
||||
$result['readme']['path'] = $readmeFile[0];
|
||||
$result['readme']['name'] = basename($readmeFile[0]);
|
||||
}
|
||||
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $result['msg'], 'templates');
|
||||
|
||||
return $this->successResponse('Success', $result);
|
||||
} else {
|
||||
$result['msg'] = 'Unable to return list of yml templates! Check the application logs!';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $result['msg'], 'templates');
|
||||
|
||||
return $this->failureResponse($result);
|
||||
}
|
||||
}
|
||||
|
||||
public function get_template_file_contents(Request $request)
|
||||
{
|
||||
$template['code'] = File::get($request->filepath);
|
||||
$yamlContents = Yaml::parse($template['code']);
|
||||
$template['templateName'] = $yamlContents['main']['name'];
|
||||
$template['description'] = $yamlContents['main']['desc'];
|
||||
if (count($template) > 0) {
|
||||
$result['data'] = $template;
|
||||
$result['msg'] = 'Template content returned!';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $result['msg'], 'templates');
|
||||
|
||||
return $this->successResponse('Success', $result);
|
||||
} else {
|
||||
$result['msg'] = 'Unable to return template content! Check the application logs!';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $result['msg'], 'templates');
|
||||
|
||||
return $this->failureResponse($result);
|
||||
}
|
||||
}
|
||||
}
|
31
app/Http/Controllers/Api/TrackedJobController.php
Normal file
31
app/Http/Controllers/Api/TrackedJobController.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\TrackedJob;
|
||||
use App\Traits\RespondsWithHttpStatus;
|
||||
|
||||
class TrackedJobController extends Controller
|
||||
{
|
||||
use RespondsWithHttpStatus;
|
||||
|
||||
public function __construct(TrackedJob $model, $modelname = 'tracked_job')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Tag $tag
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$result = $this->model::where('device_id', $id)->orderBy('id', 'desc')->first();
|
||||
|
||||
return $this->successResponse('Latest trackable job', $result);
|
||||
}
|
||||
}
|
73
app/Http/Controllers/Api/UserController.php
Normal file
73
app/Http/Controllers/Api/UserController.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreUserRequest;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class UserController extends ApiBaseController
|
||||
{
|
||||
public function __construct(User $model, $modelname = 'user')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['id', 'name', 'username', 'email'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols));
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreUserRequest $request)
|
||||
{
|
||||
return parent::storeResource($request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\User $user
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\User $user
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreUserRequest $request)
|
||||
{
|
||||
return parent::updateResource($id, $request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
return parent::destroy($id);
|
||||
}
|
||||
}
|
73
app/Http/Controllers/Api/VendorController.php
Normal file
73
app/Http/Controllers/Api/VendorController.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Requests\StoreVendorRequest;
|
||||
use App\Models\Vendor;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class VendorController extends ApiBaseController
|
||||
{
|
||||
public function __construct(Vendor $model, $modelname = 'vendor')
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->modelname = $modelname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a listing of the resource.
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function index(Request $request, $searchCols = null, $relationship = null, $withCount = null)
|
||||
{
|
||||
$searchCols = ['vendorname'];
|
||||
|
||||
return response()->json(parent::index($request, $searchCols));
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a newly created resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function store(StoreVendorRequest $request)
|
||||
{
|
||||
return parent::storeResource($request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Display the specified resource.
|
||||
*
|
||||
* @param \App\Models\Vendor $vendor
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function show($id, $relationship = null, $withCount = null)
|
||||
{
|
||||
return parent::show($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the specified resource in storage.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @param \App\Models\Vendor $vendor
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function update($id, StoreVendorRequest $request)
|
||||
{
|
||||
return parent::updateResource($id, $request->toDTO()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the specified resource from storage.
|
||||
*
|
||||
* @param int $id
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function destroy($id, $return = 0)
|
||||
{
|
||||
return parent::destroy($id);
|
||||
}
|
||||
}
|
116
app/Http/Controllers/Api/timezone_list.php
Normal file
116
app/Http/Controllers/Api/timezone_list.php
Normal file
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'Pacific/Midway' => '(GMT-11:00) Midway Island',
|
||||
'US/Samoa' => '(GMT-11:00) Samoa',
|
||||
'US/Hawaii' => '(GMT-10:00) Hawaii',
|
||||
'US/Alaska' => '(GMT-09:00) Alaska',
|
||||
'US/Pacific' => '(GMT-08:00) Pacific Time (US & Canada)',
|
||||
'America/Tijuana' => '(GMT-08:00) Tijuana',
|
||||
'US/Arizona' => '(GMT-07:00) Arizona',
|
||||
'US/Mountain' => '(GMT-07:00) Mountain Time (US & Canada)',
|
||||
'America/Chihuahua' => '(GMT-07:00) Chihuahua',
|
||||
'America/Mazatlan' => '(GMT-07:00) Mazatlan',
|
||||
'America/Mexico_City' => '(GMT-06:00) Mexico City',
|
||||
'America/Monterrey' => '(GMT-06:00) Monterrey',
|
||||
'Canada/Saskatchewan' => '(GMT-06:00) Saskatchewan',
|
||||
'US/Central' => '(GMT-06:00) Central Time (US & Canada)',
|
||||
'US/Eastern' => '(GMT-05:00) Eastern Time (US & Canada)',
|
||||
'US/East-Indiana' => '(GMT-05:00) Indiana (East)',
|
||||
'America/Bogota' => '(GMT-05:00) Bogota',
|
||||
'America/Lima' => '(GMT-05:00) Lima',
|
||||
'America/Caracas' => '(GMT-04:30) Caracas',
|
||||
'Canada/Atlantic' => '(GMT-04:00) Atlantic Time (Canada)',
|
||||
'America/La_Paz' => '(GMT-04:00) La Paz',
|
||||
'America/Santiago' => '(GMT-04:00) Santiago',
|
||||
'Canada/Newfoundland' => '(GMT-03:30) Newfoundland',
|
||||
'America/Buenos_Aires' => '(GMT-03:00) Buenos Aires',
|
||||
'Greenland' => '(GMT-03:00) Greenland',
|
||||
'Atlantic/Stanley' => '(GMT-02:00) Stanley',
|
||||
'Atlantic/Azores' => '(GMT-01:00) Azores',
|
||||
'Atlantic/Cape_Verde' => '(GMT-01:00) Cape Verde Is.',
|
||||
'Africa/Casablanca' => '(GMT) Casablanca',
|
||||
'Europe/Dublin' => '(GMT) Dublin',
|
||||
'Europe/Lisbon' => '(GMT) Lisbon',
|
||||
'Europe/London' => '(GMT) London',
|
||||
'Africa/Monrovia' => '(GMT) Monrovia',
|
||||
'Europe/Amsterdam' => '(GMT+01:00) Amsterdam',
|
||||
'Europe/Belgrade' => '(GMT+01:00) Belgrade',
|
||||
'Europe/Berlin' => '(GMT+01:00) Berlin',
|
||||
'Europe/Bratislava' => '(GMT+01:00) Bratislava',
|
||||
'Europe/Brussels' => '(GMT+01:00) Brussels',
|
||||
'Europe/Budapest' => '(GMT+01:00) Budapest',
|
||||
'Europe/Copenhagen' => '(GMT+01:00) Copenhagen',
|
||||
'Europe/Ljubljana' => '(GMT+01:00) Ljubljana',
|
||||
'Europe/Madrid' => '(GMT+01:00) Madrid',
|
||||
'Europe/Paris' => '(GMT+01:00) Paris',
|
||||
'Europe/Prague' => '(GMT+01:00) Prague',
|
||||
'Europe/Rome' => '(GMT+01:00) Rome',
|
||||
'Europe/Sarajevo' => '(GMT+01:00) Sarajevo',
|
||||
'Europe/Skopje' => '(GMT+01:00) Skopje',
|
||||
'Europe/Stockholm' => '(GMT+01:00) Stockholm',
|
||||
'Europe/Vienna' => '(GMT+01:00) Vienna',
|
||||
'Europe/Warsaw' => '(GMT+01:00) Warsaw',
|
||||
'Europe/Zagreb' => '(GMT+01:00) Zagreb',
|
||||
'Europe/Athens' => '(GMT+02:00) Athens',
|
||||
'Europe/Bucharest' => '(GMT+02:00) Bucharest',
|
||||
'Africa/Cairo' => '(GMT+02:00) Cairo',
|
||||
'Africa/Harare' => '(GMT+02:00) Harare',
|
||||
'Europe/Helsinki' => '(GMT+02:00) Helsinki',
|
||||
'Europe/Istanbul' => '(GMT+02:00) Istanbul',
|
||||
'Asia/Jerusalem' => '(GMT+02:00) Jerusalem',
|
||||
'Europe/Kiev' => '(GMT+02:00) Kyiv',
|
||||
'Europe/Minsk' => '(GMT+02:00) Minsk',
|
||||
'Europe/Riga' => '(GMT+02:00) Riga',
|
||||
'Europe/Sofia' => '(GMT+02:00) Sofia',
|
||||
'Europe/Tallinn' => '(GMT+02:00) Tallinn',
|
||||
'Europe/Vilnius' => '(GMT+02:00) Vilnius',
|
||||
'Asia/Baghdad' => '(GMT+03:00) Baghdad',
|
||||
'Asia/Kuwait' => '(GMT+03:00) Kuwait',
|
||||
'Africa/Nairobi' => '(GMT+03:00) Nairobi',
|
||||
'Asia/Riyadh' => '(GMT+03:00) Riyadh',
|
||||
'Europe/Moscow' => '(GMT+03:00) Moscow',
|
||||
'Asia/Tehran' => '(GMT+03:30) Tehran',
|
||||
'Asia/Baku' => '(GMT+04:00) Baku',
|
||||
'Europe/Volgograd' => '(GMT+04:00) Volgograd',
|
||||
'Asia/Muscat' => '(GMT+04:00) Muscat',
|
||||
'Asia/Tbilisi' => '(GMT+04:00) Tbilisi',
|
||||
'Asia/Yerevan' => '(GMT+04:00) Yerevan',
|
||||
'Asia/Kabul' => '(GMT+04:30) Kabul',
|
||||
'Asia/Karachi' => '(GMT+05:00) Karachi',
|
||||
'Asia/Tashkent' => '(GMT+05:00) Tashkent',
|
||||
'Asia/Kolkata' => '(GMT+05:30) Kolkata',
|
||||
'Asia/Kathmandu' => '(GMT+05:45) Kathmandu',
|
||||
'Asia/Yekaterinburg' => '(GMT+06:00) Ekaterinburg',
|
||||
'Asia/Almaty' => '(GMT+06:00) Almaty',
|
||||
'Asia/Dhaka' => '(GMT+06:00) Dhaka',
|
||||
'Asia/Novosibirsk' => '(GMT+07:00) Novosibirsk',
|
||||
'Asia/Bangkok' => '(GMT+07:00) Bangkok',
|
||||
'Asia/Jakarta' => '(GMT+07:00) Jakarta',
|
||||
'Asia/Krasnoyarsk' => '(GMT+08:00) Krasnoyarsk',
|
||||
'Asia/Chongqing' => '(GMT+08:00) Chongqing',
|
||||
'Asia/Hong_Kong' => '(GMT+08:00) Hong Kong',
|
||||
'Asia/Kuala_Lumpur' => '(GMT+08:00) Kuala Lumpur',
|
||||
'Australia/Perth' => '(GMT+08:00) Perth',
|
||||
'Asia/Singapore' => '(GMT+08:00) Singapore',
|
||||
'Asia/Taipei' => '(GMT+08:00) Taipei',
|
||||
'Asia/Ulaanbaatar' => '(GMT+08:00) Ulaan Bataar',
|
||||
'Asia/Urumqi' => '(GMT+08:00) Urumqi',
|
||||
'Asia/Irkutsk' => '(GMT+09:00) Irkutsk',
|
||||
'Asia/Seoul' => '(GMT+09:00) Seoul',
|
||||
'Asia/Tokyo' => '(GMT+09:00) Tokyo',
|
||||
'Australia/Adelaide' => '(GMT+09:30) Adelaide',
|
||||
'Australia/Darwin' => '(GMT+09:30) Darwin',
|
||||
'Asia/Yakutsk' => '(GMT+10:00) Yakutsk',
|
||||
'Australia/Brisbane' => '(GMT+10:00) Brisbane',
|
||||
'Australia/Canberra' => '(GMT+10:00) Canberra',
|
||||
'Pacific/Guam' => '(GMT+10:00) Guam',
|
||||
'Australia/Hobart' => '(GMT+10:00) Hobart',
|
||||
'Australia/Melbourne' => '(GMT+10:00) Melbourne',
|
||||
'Pacific/Port_Moresby' => '(GMT+10:00) Port Moresby',
|
||||
'Australia/Sydney' => '(GMT+10:00) Sydney',
|
||||
'Asia/Vladivostok' => '(GMT+11:00) Vladivostok',
|
||||
'Asia/Magadan' => '(GMT+12:00) Magadan',
|
||||
'Pacific/Auckland' => '(GMT+12:00) Auckland',
|
||||
'Pacific/Fiji' => '(GMT+12:00) Fiji',
|
||||
];
|
40
app/Http/Controllers/Auth/ConfirmPasswordController.php
Normal file
40
app/Http/Controllers/Auth/ConfirmPasswordController.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Foundation\Auth\ConfirmsPasswords;
|
||||
|
||||
class ConfirmPasswordController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Confirm Password Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This controller is responsible for handling password confirmations and
|
||||
| uses a simple trait to include the behavior. You're free to explore
|
||||
| this trait and override any functions that require customization.
|
||||
|
|
||||
*/
|
||||
|
||||
use ConfirmsPasswords;
|
||||
|
||||
/**
|
||||
* Where to redirect users when the intended url fails.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $redirectTo = RouteServiceProvider::HOME;
|
||||
|
||||
/**
|
||||
* Create a new controller instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware('auth');
|
||||
}
|
||||
}
|
32
app/Http/Controllers/Auth/ForgotPasswordController.php
Normal file
32
app/Http/Controllers/Auth/ForgotPasswordController.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
|
||||
|
||||
class ForgotPasswordController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Password Reset Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This controller is responsible for handling password reset emails and
|
||||
| includes a trait which assists in sending these notifications from
|
||||
| your application to your users. Feel free to explore this trait.
|
||||
|
|
||||
*/
|
||||
|
||||
use SendsPasswordResetEmails;
|
||||
|
||||
/**
|
||||
* Create a new controller instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware('guest');
|
||||
}
|
||||
}
|
192
app/Http/Controllers/Auth/LoginController.php
Normal file
192
app/Http/Controllers/Auth/LoginController.php
Normal file
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Foundation\Auth\AuthenticatesUsers;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Login Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This controller handles authenticating users for the application and
|
||||
| redirecting them to your home screen. The controller uses a trait
|
||||
| to conveniently provide its functionality to your applications.
|
||||
|
|
||||
*/
|
||||
|
||||
use AuthenticatesUsers;
|
||||
|
||||
/**
|
||||
* Where to redirect users after login.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $redirectTo = '/dashboard';
|
||||
|
||||
/**
|
||||
* Login username to be used by the controller.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $username;
|
||||
|
||||
/**
|
||||
* Create a new controller instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware('guest')->except('logout');
|
||||
$this->username = $this->findUsername();
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$user = null;
|
||||
|
||||
if (!$user) {
|
||||
$msg = 'Authenticating user (' . $request->username . ') against database.';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $msg, 'authentication');
|
||||
|
||||
$this->validateLogin($request); // replaced $this->validateLogin in AuthenticatesUsers.php with private version in this class
|
||||
|
||||
if ($this->hasTooManyLoginAttempts($request)) {
|
||||
$this->fireLockoutEvent($request);
|
||||
|
||||
return $this->sendLockoutResponse($request);
|
||||
}
|
||||
|
||||
if ($this->attemptLogin($request)) {
|
||||
if ($user = Auth::user()) {
|
||||
$msg = 'Local authentication for user ' . $user->email;
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'info', $msg, 'authentication');
|
||||
|
||||
$user->last_login = Carbon::now();
|
||||
$user->save();
|
||||
|
||||
return redirect('/dashboard');
|
||||
}
|
||||
|
||||
return $this->sendLoginResponse($request);
|
||||
}
|
||||
|
||||
$this->incrementLoginAttempts($request);
|
||||
$msg = 'Local authentication failed.';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $msg, 'authentication');
|
||||
|
||||
return $this->sendFailedLoginResponse($request);
|
||||
}
|
||||
}
|
||||
|
||||
public function showLoginForm()
|
||||
{
|
||||
$banner = \App\Models\Banner::select('login_banner')->get();
|
||||
$login_banner = $banner[0]->login_banner;
|
||||
|
||||
return view('auth.login', compact('login_banner'));
|
||||
}
|
||||
|
||||
public function showLoggedOut()
|
||||
{
|
||||
// assume we're logged out at this point
|
||||
return view('auth.logged-out');
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
$this->guard()->logout();
|
||||
$request->session()->flush();
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect('/login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the login username to be used by the controller.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function findUsername()
|
||||
{
|
||||
$login = request()->input('username');
|
||||
|
||||
$fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
|
||||
|
||||
request()->merge([$fieldType => $login]);
|
||||
|
||||
return $fieldType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get username property.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function username()
|
||||
{
|
||||
return $this->username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the user login request.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return void
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
private function validateLogin(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'username' => 'required|string',
|
||||
'password' => 'required|string',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect the user after determining they are locked out.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
private function sendLockoutResponse(Request $request)
|
||||
{
|
||||
$seconds = $this->limiter()->availableIn(
|
||||
$this->throttleKey($request)
|
||||
);
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'username' => [trans('auth.throttle', [
|
||||
'seconds' => $seconds,
|
||||
'minutes' => ceil($seconds / 60),
|
||||
])],
|
||||
])->status(Response::HTTP_TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the failed login response instance.
|
||||
*
|
||||
* @param \Illuminate\Http\Request $request
|
||||
* @return \Symfony\Component\HttpFoundation\Response
|
||||
*
|
||||
* @throws \Illuminate\Validation\ValidationException
|
||||
*/
|
||||
protected function sendFailedLoginResponse(Request $request)
|
||||
{
|
||||
throw ValidationException::withMessages([
|
||||
'username' => [trans('auth.failed')],
|
||||
]);
|
||||
}
|
||||
}
|
71
app/Http/Controllers/Auth/RegisterController.php
Normal file
71
app/Http/Controllers/Auth/RegisterController.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Auth\RegistersUsers;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class RegisterController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Register Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This controller handles the registration of new users as well as their
|
||||
| validation and creation. By default this controller uses a trait to
|
||||
| provide this functionality without requiring any additional code.
|
||||
|
|
||||
*/
|
||||
|
||||
use RegistersUsers;
|
||||
|
||||
/**
|
||||
* Where to redirect users after registration.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $redirectTo = '/dashboard';
|
||||
|
||||
/**
|
||||
* Create a new controller instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware('guest');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a validator for an incoming registration request.
|
||||
*
|
||||
* @param array $data
|
||||
* @return \Illuminate\Contracts\Validation\Validator
|
||||
*/
|
||||
protected function validator(array $data)
|
||||
{
|
||||
return Validator::make($data, [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
|
||||
'password' => ['required', 'string', 'min:8', 'confirmed'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user instance after a valid registration.
|
||||
*
|
||||
* @param array $data
|
||||
* @return \App\Models\User
|
||||
*/
|
||||
protected function create(array $data)
|
||||
{
|
||||
return User::create([
|
||||
'name' => $data['name'],
|
||||
'email' => $data['email'],
|
||||
'password' => \Hash::make($data['password']),
|
||||
]);
|
||||
}
|
||||
}
|
41
app/Http/Controllers/Auth/ResetPasswordController.php
Normal file
41
app/Http/Controllers/Auth/ResetPasswordController.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Foundation\Auth\ResetsPasswords;
|
||||
|
||||
class ResetPasswordController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Password Reset Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This controller is responsible for handling password reset requests
|
||||
| and uses a simple trait to include this behavior. You're free to
|
||||
| explore this trait and override any methods you wish to tweak.
|
||||
|
|
||||
*/
|
||||
|
||||
use ResetsPasswords;
|
||||
|
||||
/**
|
||||
* Where to redirect users after resetting their password.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $redirectTo = '/dashboard';
|
||||
|
||||
use ResetsPasswords;
|
||||
|
||||
/**
|
||||
* Create a new controller instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware('guest');
|
||||
}
|
||||
}
|
42
app/Http/Controllers/Auth/VerificationController.php
Normal file
42
app/Http/Controllers/Auth/VerificationController.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Foundation\Auth\VerifiesEmails;
|
||||
|
||||
class VerificationController extends Controller
|
||||
{
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Email Verification Controller
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This controller is responsible for handling email verification for any
|
||||
| user that recently registered with the application. Emails may also
|
||||
| be re-sent if the user didn't receive the original email message.
|
||||
|
|
||||
*/
|
||||
|
||||
use VerifiesEmails;
|
||||
|
||||
/**
|
||||
* Where to redirect users after verification.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $redirectTo = RouteServiceProvider::HOME;
|
||||
|
||||
/**
|
||||
* Create a new controller instance.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$this->middleware('auth');
|
||||
$this->middleware('signed')->only('verify');
|
||||
$this->middleware('throttle:60,1')->only('verify', 'resend');
|
||||
}
|
||||
}
|
49
app/Http/Controllers/Connections/MainConnectionManager.php
Normal file
49
app/Http/Controllers/Connections/MainConnectionManager.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections;
|
||||
|
||||
use App\Http\Controllers\Connections\Params\DeviceParams;
|
||||
|
||||
class MainConnectionManager
|
||||
{
|
||||
protected $deviceRecord;
|
||||
|
||||
protected $deviceParamsObject;
|
||||
|
||||
protected $telnetConnection;
|
||||
|
||||
protected $sshConnection;
|
||||
|
||||
protected $debug;
|
||||
|
||||
public function __construct(array $deviceRecord, $debug)
|
||||
{
|
||||
$this->deviceRecord = $deviceRecord;
|
||||
$this->debug = $debug;
|
||||
}
|
||||
|
||||
public function setupConnectAndReturnOutput()
|
||||
{
|
||||
$this->getAllConnectionParamsArray();
|
||||
|
||||
if ($this->deviceParamsObject->connect['protocol'] == 'telnet') {
|
||||
$this->telnetConnection = new TelnetConnectionManager($this->deviceParamsObject, $this->debug);
|
||||
|
||||
return $this->telnetConnection->telnetConnectionAndOutput();
|
||||
} elseif ($this->deviceParamsObject->connect['protocol'] == 'ssh') {
|
||||
$this->sshConnection = new SSHConnectionManager($this->deviceParamsObject, $this->debug);
|
||||
|
||||
return $this->sshConnection->SshConnectionAndOutput();
|
||||
} else {
|
||||
throw new \Exception('Error Processing '.__CLASS__.' - '.__FUNCTION__.' Request. Your rConfig template file could be invalid.', 1);
|
||||
}
|
||||
}
|
||||
|
||||
public function getAllConnectionParamsArray()
|
||||
{
|
||||
$deviceParams = new DeviceParams($this->deviceRecord);
|
||||
$this->deviceParamsObject = $deviceParams->getAllDeviceParams();
|
||||
|
||||
return $this->deviceParamsObject;
|
||||
}
|
||||
}
|
42
app/Http/Controllers/Connections/Params/ConnectionParams.php
Normal file
42
app/Http/Controllers/Connections/Params/ConnectionParams.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Params;
|
||||
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
/**
|
||||
* Loads & Stores template, per devicesParams object in an object, configuration parameters as passed form rConfig Templates file loaded for this specific devices templateId
|
||||
* Test Covered in BasicCommandsTest
|
||||
*
|
||||
* @author Stephen_Stack
|
||||
*/
|
||||
class ConnectionParams
|
||||
{
|
||||
private $templateId;
|
||||
|
||||
public function __construct(int $templateId)
|
||||
{
|
||||
$this->templateId = $templateId;
|
||||
}
|
||||
|
||||
public function getTemplateParams()
|
||||
{
|
||||
$templateArray = $this->getTemplateArray();
|
||||
|
||||
return $this->templateToArray($templateArray['code']);
|
||||
}
|
||||
|
||||
private function getTemplateArray()
|
||||
{
|
||||
$loadtemplate = new LoadTemplate($this->templateId);
|
||||
|
||||
return json_decode($loadtemplate->load(), true);
|
||||
}
|
||||
|
||||
private function templateToArray($code)
|
||||
{
|
||||
$yamlContents = Yaml::parse($code);
|
||||
|
||||
return $yamlContents;
|
||||
}
|
||||
}
|
38
app/Http/Controllers/Connections/Params/DeviceParams.php
Normal file
38
app/Http/Controllers/Connections/Params/DeviceParams.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Loads & Stores device params in an object, device specific parameters as passed from rConfig database
|
||||
*/
|
||||
|
||||
namespace App\Http\Controllers\Connections\Params;
|
||||
|
||||
class DeviceParams
|
||||
{
|
||||
private $deviceParams;
|
||||
|
||||
public function __construct(array $deviceRecord)
|
||||
{
|
||||
$this->deviceParams = $deviceRecord;
|
||||
}
|
||||
|
||||
public function getAllDeviceParams()
|
||||
{
|
||||
return (object) $this->getDeviceParamsCombinedArray();
|
||||
}
|
||||
|
||||
private function getDeviceParamsCombinedArray()
|
||||
{
|
||||
$deviceConnectionArray = $this->getDeviceConnectionparams();
|
||||
$deviceConnectionArray['deviceparams'] = $this->deviceParams;
|
||||
|
||||
return $deviceConnectionArray;
|
||||
}
|
||||
|
||||
private function getDeviceConnectionparams()
|
||||
{
|
||||
|
||||
$template_data = new ConnectionParams($this->deviceParams['device_template']);
|
||||
|
||||
return $template_data->getTemplateParams();
|
||||
}
|
||||
}
|
46
app/Http/Controllers/Connections/Params/LoadTemplate.php
Normal file
46
app/Http/Controllers/Connections/Params/LoadTemplate.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Params;
|
||||
|
||||
use App\Models\Template;
|
||||
use File;
|
||||
|
||||
/**
|
||||
* Retrives template file from fielsystem, and loads to object
|
||||
* Test Covered in BasicCommandsTest
|
||||
*
|
||||
* @author Stephen_Stack
|
||||
*/
|
||||
class LoadTemplate
|
||||
{
|
||||
private $templateId;
|
||||
|
||||
public function __construct(int $templateId)
|
||||
{
|
||||
$this->templateId = $templateId;
|
||||
}
|
||||
|
||||
public function load()
|
||||
{
|
||||
$path = Template::select('fileName')->where('id', $this->templateId)->get();
|
||||
// dd($path);
|
||||
if (count($path) === 0) {
|
||||
throw new \Exception('Template not found');
|
||||
}
|
||||
$fullpath = storage_path() . $path[0]->fileName;
|
||||
$templateArr['fileName'] = $this->getFileBasename($fullpath);
|
||||
$templateArr['code'] = $this->getTemplateCode($fullpath);
|
||||
|
||||
return json_encode($templateArr);
|
||||
}
|
||||
|
||||
private function getFileBasename($filePath)
|
||||
{
|
||||
return basename($filePath);
|
||||
}
|
||||
|
||||
private function getTemplateCode($filePath)
|
||||
{
|
||||
return File::get($filePath);
|
||||
}
|
||||
}
|
169
app/Http/Controllers/Connections/SSH/Connect.php
Normal file
169
app/Http/Controllers/Connections/SSH/Connect.php
Normal file
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\SSH;
|
||||
|
||||
use App\CustomClasses\SetDeviceStatus;
|
||||
use App\Models\User;
|
||||
use App\Notifications\DBDeviceConnectionFailureNotification;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use phpseclib3\Net\SSH2;
|
||||
|
||||
class Connect
|
||||
{
|
||||
public $connection;
|
||||
|
||||
/* MAIN */
|
||||
public $name;
|
||||
public $desc;
|
||||
|
||||
/* CONNECT */
|
||||
public $timeout;
|
||||
public $protocol;
|
||||
public $port;
|
||||
|
||||
/* AUTH */
|
||||
public $sshInteractive;
|
||||
public $usernamePrompt;
|
||||
public $passwordPrompt;
|
||||
public $enable;
|
||||
public $enableCmd;
|
||||
public $enablePassPrmpt;
|
||||
public $hpAnyKeyStatus;
|
||||
public $hpAnyKeyPrmpt;
|
||||
public $sshPrivKey;
|
||||
public $ssh_key_id;
|
||||
|
||||
/* CONFIG */
|
||||
public $linebreak;
|
||||
public $paging;
|
||||
public $pagingCmd;
|
||||
public $resetPagingCmd;
|
||||
public $pagerPrompt;
|
||||
public $pagerPromptCmd;
|
||||
public $saveConfig;
|
||||
public $exitCmd;
|
||||
public $isMikrotik;
|
||||
|
||||
/* DEVICEPARAMS */
|
||||
public $device_id;
|
||||
public $hostname;
|
||||
public $username;
|
||||
public $password;
|
||||
public $devicePrompt;
|
||||
public $enablePrompt;
|
||||
public $enableModePassword;
|
||||
public $cliDebugStatus;
|
||||
public $command;
|
||||
public $commands;
|
||||
public $snippet;
|
||||
|
||||
/* OPTIONS */
|
||||
public $AnsiHost;
|
||||
public $setWindowSize;
|
||||
public $setTerminalDimensions;
|
||||
|
||||
|
||||
public function __construct(object $deviceParamsObject, $debug)
|
||||
{
|
||||
// dd($deviceParamsObject);
|
||||
/* MAIN */
|
||||
$this->name = $deviceParamsObject->main['name'];
|
||||
$this->desc = $deviceParamsObject->main['desc'];
|
||||
/* CONNECT */
|
||||
$this->timeout = $deviceParamsObject->connect['timeout'];
|
||||
$this->protocol = $deviceParamsObject->connect['protocol'];
|
||||
$this->port = $deviceParamsObject->deviceparams['device_port_override'] ?? $deviceParamsObject->connect['port'];
|
||||
/* AUTH */
|
||||
$this->sshInteractive = $deviceParamsObject->auth['sshInteractive'] ?? null;
|
||||
$this->usernamePrompt = $deviceParamsObject->auth['username'];
|
||||
$this->passwordPrompt = $deviceParamsObject->auth['password'];
|
||||
$this->enable = $deviceParamsObject->auth['enable'];
|
||||
$this->enableCmd = $deviceParamsObject->auth['enableCmd'];
|
||||
$this->enablePassPrmpt = $deviceParamsObject->auth['enablePassPrmpt'];
|
||||
$this->hpAnyKeyStatus = $deviceParamsObject->auth['hpAnyKeyStatus'];
|
||||
$this->hpAnyKeyPrmpt = $deviceParamsObject->auth['hpAnyKeyPrmpt'];
|
||||
// Optional SSHPrivKey Setting
|
||||
$this->sshPrivKey = isset($deviceParamsObject->auth['sshPrivKey']) ? $deviceParamsObject->auth['sshPrivKey'] : null;
|
||||
/* CONFIG */
|
||||
$this->linebreak = $deviceParamsObject->config['linebreak'];
|
||||
$this->paging = $deviceParamsObject->config['paging'];
|
||||
$this->pagingCmd = $deviceParamsObject->config['pagingCmd'];
|
||||
$this->resetPagingCmd = $deviceParamsObject->config['resetPagingCmd'];
|
||||
$this->pagerPrompt = $deviceParamsObject->config['pagerPrompt'];
|
||||
$this->pagerPromptCmd = $deviceParamsObject->config['pagerPromptCmd'];
|
||||
$this->saveConfig = $deviceParamsObject->config['saveConfig'];
|
||||
$this->exitCmd = $deviceParamsObject->config['exitCmd'];
|
||||
/* DEVICEPARAMS */
|
||||
$this->device_id = $deviceParamsObject->deviceparams['id'];
|
||||
$this->hostname = $deviceParamsObject->deviceparams['device_ip'];
|
||||
if (filter_var($this->hostname, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
|
||||
//setup ipv6 string for fsockopen
|
||||
$this->hostname = '[' . $this->hostname . ']';
|
||||
}
|
||||
$this->username = $deviceParamsObject->deviceparams['device_username'];
|
||||
$this->password = $deviceParamsObject->deviceparams['device_password'];
|
||||
$this->enableModePassword = $deviceParamsObject->deviceparams['device_enable_password'];
|
||||
$this->ssh_key_id = $deviceParamsObject->deviceparams['ssh_key_id'];
|
||||
$this->devicePrompt = $deviceParamsObject->deviceparams['device_main_prompt'];
|
||||
$this->enablePrompt = $deviceParamsObject->deviceparams['device_enable_prompt'];
|
||||
$this->isMikrotik = isset($deviceParamsObject->config['isMikrotik']) ? $deviceParamsObject->config['isMikrotik'] : null;
|
||||
|
||||
/* OPTIONS */
|
||||
$this->AnsiHost = isset($deviceParamsObject->options['AnsiHost']) ? $deviceParamsObject->options['AnsiHost'] : null;
|
||||
$this->setWindowSize = isset($deviceParamsObject->options['setWindowSize']) ? $deviceParamsObject->options['setWindowSize'] : null;
|
||||
// next is implementation of https://api.phpseclib.org/2.0/File_ANSI.html#method_setDimensions
|
||||
$this->setTerminalDimensions = isset($deviceParamsObject->options['setTerminalDimensions']) ? $deviceParamsObject->options['setTerminalDimensions'] : null;
|
||||
|
||||
$cliDebugStatus = ($debug === true) ? 1 : 0; // convert debug to boolean
|
||||
$this->cliDebugStatus = $cliDebugStatus;
|
||||
$this->commands = $deviceParamsObject->deviceparams['commands'];
|
||||
if (isset($deviceParamsObject->deviceparams['snippet'])) {
|
||||
$this->snippet = $deviceParamsObject->deviceparams['snippet'];
|
||||
}
|
||||
}
|
||||
|
||||
public function connect()
|
||||
{
|
||||
$this->sshPortValidOrDefault();
|
||||
$this->connection = new SSH2($this->hostname, $this->port, $this->timeout);
|
||||
if ($this->setWindowSize != null) {
|
||||
$this->connection->setWindowSize($this->setWindowSize[0], $this->setWindowSize[1]);
|
||||
}
|
||||
if ($this->setTerminalDimensions != null) {
|
||||
$this->connection->setTerminalDimensions = [$this->setTerminalDimensions[0], $this->setTerminalDimensions[1]];
|
||||
}
|
||||
$this->checkConnectionState();
|
||||
$this->SSHdebuggingCheck();
|
||||
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
private function sshPortValidOrDefault()
|
||||
{
|
||||
if ($this->port == null || $this->port <= 0 || $this->port > 65535) {
|
||||
return $this->port;
|
||||
} else {
|
||||
return $this->port;
|
||||
}
|
||||
}
|
||||
|
||||
private function SSHdebuggingCheck()
|
||||
{
|
||||
// debugging check - real time output on CLI
|
||||
if ($this->cliDebugStatus && !defined('NET_SSH2_LOGGING')) {
|
||||
define('NET_SSH2_LOGGING', SSH2::LOG_COMPLEX);
|
||||
}
|
||||
}
|
||||
|
||||
private function checkConnectionState()
|
||||
{
|
||||
if (!$this->connection) {
|
||||
$logmsg = 'Unable to connect to ' . ($this->hostname . ' - ID:' . $this->device_id);
|
||||
Notification::send(User::allUsersAndRecipients(), new DBDeviceConnectionFailureNotification($logmsg, $this->device_id));
|
||||
(new SetDeviceStatus($this->device_id, 0))->setDeviceStatus();
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->hostname, $this->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
132
app/Http/Controllers/Connections/SSH/Login.php
Normal file
132
app/Http/Controllers/Connections/SSH/Login.php
Normal file
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\SSH;
|
||||
|
||||
// use App\Http\use App\Services\Connections\Params\DeviceParams;\SSH\Send;
|
||||
// use App\Http\use App\Services\Connections\Params\DeviceParams;\SSH\Read;
|
||||
// use App\Http\use App\Services\Connections\Params\DeviceParams;\SSH\Quit;
|
||||
use App\Models\PrivSshKeys;
|
||||
use phpseclib3\Crypt\PublicKeyLoader;
|
||||
use phpseclib3\Net\SSH2;
|
||||
|
||||
class Login
|
||||
{
|
||||
protected $send;
|
||||
protected $read;
|
||||
protected $connectionObj;
|
||||
protected $loadedKey;
|
||||
|
||||
public function __construct(object $connectionObj)
|
||||
{
|
||||
$this->connectionObj = $connectionObj;
|
||||
// $this->send = new Send($this->connectionObj->connection);
|
||||
// $this->read = new Read($this->connectionObj);
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
|
||||
$this->escapeTildeChars();
|
||||
|
||||
if ($this->connectionObj->sshPrivKey) {
|
||||
// $privKeyRecord = PrivSshKeys::find($this->connectionObj->ssh_key_id);
|
||||
// $privateKey = file_get_contents($privKeyRecord->privSshKeyFile);
|
||||
|
||||
// $this->loadedKey = PublicKeyLoader::load($privateKey);
|
||||
// $this->privKeyloginErrorCheck();
|
||||
} else {
|
||||
$this->loginErrorCheck();
|
||||
$this->HPChecks();
|
||||
}
|
||||
|
||||
if ($this->connectionObj->sshInteractive === 'on') {
|
||||
$this->interactive_login();
|
||||
}
|
||||
|
||||
if ($this->connectionObj->enable == 'on') {
|
||||
$this->enableModeLogin();
|
||||
} else {
|
||||
$this->sendPagingCommand();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public function interactive_login()
|
||||
{
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->usernamePrompt . '~', SSH2::READ_REGEX);
|
||||
$this->connectionObj->connection->write($this->connectionObj->username . "\n");
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->passwordPrompt . '~', SSH2::READ_REGEX);
|
||||
$this->connectionObj->connection->write($this->connectionObj->password . "\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public function loginErrorCheck()
|
||||
{
|
||||
if (!$this->connectionObj->connection->login($this->connectionObj->username, $this->connectionObj->password)) {
|
||||
$logmsg = 'Authentication Failed for ' . ($this->connectionObj->hostname . ' ID:' . $this->connectionObj->device_id) . '. Or wrong prompt configured for this device! Check your device settings.';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->connectionObj->hostname, $this->connectionObj->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function privKeyloginErrorCheck()
|
||||
{
|
||||
if (!$this->connectionObj->connection->login($this->connectionObj->username, $this->loadedKey)) {
|
||||
$logmsg = 'Authentication Failed for ' . ($this->connectionObj->hostname . ' ID:' . $this->connectionObj->device_id) . '. Or wrong prompt configured for this device! Check your device settings.';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->connectionObj->hostname, $this->connectionObj->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function sendPagingCommand()
|
||||
{
|
||||
if ($this->connectionObj->paging === 'on') {
|
||||
// dd('~' . $this->connectionObj->devicePrompt . '~');
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
$this->connectionObj->connection->write($this->connectionObj->pagingCmd . "\n");
|
||||
sleep(1);
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
}
|
||||
|
||||
private function enableModeLogin()
|
||||
{
|
||||
$this->connectionObj->connection->write($this->connectionObj->enableCmd . "\n");
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->enablePassPrmpt . '~', SSH2::READ_REGEX);
|
||||
$this->connectionObj->connection->write($this->connectionObj->enableModePassword . "\n");
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
if ($this->connectionObj->paging === 'on') {
|
||||
$this->connectionObj->connection->write($this->connectionObj->pagingCmd . "\n");
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
$this->connectionObj->connection->write("\n"); // to line break after command output
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
|
||||
private function HPChecks()
|
||||
{
|
||||
if ($this->connectionObj->hpAnyKeyStatus === 'on') {
|
||||
// $this->connectionObj->connection->read($this->connectionObj->hpAnyKeyPrmpt, SSH2::READ_REGEX);
|
||||
$this->connectionObj->connection->write("\n");
|
||||
$this->connectionObj->connection->write("\n");
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
}
|
||||
|
||||
private function escapeTildeChars()
|
||||
{
|
||||
|
||||
// if the devicePrompt or enablePassPrmpt contains a tilde (~) character, it must be escaped with a backslash character. i.e. (\~)
|
||||
// zoho ticket #302 - devices with tilde in main prompt or enable prompt do not back up.
|
||||
// this is because we use tilde as the regex delimiter in the ssh2 library
|
||||
// so we need to escape the tilde character in the prompt with a backslash
|
||||
$this->connectionObj->pagingCmd = str_replace('~', '\~', $this->connectionObj->pagingCmd);
|
||||
$this->connectionObj->enableCmd = str_replace('~', '\~', $this->connectionObj->enableCmd);
|
||||
$this->connectionObj->enablePassPrmpt = str_replace('~', '\~', $this->connectionObj->enablePassPrmpt);
|
||||
$this->connectionObj->devicePrompt = str_replace('~', '\~', $this->connectionObj->devicePrompt);
|
||||
}
|
||||
}
|
18
app/Http/Controllers/Connections/SSH/Send.php
Normal file
18
app/Http/Controllers/Connections/SSH/Send.php
Normal file
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\SSH;
|
||||
|
||||
class Send
|
||||
{
|
||||
protected $connectionObj;
|
||||
|
||||
public function __construct($connectionObj)
|
||||
{
|
||||
$this->connectionObj = $connectionObj;
|
||||
}
|
||||
|
||||
public function sendString($command)
|
||||
{
|
||||
return $this->connectionObj->connection->write($command . "\r");
|
||||
}
|
||||
}
|
135
app/Http/Controllers/Connections/SSH/SendCommand.php
Normal file
135
app/Http/Controllers/Connections/SSH/SendCommand.php
Normal file
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\SSH;
|
||||
|
||||
use phpseclib3\File\ANSI;
|
||||
use phpseclib3\Net\SSH2;
|
||||
|
||||
class SendCommand
|
||||
{
|
||||
protected $send;
|
||||
|
||||
protected $read;
|
||||
|
||||
protected $sendSnippet;
|
||||
|
||||
protected $connectionObj;
|
||||
|
||||
protected $data;
|
||||
|
||||
public function __construct(object $connectionObj)
|
||||
{
|
||||
$this->connectionObj = $connectionObj;
|
||||
$this->send = new Send($this->connectionObj);
|
||||
}
|
||||
|
||||
public function sendShowCommand($command)
|
||||
{
|
||||
if ($this->connectionObj->sshPrivKey) {
|
||||
return $this->connectionObj->connection->exec($command);
|
||||
} else {
|
||||
|
||||
if ($this->connectionObj->AnsiHost === 'yes') {
|
||||
return $this->ansiShowCommand($command);
|
||||
}
|
||||
|
||||
if ($this->connectionObj->isMikrotik === 'yes') {
|
||||
// need to remove prompt. Mikrotik does not respond well to having a prompt configured. See the mikrotik function in the console rconfig:test command
|
||||
$this->connectionObj->devicePrompt = '';
|
||||
$this->data = $this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
|
||||
return $this->standardShowCommand($command);
|
||||
}
|
||||
}
|
||||
|
||||
private function ansiShowCommand($command)
|
||||
{
|
||||
$ansi = new ANSI();
|
||||
if (isset($this->connectionObj->connection->setTerminalDimensions)) {
|
||||
$ansi->setDimensions($this->connectionObj->connection->setTerminalDimensions[0], $this->connectionObj->connection->setTerminalDimensions[1]);
|
||||
}
|
||||
$ansi->appendString($this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX));
|
||||
$this->send->sendString($command);
|
||||
$ansi->appendString($this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX));
|
||||
// echo $ansi->getScreen(); // outputs current screen HTML
|
||||
// echo $ansi->getHistory(); // outputs current history HTML
|
||||
// $this->data = htmlspecialchars_decode(strip_tags($ansi->getScreen())); //$ansi->getScreen() returns what'd be seen on the current screen. In the case of top this is desirable
|
||||
$this->data = htmlspecialchars_decode(strip_tags($ansi->getHistory())); // getHistory() used to retired all output see ANSi examples in http://phpseclib.sourceforge.net/ssh/2.0/examples.html
|
||||
if ($this->data) {
|
||||
$this->data = $this->explodeTextToArray();
|
||||
$this->dropFirstAndLastLinesFromArray();
|
||||
$result = $this->createArrayFromData();
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
private function standardShowCommand($command)
|
||||
{
|
||||
$this->send->sendString($command);
|
||||
|
||||
// if ($this->connectionObj->isMikrotik === 'yes') {
|
||||
// $this->data = preg_replace('/\[[K', '', $this->data);
|
||||
// $this->data = preg_replace('/\[K', '', $this->data);
|
||||
// }
|
||||
|
||||
// check if this is a HP device
|
||||
if ($this->connectionObj->hpAnyKeyStatus === 'on') {
|
||||
// hack to get around procurve VT100 special characters
|
||||
// https://stackoverflow.com/questions/9913342/byte-to-character-conversion-for-a-telnet-stream
|
||||
// https://stackoverflow.com/questions/1176904/php-how-to-remove-all-non-printable-characters-in-a-string
|
||||
$this->data = $this->connectionObj->connection->read();
|
||||
$this->data = preg_replace('/[^[:print:]\r\n]/', '', $this->data);
|
||||
$this->data = preg_replace('/\[24;0HE/', '', $this->data);
|
||||
$this->data = preg_replace('/\[24;38H/', '', $this->data);
|
||||
$this->data = preg_replace('/\[24;19H/', '', $this->data);
|
||||
$this->data = preg_replace('/\[?25h/', '', $this->data);
|
||||
$this->data = preg_replace('/\[1;24r/', '', $this->data);
|
||||
$this->data = preg_replace('/\[24;1H/', '', $this->data);
|
||||
$this->data = preg_replace('/\[2K/', '', $this->data);
|
||||
} else {
|
||||
// dd($this->connectionObj->devicePrompt);
|
||||
$this->data = $this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
|
||||
if ($this->data) {
|
||||
$this->data = $this->explodeTextToArray();
|
||||
$this->dropFirstAndLastLinesFromArray();
|
||||
$result = $this->createArrayFromData();
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
public function resetPagingCommand()
|
||||
{
|
||||
$this->send->sendString($this->connectionObj->resetPagingCmd);
|
||||
$this->connectionObj->connection->read('~' . $this->connectionObj->devicePrompt . '~', SSH2::READ_REGEX);
|
||||
}
|
||||
|
||||
public function explodeTextToArray()
|
||||
{
|
||||
return explode("\r\n", $this->data);
|
||||
}
|
||||
|
||||
public function dropFirstAndLastLinesFromArray()
|
||||
{
|
||||
array_shift($this->data); //drops the command that was run from the output
|
||||
array_pop($this->data); // removes last line, usually a prompt
|
||||
}
|
||||
|
||||
public function createArrayFromData()
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if (count($this->data) > 0) {
|
||||
foreach ($this->data as $line) {
|
||||
$line = explode("\r\n", $line);
|
||||
array_push($result, $line[0]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
95
app/Http/Controllers/Connections/SSHConnectionManager.php
Normal file
95
app/Http/Controllers/Connections/SSHConnectionManager.php
Normal file
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections;
|
||||
|
||||
use App\CustomClasses\SetDeviceStatus;
|
||||
use App\Http\Controllers\Connections\SSH\Connect;
|
||||
use App\Http\Controllers\Connections\SSH\Login;
|
||||
use App\Http\Controllers\Connections\SSH\SendCommand;
|
||||
|
||||
class SSHConnectionManager
|
||||
{
|
||||
protected $deviceParamsObject;
|
||||
|
||||
protected $connectionObj;
|
||||
|
||||
protected $loginObj;
|
||||
|
||||
protected $SendCommandObj;
|
||||
|
||||
protected $debug;
|
||||
|
||||
public function __construct($deviceParamsObject, $debug)
|
||||
{
|
||||
$this->deviceParamsObject = $deviceParamsObject;
|
||||
$this->debug = $debug;
|
||||
}
|
||||
|
||||
public function SSHConnectionAndOutput()
|
||||
{
|
||||
if ($this->loadSSHConnect() === false) {
|
||||
return false;
|
||||
}
|
||||
if ($this->loadSSHLogin() === false) {
|
||||
(new SetDeviceStatus($this->connectionObj->device_id, 0))->setDeviceStatus();
|
||||
$logmsg = 'There was an authentication or connection issue with ' . $this->deviceParamsObject->deviceparams['device_name'];
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->connectionObj->hostname, $this->connectionObj->device_id, 'device');
|
||||
|
||||
return ['failure' => $logmsg];
|
||||
}
|
||||
|
||||
$outputArray = $this->sendSSHCommand();
|
||||
|
||||
$this->setDebuggingOutput();
|
||||
$this->SSHDisconnect();
|
||||
|
||||
return $outputArray;
|
||||
}
|
||||
|
||||
private function loadSSHConnect()
|
||||
{
|
||||
$this->connectionObj = new Connect($this->deviceParamsObject, $this->debug);
|
||||
$this->connectionObj->connect();
|
||||
}
|
||||
|
||||
private function loadSSHLogin()
|
||||
{
|
||||
try {
|
||||
$this->loginObj = new Login($this->connectionObj);
|
||||
$this->loginObj->login();
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
// \activityLogIt($e->message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function setDebuggingOutput()
|
||||
{
|
||||
if ($this->connectionObj->cliDebugStatus === 1) {
|
||||
dump($this->connectionObj->connection->getlog());
|
||||
}
|
||||
}
|
||||
|
||||
private function sendSSHCommand()
|
||||
{
|
||||
$output = null;
|
||||
$this->SendCommandObj = new SendCommand($this->connectionObj);
|
||||
foreach ($this->connectionObj->commands as $command) {
|
||||
$output[$command] = $this->SendCommandObj->sendShowCommand($command);
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
private function SSHDisconnect()
|
||||
{
|
||||
// send resetPagingCommand if paging is set to on
|
||||
if ($this->connectionObj->paging === 'on') {
|
||||
$this->SendCommandObj->resetPagingCommand();
|
||||
}
|
||||
|
||||
$this->connectionObj->connection->disconnect();
|
||||
}
|
||||
}
|
174
app/Http/Controllers/Connections/Telnet/Connect.php
Normal file
174
app/Http/Controllers/Connections/Telnet/Connect.php
Normal file
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
use App\CustomClasses\SetDeviceStatus;
|
||||
use App\Models\User;
|
||||
use App\Notifications\DBDeviceConnectionFailureNotification;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
|
||||
class Connect
|
||||
{
|
||||
public $connection;
|
||||
|
||||
/* MAIN */
|
||||
public $name;
|
||||
|
||||
public $desc;
|
||||
|
||||
/* CONNECT */
|
||||
public $timeout;
|
||||
|
||||
public $protocol;
|
||||
|
||||
public $port;
|
||||
|
||||
/* AUTH */
|
||||
public $usernamePrompt;
|
||||
|
||||
public $passwordPrompt;
|
||||
|
||||
public $enable;
|
||||
|
||||
public $enableCmd;
|
||||
|
||||
public $enablePassPrmpt;
|
||||
|
||||
public $hpAnyKeyStatus;
|
||||
|
||||
public $hpAnyKeyPrmpt;
|
||||
|
||||
/* CONFIG */
|
||||
public $linebreak;
|
||||
|
||||
public $paging;
|
||||
|
||||
public $pagingCmd;
|
||||
|
||||
public $resetPagingCmd;
|
||||
|
||||
public $pagerPrompt;
|
||||
|
||||
public $pagerPromptCmd;
|
||||
|
||||
public $saveConfig;
|
||||
|
||||
public $exitCmd;
|
||||
|
||||
/* DEVICEPARAMS */
|
||||
public $device_id;
|
||||
|
||||
public $hostname;
|
||||
|
||||
public $username;
|
||||
|
||||
public $password;
|
||||
|
||||
public $devicePrompt;
|
||||
|
||||
public $cliDebugStatus;
|
||||
|
||||
public $command;
|
||||
|
||||
|
||||
/* OPTIONS */
|
||||
public $AnsiHost;
|
||||
|
||||
/* VT100 */
|
||||
public $hasSplashScreen;
|
||||
public $splashScreenReadToText;
|
||||
public $splashScreenSendControlCode;
|
||||
|
||||
public function __construct(object $deviceParamsObject, $debug)
|
||||
{
|
||||
// dd($deviceParamsObject);
|
||||
/* MAIN */
|
||||
$this->name = $deviceParamsObject->main['name'];
|
||||
$this->desc = $deviceParamsObject->main['desc'];
|
||||
/* CONNECT */
|
||||
$this->timeout = $deviceParamsObject->connect['timeout'];
|
||||
$this->protocol = $deviceParamsObject->connect['protocol'];
|
||||
$this->port = $deviceParamsObject->deviceparams['device_port_override'] ?? $deviceParamsObject->connect['port'];
|
||||
/* AUTH */
|
||||
$this->usernamePrompt = $deviceParamsObject->auth['username'];
|
||||
$this->passwordPrompt = $deviceParamsObject->auth['password'];
|
||||
$this->enable = $deviceParamsObject->auth['enable'];
|
||||
$this->enableCmd = $deviceParamsObject->auth['enableCmd'];
|
||||
$this->enablePassPrmpt = $deviceParamsObject->auth['enablePassPrmpt'];
|
||||
$this->hpAnyKeyStatus = $deviceParamsObject->auth['hpAnyKeyStatus'];
|
||||
$this->hpAnyKeyPrmpt = $deviceParamsObject->auth['hpAnyKeyPrmpt'];
|
||||
// Optional SSHPrivKey Setting
|
||||
$this->sshPrivKey = isset($deviceParamsObject->auth['sshPrivKey']) ? $deviceParamsObject->auth['sshPrivKey'] : null;
|
||||
/* CONFIG */
|
||||
$this->linebreak = $deviceParamsObject->config['linebreak'];
|
||||
$this->paging = $deviceParamsObject->config['paging'];
|
||||
$this->pagingCmd = $deviceParamsObject->config['pagingCmd'];
|
||||
$this->resetPagingCmd = $deviceParamsObject->config['resetPagingCmd'];
|
||||
$this->pagerPrompt = $deviceParamsObject->config['pagerPrompt'];
|
||||
$this->pagerPromptCmd = $deviceParamsObject->config['pagerPromptCmd'];
|
||||
$this->saveConfig = $deviceParamsObject->config['saveConfig'];
|
||||
$this->exitCmd = $deviceParamsObject->config['exitCmd'];
|
||||
/* DEVICEPARAMS */
|
||||
$this->device_id = $deviceParamsObject->deviceparams['id'];
|
||||
$this->hostname = $deviceParamsObject->deviceparams['device_ip'];
|
||||
if (filter_var($this->hostname, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
|
||||
//setup ipv6 string for fsockopen
|
||||
$this->hostname = '[' . $this->hostname . ']';
|
||||
}
|
||||
$this->username = $deviceParamsObject->deviceparams['device_username'];
|
||||
$this->password = $deviceParamsObject->deviceparams['device_password'];
|
||||
$this->enableModePassword = $deviceParamsObject->deviceparams['device_enable_password'];
|
||||
$this->devicePrompt = $deviceParamsObject->deviceparams['device_main_prompt'];
|
||||
$this->enablePrompt = $deviceParamsObject->deviceparams['device_enable_prompt'];
|
||||
/* OPTIONS */
|
||||
$this->AnsiHost = isset($deviceParamsObject->options['AnsiHost']) ? $deviceParamsObject->options['AnsiHost'] : null; // ssh option only - keeping here for consistency
|
||||
$this->setWindowSize = isset($deviceParamsObject->options['setWindowSize']) ? $deviceParamsObject->options['setWindowSize'] : null; // ssh option only - keeping here for consistency
|
||||
$this->setTerminalDimensions = isset($deviceParamsObject->options['setTerminalDimensions']) ? $deviceParamsObject->options['setTerminalDimensions'] : null; // ssh option only - keeping here for consistency
|
||||
|
||||
/* VT100 */
|
||||
$this->hasSplashScreen = isset($deviceParamsObject->vt100['hasSplashScreen']) ? $deviceParamsObject->vt100['hasSplashScreen'] : null;
|
||||
$this->splashScreenReadToText = isset($deviceParamsObject->vt100['splashScreenReadToText']) ? $deviceParamsObject->vt100['splashScreenReadToText'] : null;
|
||||
$this->splashScreenSendControlCode = isset($deviceParamsObject->vt100['splashScreenSendControlCode']) ? $deviceParamsObject->vt100['splashScreenSendControlCode'] : null;
|
||||
|
||||
$this->cliDebugStatus = $debug;
|
||||
$this->commands = $deviceParamsObject->deviceparams['commands'];
|
||||
}
|
||||
|
||||
public function connect()
|
||||
{
|
||||
$this->telnetPortValidOrDefault();
|
||||
$this->connection = @fsockopen($this->hostname, $this->port, $errno, $errstr, $this->timeout);
|
||||
if ($this->checkConnectionState() === false) {
|
||||
return false;
|
||||
}
|
||||
$this->setStreamTimeout();
|
||||
|
||||
return $this->connection;
|
||||
}
|
||||
|
||||
private function telnetPortValidOrDefault()
|
||||
{
|
||||
if ($this->port == null || $this->port <= 0 || $this->port > 65535) {
|
||||
return $this->port;
|
||||
} else {
|
||||
return $this->port;
|
||||
}
|
||||
}
|
||||
|
||||
private function setStreamTimeout()
|
||||
{
|
||||
return stream_set_timeout($this->connection, $this->timeout);
|
||||
}
|
||||
|
||||
private function checkConnectionState()
|
||||
{
|
||||
if (!$this->connection) {
|
||||
$logmsg = 'Unable to connect to ' . ($this->hostname . ' - ID:' . $this->device_id);
|
||||
Notification::send(User::all(), new DBDeviceConnectionFailureNotification($logmsg, $this->device_id));
|
||||
(new SetDeviceStatus($this->device_id, 0))->setDeviceStatus();
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->hostname, $this->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
76
app/Http/Controllers/Connections/Telnet/Login.php
Normal file
76
app/Http/Controllers/Connections/Telnet/Login.php
Normal file
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
use App\CustomClasses\SetDeviceStatus;
|
||||
|
||||
class Login
|
||||
{
|
||||
protected $send;
|
||||
|
||||
protected $read;
|
||||
|
||||
protected $connectionObj;
|
||||
|
||||
public function __construct(object $connectionObj)
|
||||
{
|
||||
// dd($connectionObj);
|
||||
$this->connectionObj = $connectionObj;
|
||||
$this->send = new Send($this->connectionObj->connection);
|
||||
$this->read = new Read($this->connectionObj);
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
|
||||
if (isset($this->connectionObj->hasSplashScreen) && $this->connectionObj->hasSplashScreen == 'on') {
|
||||
// avaya login
|
||||
$this->read->readTo($this->connectionObj->splashScreenReadToText);
|
||||
$this->send->sendControlCode($this->connectionObj->splashScreenSendControlCode);
|
||||
}
|
||||
|
||||
if ($this->connectionObj->usernamePrompt != "") {
|
||||
$this->read->readTo($this->connectionObj->usernamePrompt);
|
||||
$this->send->sendString($this->connectionObj->username);
|
||||
}
|
||||
|
||||
$this->read->readTo($this->connectionObj->passwordPrompt);
|
||||
$this->send->sendString($this->connectionObj->password);
|
||||
|
||||
if ($this->connectionObj->enable == 'on') {
|
||||
$devicePromptValid = $this->enableModeLogin();
|
||||
} else {
|
||||
$devicePromptValid = $this->read->readTo($this->connectionObj->devicePrompt);
|
||||
}
|
||||
|
||||
$this->send->sendString($this->connectionObj->pagingCmd);
|
||||
$this->read->readTo($this->connectionObj->devicePrompt);
|
||||
|
||||
return $this->loginErrorCheck($devicePromptValid);
|
||||
}
|
||||
|
||||
private function loginErrorCheck($devicePromptValid)
|
||||
{
|
||||
if ($devicePromptValid != true) {
|
||||
(new SetDeviceStatus($this->connectionObj->device_id, 0))->setDeviceStatus();
|
||||
$logmsg = 'Authentication Failed for ' . ($this->connectionObj->hostname . ' ID:' . $this->connectionObj->device_id) . '. Or wrong prompt configured for this device! Check your device settings.';
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->connectionObj->hostname, $this->connectionObj->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function enableModeLogin()
|
||||
{
|
||||
// ADD HP LOGIN HERE AFTER
|
||||
// dd($this->connectionObj);
|
||||
$this->read->readTo($this->connectionObj->enablePrompt);
|
||||
$this->send->sendString($this->connectionObj->enableCmd);
|
||||
$this->read->readTo($this->connectionObj->enablePassPrmpt);
|
||||
$this->send->sendString($this->connectionObj->enableModePassword);
|
||||
|
||||
return $this->read->readTo($this->connectionObj->devicePrompt);
|
||||
}
|
||||
}
|
22
app/Http/Controllers/Connections/Telnet/Logout.php
Normal file
22
app/Http/Controllers/Connections/Telnet/Logout.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
class Logout
|
||||
{
|
||||
protected $connectionObj;
|
||||
|
||||
protected $quit;
|
||||
|
||||
public function __construct(object $connectionObj)
|
||||
{
|
||||
// dd($connectionObj);
|
||||
$this->connectionObj = $connectionObj;
|
||||
$this->quit = new Quit($this->connectionObj);
|
||||
}
|
||||
|
||||
public function logout()
|
||||
{
|
||||
return $this->quit->closeTelnet();
|
||||
}
|
||||
}
|
62
app/Http/Controllers/Connections/Telnet/Quit.php
Normal file
62
app/Http/Controllers/Connections/Telnet/Quit.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
class Quit
|
||||
{
|
||||
private $connectionObj;
|
||||
|
||||
protected $send;
|
||||
|
||||
protected $read;
|
||||
|
||||
public function __construct(object $connectionObj)
|
||||
{
|
||||
$this->connectionObj = $connectionObj;
|
||||
$this->send = new Send($this->connectionObj->connection);
|
||||
$this->read = new Read($this->connectionObj);
|
||||
}
|
||||
|
||||
public function closeTelnet()
|
||||
{
|
||||
$this->checkConnectionStatus();
|
||||
$this->resetPagingCmd();
|
||||
$this->sendSaveConfig();
|
||||
$this->sendExitCmd();
|
||||
|
||||
fclose($this->connectionObj->connection);
|
||||
}
|
||||
|
||||
private function checkConnectionStatus()
|
||||
{
|
||||
if (!$this->connectionObj->connection) {
|
||||
$logmsg = 'Telnet connection already closed for ' . ($this->connectionObj->hostname . ' ID:' . $this->connectionObj->device_id);
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->connectionObj->hostname, $this->connectionObj->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function resetPagingCmd()
|
||||
{
|
||||
if (!empty($this->connectionObj->resetPagingCmd)) {
|
||||
$this->send->sendString($this->connectionObj->resetPagingCmd);
|
||||
$this->read->readTo($this->connectionObj->devicePrompt);
|
||||
}
|
||||
}
|
||||
|
||||
private function sendSaveConfig()
|
||||
{
|
||||
if (!empty($this->connectionObj->saveConfig)) {
|
||||
$this->send->sendString($this->connectionObj->saveConfig);
|
||||
$this->read->readTo($this->connectionObj->devicePrompt);
|
||||
}
|
||||
}
|
||||
|
||||
private function sendExitCmd()
|
||||
{
|
||||
if (!empty($this->connectionObj->exitCmd)) {
|
||||
$this->send->sendString($this->connectionObj->exitCmd);
|
||||
}
|
||||
}
|
||||
}
|
101
app/Http/Controllers/Connections/Telnet/Read.php
Normal file
101
app/Http/Controllers/Connections/Telnet/Read.php
Normal file
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
class Read
|
||||
{
|
||||
// private $filterarray = [
|
||||
// 'Access',
|
||||
// ' ',
|
||||
// '--More--',
|
||||
// 'chr(8)'
|
||||
// ];
|
||||
protected $connection;
|
||||
|
||||
protected $cliDebugStatus;
|
||||
|
||||
protected $pagerPrompt;
|
||||
|
||||
private $character;
|
||||
|
||||
protected $data;
|
||||
|
||||
private $prompt;
|
||||
|
||||
protected $send;
|
||||
|
||||
public function __construct($connectionObj)
|
||||
{
|
||||
$this->connection = $connectionObj->connection;
|
||||
$this->cliDebugStatus = $connectionObj->cliDebugStatus;
|
||||
$this->pagerPrompt = $connectionObj->pagerPrompt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read from socket until $prompt
|
||||
*
|
||||
* @param string $prompt Single character or string
|
||||
*/
|
||||
public function readTo($prompt)
|
||||
{
|
||||
$this->prompt = $prompt;
|
||||
$this->errorIfNoConnection();
|
||||
|
||||
while (($this->character = fgetc($this->connection)) !== false) {
|
||||
$this->data .= $this->character;
|
||||
if ($this->readToPrompt()) {
|
||||
break;
|
||||
}
|
||||
// if($this->cliDebugStatus) {echo $this->character;}
|
||||
|
||||
}
|
||||
|
||||
return $this->readToPrompt(); // this will end while loop on a match
|
||||
}
|
||||
|
||||
private function readToPrompt()
|
||||
{
|
||||
if (preg_match('/' . $this->prompt . '$/', $this->data)) {
|
||||
if ($this->cliDebugStatus) {
|
||||
dump($this->data);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// $this->keystrokeOnMatchToPageDownConfig();
|
||||
// $promptLength = gmp_strval(gmp_neg(strlen($this->prompt)));
|
||||
// if (substr(trim($this->data), $promptLength) === $this->prompt)
|
||||
// {
|
||||
// if($this->cliDebugStatus) { dump($this->data); }
|
||||
// return true;
|
||||
// }
|
||||
}
|
||||
|
||||
public function getDataStream()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
private function errorIfNoConnection()
|
||||
{
|
||||
if (!$this->connection) {
|
||||
throw new \Exception('Telnet connection failed');
|
||||
}
|
||||
}
|
||||
|
||||
// public function keystrokeOnMatchToPageDownConfig()
|
||||
// {
|
||||
// // dump(strpos($this->data, '--More--'));
|
||||
// if (strpos($this->data, $this->pagerPrompt) != false) {
|
||||
// $this->send = new Send($this->connection);
|
||||
// $this->send->sendString(" ");
|
||||
// }
|
||||
// }
|
||||
|
||||
/* FOR FUTURE USE */
|
||||
// private function filterData()
|
||||
// {
|
||||
// array_map(function ($filter){
|
||||
// $this->data = str_replace($filter, "", $this->data);
|
||||
// }, $this->filterarray);
|
||||
// }
|
||||
}
|
24
app/Http/Controllers/Connections/Telnet/Send.php
Normal file
24
app/Http/Controllers/Connections/Telnet/Send.php
Normal file
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
class Send
|
||||
{
|
||||
protected $connection;
|
||||
|
||||
public function __construct($connection)
|
||||
{
|
||||
$this->connection = $connection;
|
||||
}
|
||||
|
||||
public function sendString($command)
|
||||
{
|
||||
fwrite($this->connection, $command . "\r\n");
|
||||
}
|
||||
|
||||
public function sendControlCode($code)
|
||||
{
|
||||
sleep(1);
|
||||
fwrite($this->connection, $code); // ASCII code for Ctrl+Y
|
||||
}
|
||||
}
|
72
app/Http/Controllers/Connections/Telnet/SendCommand.php
Normal file
72
app/Http/Controllers/Connections/Telnet/SendCommand.php
Normal file
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections\Telnet;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SendCommand extends Read
|
||||
{
|
||||
protected $send;
|
||||
|
||||
protected $read;
|
||||
|
||||
|
||||
protected $connectionObj;
|
||||
|
||||
public function __construct(object $connectionObj)
|
||||
{
|
||||
$this->connectionObj = $connectionObj;
|
||||
$this->send = new Send($this->connectionObj->connection);
|
||||
$this->read = new Read($this->connectionObj);
|
||||
}
|
||||
|
||||
public function sendShowCommand($command)
|
||||
{
|
||||
// command contains var replace it
|
||||
$command = $this->replaceVariables($command);
|
||||
|
||||
$this->send->sendString($command);
|
||||
if ($this->read->readTo($this->connectionObj->devicePrompt) == true) {
|
||||
// $this->read->data is inherited by Read class extentsion/ inheritence
|
||||
$this->read->data = $this->explodeTextToArray();
|
||||
$this->dropFirstAndLastLinesFromArray();
|
||||
$result = $this->createArrayFromData();
|
||||
$this->read->data = ''; // reset after converting the data object to array from the read class - just above!
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
private function explodeTextToArray()
|
||||
{
|
||||
return explode("\r\n", $this->read->data);
|
||||
}
|
||||
|
||||
private function dropFirstAndLastLinesFromArray()
|
||||
{
|
||||
array_shift($this->read->data); //drops the command that was run from the output
|
||||
array_pop($this->read->data); // removes last line, usually a prompt
|
||||
}
|
||||
|
||||
private function createArrayFromData()
|
||||
{
|
||||
$result = [];
|
||||
if (count($this->read->data) > 0) {
|
||||
foreach ($this->read->data as $line) {
|
||||
$line = explode("\r\n", $line);
|
||||
array_push($result, $line[0]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private function replaceVariables($command)
|
||||
{
|
||||
if (Str::contains($command, '{deviceid}')) {
|
||||
$command = str_replace('{deviceid}', $this->connectionObj->device_id, $command);
|
||||
}
|
||||
|
||||
return $command;
|
||||
}
|
||||
}
|
82
app/Http/Controllers/Connections/TelnetConnectionManager.php
Normal file
82
app/Http/Controllers/Connections/TelnetConnectionManager.php
Normal file
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Connections;
|
||||
|
||||
use App\CustomClasses\SetDeviceStatus;
|
||||
use App\Http\Controllers\Connections\Telnet\Connect;
|
||||
use App\Http\Controllers\Connections\Telnet\Login;
|
||||
use App\Http\Controllers\Connections\Telnet\Logout;
|
||||
use App\Http\Controllers\Connections\Telnet\SendCommand;
|
||||
|
||||
class TelnetConnectionManager
|
||||
{
|
||||
protected $deviceParamsObject;
|
||||
|
||||
protected $connectionObj;
|
||||
|
||||
protected $loginObj;
|
||||
|
||||
protected $SendCommandObj;
|
||||
|
||||
protected $debug;
|
||||
|
||||
public function __construct($deviceParamsObject, $debug)
|
||||
{
|
||||
$this->deviceParamsObject = $deviceParamsObject;
|
||||
$this->debug = $debug;
|
||||
}
|
||||
|
||||
public function telnetConnectionAndOutput()
|
||||
{
|
||||
if ($this->loadTelnetConnect() === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->loadTelnetLogin() === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->SendCommandObj = new SendCommand($this->connectionObj);
|
||||
$outputArray = $this->sendTelnetCommand();
|
||||
|
||||
$this->loadTelnetLogout();
|
||||
|
||||
return $outputArray;
|
||||
}
|
||||
|
||||
private function loadTelnetConnect()
|
||||
{
|
||||
$this->connectionObj = new Connect($this->deviceParamsObject, $this->debug);
|
||||
|
||||
return $this->connectionObj->connect();
|
||||
}
|
||||
|
||||
private function loadTelnetLogin()
|
||||
{
|
||||
$this->loginObj = new Login($this->connectionObj);
|
||||
|
||||
if (!$this->loginObj->login()) {
|
||||
(new SetDeviceStatus($this->connectionObj->device_id, 0))->setDeviceStatus();
|
||||
$logmsg = 'There was an authentication or connection issue with ' . $this->deviceParamsObject->deviceparams['device_name'];
|
||||
activityLogIt(__CLASS__, __FUNCTION__, 'error', $logmsg, 'connection', $this->connectionObj->hostname, $this->connectionObj->device_id, 'device');
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private function sendTelnetCommand()
|
||||
{
|
||||
$output = null;
|
||||
foreach ($this->connectionObj->commands as $command) {
|
||||
$output[$command] = $this->SendCommandObj->sendShowCommand($command);
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
private function loadTelnetLogout()
|
||||
{
|
||||
$logout = new Logout($this->connectionObj);
|
||||
$logout->logout();
|
||||
}
|
||||
}
|
13
app/Http/Controllers/Controller.php
Normal file
13
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Bus\DispatchesJobs;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
|
||||
}
|
11
app/Http/Controllers/SpaController.php
Normal file
11
app/Http/Controllers/SpaController.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
class SpaController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return view('spa');
|
||||
}
|
||||
}
|
202
app/Http/Helpers.php
Normal file
202
app/Http/Helpers.php
Normal file
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* Return active class if current path begins with this path.
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
// function setActive($path)
|
||||
// {
|
||||
// return Request::is($path . '*') ? ' active' : '';
|
||||
// }
|
||||
|
||||
/**
|
||||
* Return Formatted Text From Path Stub
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function setPageName($path)
|
||||
{
|
||||
$title = str_replace('-', ' ', $path);
|
||||
$title = ucwords($title);
|
||||
|
||||
return $title;
|
||||
}
|
||||
/**
|
||||
* Return Formatted Text From Path Stub
|
||||
*
|
||||
* @param string $path
|
||||
* @return string
|
||||
*/
|
||||
function setPagePath($path)
|
||||
{
|
||||
$title = str_replace('-', ' ', $path);
|
||||
// $title = ucwords($title);
|
||||
return $title;
|
||||
}
|
||||
|
||||
function rconfig_appdir_path()
|
||||
{
|
||||
return Config::get('rConfig.app_dir_path');
|
||||
}
|
||||
|
||||
function rconfig_appdir_storage_path()
|
||||
{
|
||||
return rconfig_appdir_path() . '/storage';
|
||||
}
|
||||
|
||||
function rconfig_app_path()
|
||||
{
|
||||
return rconfig_appdir_storage_path() . '/app/rconfig/';
|
||||
}
|
||||
|
||||
function templates_path()
|
||||
{
|
||||
return rconfig_appdir_storage_path() . '/app/rconfig/templates/';
|
||||
}
|
||||
|
||||
function config_data_path()
|
||||
{
|
||||
return rconfig_appdir_storage_path() . '/app/rconfig/data/';
|
||||
}
|
||||
|
||||
function download_path()
|
||||
{
|
||||
return rconfig_appdir_storage_path() . '/app/rconfig/downloads/';
|
||||
}
|
||||
function report_path()
|
||||
{
|
||||
return rconfig_appdir_storage_path() . '/app/rconfig/reports/';
|
||||
}
|
||||
|
||||
function custom_chown($path)
|
||||
{
|
||||
File::exists('/etc/redhat-release') ? chown($path, 'apache') : chown($path, 'www-data');
|
||||
}
|
||||
|
||||
function isDocker(): bool
|
||||
{
|
||||
return is_file("/.dockerenv");
|
||||
}
|
||||
|
||||
function formatSize($bytes)
|
||||
{
|
||||
$types = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
for ($i = 0; $bytes >= 1024 && $i < (count($types) - 1); $bytes /= 1024, $i++);
|
||||
|
||||
return round($bytes, 2) . ' ' . $types[$i];
|
||||
}
|
||||
|
||||
function dir_size($directory)
|
||||
{
|
||||
$size = 0;
|
||||
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, RecursiveIteratorIterator::SELF_FIRST)) as $file) {
|
||||
$size += $file->getSize();
|
||||
}
|
||||
|
||||
return $size;
|
||||
}
|
||||
|
||||
function diskInfo()
|
||||
{
|
||||
/* get disk space free (in bytes) */
|
||||
$df = disk_free_space('/');
|
||||
/* and get disk space total (in bytes) */
|
||||
$dt = disk_total_space('/');
|
||||
/* now we calculate the disk space used (in bytes) */
|
||||
$du = $dt - $df;
|
||||
/* percentage of disk used - this will be used to also set the width % of the progress bar */
|
||||
$dp = sprintf('%.2f', ($du / $dt) * 100);
|
||||
|
||||
/* and we formate the size from bytes to MB, GB, etc. */
|
||||
|
||||
$df = formatSize($df);
|
||||
$du = formatSize($du);
|
||||
$dt = formatSize($dt);
|
||||
|
||||
$disk = [
|
||||
'Disk Free Space' => $df,
|
||||
'Disk Used Space' => $du,
|
||||
'Disk Total Space' => $dt,
|
||||
'Disk Percent Used' => $dp . '%',
|
||||
];
|
||||
|
||||
return $disk;
|
||||
}
|
||||
|
||||
function getOSInformation()
|
||||
{
|
||||
if (false == function_exists('shell_exec') || false == is_readable('/etc/os-release')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$os = shell_exec('cat /etc/os-release');
|
||||
$listIds = preg_match_all('/.*=/', $os, $matchListIds);
|
||||
$listIds = $matchListIds[0];
|
||||
|
||||
$listVal = preg_match_all('/=.*/', $os, $matchListVal);
|
||||
$listVal = $matchListVal[0];
|
||||
|
||||
array_walk($listIds, function (&$v, $k) {
|
||||
$v = strtolower(str_replace('=', '', $v));
|
||||
});
|
||||
|
||||
array_walk($listVal, function (&$v, $k) {
|
||||
$v = preg_replace('/=|"/', '', $v);
|
||||
});
|
||||
|
||||
return array_combine($listIds, $listVal);
|
||||
}
|
||||
|
||||
function activityLogIt($class, $function, $log_name, $description, $event_type, $device_name = null, $device_id = null, $connection_category = null, $connection_ids = null)
|
||||
{
|
||||
// test covered
|
||||
activity($log_name)
|
||||
->tap(function (Spatie\Activitylog\Contracts\Activity $activity) use ($class, $function, $event_type, $device_name, $device_id, $connection_category, $connection_ids) {
|
||||
$activity->event_type = $event_type;
|
||||
$activity->device_name = $device_name;
|
||||
$activity->device_id = $device_id;
|
||||
$activity->connection_category = $connection_category;
|
||||
$activity->connection_ids = serialize($connection_ids);
|
||||
$activity->class = $class;
|
||||
$activity->function = $function;
|
||||
})
|
||||
->log($description);
|
||||
|
||||
// log_name = severity level
|
||||
// critical - pficon-error-circle-o
|
||||
// error - pficon-error-circle-o
|
||||
// warn - pficon-warning-triangle-o
|
||||
// info - pficon-info
|
||||
// default - pficon-info
|
||||
|
||||
// description
|
||||
// {Class/Function: MSG}
|
||||
|
||||
// event_type
|
||||
// scheduler
|
||||
// downloader
|
||||
// connection
|
||||
// config
|
||||
// backup
|
||||
|
||||
// device_name
|
||||
// string
|
||||
|
||||
// device_id
|
||||
// int
|
||||
|
||||
// connection_ids
|
||||
// int or array
|
||||
|
||||
// connection_category
|
||||
// task
|
||||
// tag
|
||||
// category
|
||||
// device
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user