├── .gitignore
├── LICENSE
├── README.md
├── append.php
├── example.png
├── hcpp_hooks.php
├── local.conf
├── pluginable.php
├── post_install.sh
├── prepend.php
├── screenshot.png
└── v-invoke-plugin
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | logging
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # hestiacp-pluginable
2 | Extend [Hestia Control Panel](https://hestiacp.com) via a simple, WordPress-like plugins API.
3 |
4 | 
5 |
6 | Version 2.x, now with a leaner design that uses HestiaCP 'sanctioned' /etc/hestiacp/local.conf and php.ini's native prepend/append system to extend HestiaCP with little modifications to core files. This makes install/uninstall a lot easier, less intrusive, and more forward compatible with HestiaCP updates. You will also find that version 2.x displays plugins and updates in the existing HestiaCP UI. See (#1 above) 'Updates' and 'Configure' in HestiaCP. Pluginable allows plugins (such as the [NodeApp plugin](https://github.com/virtuosoft-dev/hcpp-nodeapp) #2 above) to customize and react to virtually all aspects of the HestiaCP web UI and [CLI API](https://hestiacp.com/docs/reference/cli.html). Both the pluginable project and plugins that use it can receive updates directly from their respective git repositories.
7 |
8 | ## Requirements
9 |
10 | * Hestia Control Panel version 1.9.X or greater
11 | * Ubuntu or Debian Linux OS
12 |
13 | ## Installation
14 | First, back up your system! This install process will patch (__Read__: ___Permanently Alter___) HestiaCP files and templates. A backup of the original file is created with a timestamp extension, i.e. `domain.sh.bak_2023_06_10_21_02`. The files in the following folders will be altered during installation and after every update:
15 |
16 | * /etc/hestiacp/hooks
17 | * /usr/local/hestia/data/templates/web/php-fpm
18 | * /usr/local/hestia/php/lib
19 | * /usr/local/hestia/func
20 |
21 | > [!Warning]
22 | > Until HestiaCP gets the attention and [funding it deserves (please consider donating or contribute to testing)](https://hestiacp.com/donate.html); ***we recommand turning off auto-updates!!!*** Even though Pluginable is designed to auto-update and re-apply installation patches on HestiaCP core updates, there are not enough resources to test synchronized releases. It is not recommended to enable updates in production at this time. It is always best practice to check this readme before updating Pluginable or HestiaCP.
23 | >
24 | > ***As of this writing Pluginable v2.0.4 has been tested to be compatible with HestiaCP v1.9.3.***
25 | >
26 | > ***To turn off auto-updates:***
27 | > * Via Hestia Control Panel go to, `Server Settings->Updates->Disable Automatic Updates`
28 | > * Via the command line type, `sudo /usr/local/hestia/bin/v-delete-cron-hestia-autoupdate`.
29 |
30 | Clone the latest release version (i.e. replace **v2.0.4** below with the latest release version) to the hooks folder:
31 | ```
32 | sudo git clone --branch v2.0.4 https://github.com/virtuosoft-dev/hestiacp-pluginable /etc/hestiacp/hooks
33 | ```
34 |
35 | Run the post_install.sh script:
36 |
37 | ```
38 | sudo /etc/hestiacp/hooks/post_install.sh
39 | ```
40 |
41 | This will automatically be run anytime HestiaCP updates itself. You may wish to re-run it if you have created new templates in /usr/local/hestia/data/templates/web/php-fpm, as this will include the patches for open_basedir, auto_prepend/append. Currently, this project is compatible with HestiaCP v1.9.X in Nginx + Apache2 with Multi-PHP installation options.
42 |
43 | ---
44 |
45 | ## Uninstallation
46 | Uninstallation of Version 2.X is greatly simplified, removing the risk of perminently altering your HestiaCP install. Follow these steps to restore your stock HestiaCP installation:
47 |
48 | ### Automatic Uninstall
49 | Run the following from the command line:
50 | ```
51 | sudo php -f /etc/hestiacp/hooks/pluginable.php -- --uninstall
52 | ```
53 |
54 | ### Manual Uninstall
55 |
56 | 1) Restore the original patched files with the .bak extension. i.e. if you see `domain.sh.bak_2023_06_10_21_02`, remove the existing `domain.sh` and rename `domain.sh.bak_2023_06_10_21_02` to `domain.sh`. Be sure to choose the .bak extension file with the most recent date if you see more than one. This will need to be performed for the following folders:
57 |
58 | * /usr/local/hestia/data/templates/web/php-fpm
59 | * /usr/local/hestia/php/lib
60 | * /usr/local/hestia/func
61 |
62 | 2) Remove the pluginable files and the local.conf via sudo:
63 |
64 | ```
65 | sudo rm /usr/local/hestia/bin/v-invoke-plugin
66 | sudo rm /etc/hestiacp/local.conf
67 | sudo rm /etc/hestiacp/hooks/*
68 | ```
69 |
70 | 3) Optionally remove Pluginable's data and plugin files:
71 |
72 | ```
73 | sudo rm -rf /usr/local/hestia/plugins
74 | sudo rm -rf /usr/local/hestia/data/hcpp
75 | ```
76 |
77 |
78 |
79 |
80 | ---
81 |
82 |
83 |
84 |
85 | ## Notable Plugins
86 | A number of plugins that use HestiaCP-Pluginable have been updated to the 2.X API and authored by [Stephen J. Carnam @ Virtuosoft](https://virtuosoft.com/donate). They can be found under the HCPP prefix on Virtuosoft's GitHub repo:
87 |
88 | * [HCPP-NodeApp](https://github.com/virtuosoft-dev/hcpp-nodeapp)
89 | * [HCPP-MagicLink](https://github.com/virtuosoft-dev/hcpp-magiclink)
90 |
91 | *Important Note: The following plugins are dependent on [HCPP-NodeApp](https://github.com/virtuosoft-dev/hcpp-nodeapp), ensure you install [HCPP-NodeApp](https://github.com/virtuosoft-dev/hcpp-nodeapp) first!*
92 |
93 | * [HCPP-VitePress](https://github.com/virtuosoft-dev/hcpp-vitepress)
94 | * [HCPP-NodeRED](https://github.com/virtuosoft-dev/hcpp-nodered)
95 | * [HCPP-NodeBB](https://github.com/virtuosoft-dev/hcpp-nodebb)
96 | * [HCPP-Ghost](https://github.com/virtuosoft-dev/hcpp-ghost)
97 |
98 |
112 |
113 | ---
114 |
115 |
116 | ## Creating a plugin
117 | Plugins live in a folder of their own name within `/usr/local/hestia/plugins` and must contain a file called plugin.php. For instance, an example plugin would be at:
118 |
119 | ```
120 | /usr/local/hestia/plugins/example
121 | ```
122 | and contain the file plugin.php at:
123 | ```
124 | /usr/local/hestia/plugins/example/plugin.php
125 | ```
126 |
127 | A plugin can hook and respond to actions that HestiaCP invokes whenever an API call or control panel web page is viewed. A simple hook that can intercept whenever the API call [v-list-users](https://hestiacp.com/docs/reference/cli.html#v-list-user) is invoked, either by the REST API or website control panel would look like:
128 |
129 | ```
130 | add_action( 'v_list_users', function( $args ) {
138 |
139 | global $hcpp;
140 | $hcpp->logging = true;
141 | $hcpp->log( $args );
142 | return $args;
143 |
144 | });
145 | ```
146 |
147 | The `Plugin URI` is used by Pluginable to check for newer releases from the respective GitHub repository. The `Description` should be short and breif; it will be used to describe the plugin on the updates page (see screenshot at the top of this document). It is important that an $hcpp->add_action hook returns (passes along) the incoming argument (the `$args` parameter above). An optional third parameter can be passed for priority with the default being 10, [just like how WordPress does it](https://developer.wordpress.org/reference/functions/add_action/).
148 |
149 | The above sample plugin will write the arguments to `/tmp/hcpp.log` (if logging is on, see 'Debug Logging' below).
150 |
151 | Note that the hook is the same name as the HestiaCP command line API *but with underscores in place of hyphens*.
152 |
153 | ### Extending HCPP_Hooks Class
154 | Using the HCPP_Hooks class can greatly simplify plugin authoring. You may wish to group all of your plugin's action hooks, methods, and properties into a class and register it with Pluginable to organize your plugin's behaviors. A complex plugin that uses the traditional API can be found in the [HCPP-NodeApp plugin](https://github.com/virtuosoft-dev/hcpp-nodeapp). But a much simpler example using the HCPP_Hooks class can be found in the [HCPP-VitePress plugin](https://github.com/virtuosoft-dev/hcpp-vitepress). We can further illustrate using the HCPP_Hooks class to extend or alter HestiaCP with the example below:
155 |
156 | 1) First; create the `plugin.php` file with a proper header and `require_once` the file containing your plugin's class.
157 | ```
158 | register_plugin( MyPlugin::class );
180 | ```
181 |
182 | By using `extends HCPP_Hooks` you can immediately write public functions that respond to HestiaCP's action hooks. Simply name your functions with the appropiate prefix, i.e `hcpp_` for pluginable generated action hooks (see Noteworthy Action Hooks below) or `v_` for [HestiaCP's native CLI API](https://hestiacp.com/docs/reference/cli.html) commands. The example above will replace the string 'Debian' with 'Commodore64' (or 'Ubuntu' with 'Apple ][e') in the CLI command v-list-sys-info output by hooking the `v_list_sys_info_output` action (note the `_output` suffix allows us to filter the output). For example, when the user types this command on the terminal or visits HestiaCP's Server Settings page (that uses the command) they will see 'Commodore64' listed as the operating system:
183 |
184 | 
185 |
186 | By creating your class and registering it via `$hcpp->register_plugin` your plugin instance is created and can be referenced by other plugins by name within the HCPP object. For example, the `$hcpp->myplugin` property will now hold a reference to your plugin and can be accessed by other plugin authors. This is how the VitePress plugin can utilize the NodeApp plugin (via `$hcpp->nodeapp`) to implement VitePress features.
187 |
188 |
189 | ### Registering Install and Uninstall Scripts
190 | Often times a plugin may wish to add files and folders to the HestiaCP runtime; specifically the data/templates folder. In these cases, it's in the plugin's best interest to copy over its own template files upon installation. Likewise, it's important to remove such files upon un-installation or plugin deletion. HestiaCP Pluginable API provides two such methods to aid authors in running plugin installation and un-installation scripts:
191 |
192 | ```
193 | // From within plugin.php
194 |
195 | global $hcpp;
196 |
197 | $hcpp->register_install_script( dirname(__FILE__) . '/install.sh' );
198 | $hcpp->register_uninstall_script( dirname(__FILE__) . '/uninstall.sh' );
199 | ```
200 |
201 | You should define your optional install and uninstall scripts at the start of your plugin.php file to ensure they are properly registered. HestiaCP Pluginable will invoke the install.sh script only once; the next time a user login event occurs in Hestia and the plugin folder exists in `/usr/local/hestia/plugins`. The install script will run within the context of the current working directory of the plugin's folder to make it easy to define copy commands from the plugin's current folder.
202 |
203 | The uninstall.sh script is only run when the plugin has been deleted from the system (from `/usr/local/hestia/plugins` directory or if the user has selected 'Uninstall' from HestiaCP Server's [gear icon] Configure -> Plugins section to uninstall a plugin). Because the script itself is removed; Hestia Pluginable will copy the uninstall.sh script from the plugin folder when it is registered via the `register_uninstall_script` method. The uninstall.sh script is copied to the `/usr/local/hestia/data/hcpp/uninstallers/` folder and renamed to the same name as the plugin's original parent folder name. HestiaCP Pluginable executes the script in the context of the aforementioned uninstallers folder when the 'Uninstall' option is selected from HestiaCP Server's Configure -> Plugins menu. Lastly, the script itself is destroyed after it has been executed.
204 |
205 | Its not recommended to alter the existing files that HestiaCP comes with because they can be overwritten when HestiaCP self-updates. In those cases, (again, NOT recommended) you can utilitize HestiaCP Pluginable's API's `patch_file` function and `hcpp_post_install` action hook to re-apply any changes to core files. Care should be taken as this can become complicated and difficult to undo with plugin uninstallation (and if other plugins have applied changes prior). Because Pluginable itself has already patched a number of HestiaCP core files; chances are an action hook already exists for you to customize HestiaCP without the need to alter core files.
206 |
207 |
208 | ### Invoking Plugins via Hestia API
209 | Plugins also have the ability to execute code on behalf of invoking Hestia's API. An additional bin file called `v-invoke-plugin` can take an arbitrary number of arguments and will in turn execute the `hcpp_invoke_plugin` action. A plugin author can subscribe to this message and execute custom code. Results can be returned, altering any values passed to other subscribers; or an author can echo results back to the caller as clear text or optionally, as JSON (or as JSON if an argument contains the string `json` as by convention like other Hestia API bin commands).
210 |
211 | ### Calling Other API Methods
212 | You can run any of HestiaCP's API commands using the HCPP object's `run` method. For example, the following code will return an object (JSON already decoded) of all the users:
213 |
214 | ```
215 | global $hcpp;
216 | $all_users = $hcpp->run('v-list-users json');
217 | ```
218 |
219 | You also have access to the `runuser` method that can be used to run any arbituary command as a given Linux user; the following would list the contents of the user's home folder:
220 |
221 | ```
222 | global $hcpp;
223 | $results = $hcpp->runuser( 'username', 'ls -laF' );
224 | ```
225 |
226 |
227 | ### Noteworthy Action Hooks
228 | You can invoke your plugins early by hooking the `hcpp_prepend` and/or `hcpp_ob_started` actions as these are fired with every UI screen of the HestiaCP web interface. You can scan the source code of pluginable.php and look for source that invokes the `do_action` method. Additional actions, their parameters, and their descriptions are listed below:
229 |
230 | * `hcpp_prepend` - Occurs at start, when a HestiaCP UI's web page is requested.
231 | * `hcpp_append` - Occurs at end, when a HestiaCP UI's web page is about to be sent.
232 | * `hcpp_ob_started` - Occurs at after initial output buffer is started, when a HestiaCP UI's web page is requested.
233 | * `hcpp_plugin_installed` - $plugin_name, Occurs when a plugin is installed.
234 | * `hcpp_plugin_uninstalled` - $plugin_name, Occurs when a plugin is uninstalled.
235 | * `hcpp_runuser` - [$user, $cmd], Occurs when $hcpp->runuser method is invoked.
236 | * `hcpp_runuser_exec` - $cmd, Occurs when $hcpp->runuser method is invoked and the command is about to be executed.
237 | * `hcpp_runuser_result` - $result, Occurs after $hcpp->runuser executes a command and the results are returned.
238 | * `hcpp_post_install` - Occurs when the HestiaCP system has been updated and a new version has finished installing.
239 | * `hcpp_rebooted` - Occurs after the operating system has been rebooted.
240 | * `hcpp_plugin_enabled` - $plugin, Occurs when the given plugin has been enabled.
241 | * `hcpp_plugin_disabled` - $plugin, Occurs when the given plugin has been disabled.
242 |
243 | All HestiaCP web UI pages can be altered using the `_xpath` and `_html` based action hooks. For instance, when the user requests the URL from a HestiaCP instance at https://cp.example.com/list/web. Notice that the slashes after the domain has been changed to underscores and the `_xpath` and `_html` extension has been added to the action name along with the `hcpp_` prefix. Therefore plugin developers can alter the output of the HestiaCP's listing of websites on the web tab by implementing hooks for one or more of the following actions:
244 |
245 | * `hcpp_list_web_xpath` - $xpath, Invoked when a HestiaCP web page is about to be sent; the $xpath contains a PHP DOMXPath object that can be used to modify the output.
246 | * `hcpp_list_web_html` - $html, Invoked when a HestiaCP web page is about to be sent; the $html contains the raw HTML source code that can be modified before it is sent.
247 | * `hcpp_all_xpath` - $xpath, Occurs for every HestiaCP web page that is requested; the $xpath contains a PHP DOMXPath object that can be used to modify the output.
248 | * `hcpp_all_html` - $html, Occurs for every HestiaCP web page that is requested; the $html contains the raw HTML source code that can be modified before it is sent.
249 |
250 |
251 | All [HestiaCP CLI commands](https://hestiacp.com/docs/reference/cli.html) can be hooked by their given name. In most cases you can alter the parameters passed to the command before the command is actually executed. This powerful method allows plugins do alter or enhance the behavior of HestiaCP.
252 |
253 | For example: If the CLI command to list details of a user account by name were invoked via the example CLI: `v-list-user admin`; the following action hooks will be called:
254 |
255 | * `v_list_user` - $args would contain the paramters passed to the command as an array; i.e. $args[0] would contain `admin` given the example above. It is important to return the $args array (with optional modifications) to be executed by HestiaCP's original CLI command.
256 | * `v_list_user_output` - $output would contain the output of the HestiaCP's v-list-user CLI command. It is important to return the $output variable for callers to receive the results from invoking the original HestiaCP CLI command.
257 |
258 | The example above illustrates how a HestiaCP Pluginable plugin can use action hooks to receive and alter arguments destined for HestiaCP's native CLI API as well as receive and alter the resultes of those commands before these are returned to the caller.
259 |
260 | ### Adding a Custom Page to Hestia's UI
261 | Pluginable features an easy way to add a custom page to HestiaCP web UI, for example:
262 |
263 | ```
264 | global $hcpp;
265 | $hcpp->add_custom_page( 'nodeapp', __DIR__ . '/pages/nodeapp.php' );
266 | ```
267 |
268 | This would add a custom page to display the contents of the nodeapp.php when the user visits the URL https://cp.example.com/?p=nodeapp. The standard HestiaCP header, menu tabs, and footer, stylesheets, etc. will automatically be prepended and appended to the output. The plugin developer only needs to worry about including the optional toolbar and container div tags. See the NodeApp's implementation of logs at: https://github.com/virtuosoft-dev/hcpp-nodeapp/blob/main/pages/nodeapplog.php
269 |
270 |
271 | ### Hosted Site Prepends and Appends
272 | The HestiaCP Pluginable project includes special functionality for processing [PHP auto prepend and auto append directives](https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file) ***on the hosted sites***. This functionality allows a plugin to execute isolated code that is not apart of Hestia Control Panel actions, nor has access to the global $hcpp object; but rather as apart of all hosted sites running PHP. This feature is commonly used by anti-malware scanning applications (such as [WordFence](https://www.wordfence.com/help/firewall/optimizing-the-firewall/), [ISPProtect](https://ispprotect.com/ispprotect-bandaemon/), etc.), performance metric/tuning apps, or freemium hosting providers that wish to inject ads and other functionality into existing websites.
273 |
274 | A plugin author can execute custom PHP for hosted sites by simply including a file named 'prepend.php' for execution before any hosted site scripts; and/or include a file named 'append.php' to execute code after any hosted site scripts.
275 |
276 | Execution priority within plugins can occur earlier or later (with competing plugins) by simply including an underscore followed by a priority number. Like the priority number in [WordPress' action API](https://developer.wordpress.org/reference/functions/add_action/), a file with a name and lower number will execute before files named with a larger number. For example, `prepend_1.php` (priority #1) executes before `prepend_99.php` (priority #99). The default is 10, therefore the file named `prepend.php` is essentially the same as `prepend_10.php`.
277 |
278 |
279 | ### Allocating Ports for Additional Services
280 | HestiaCP Pluginable's API includes methods for allocating unique server ports. Using the methods below, your plugin can reserve ports on the server for domain or user specific based services (i.e. hosting a NodeJS Express based app, or setting up a Xdebug user session, etc) or a unique system wide service (i.e. an XMPP server, MQTT broker, or a Gitea server for all clients, etc).
281 |
282 |
283 | ```
284 | $port = $hcpp->allocate_port( $name, $user, $domain );
285 |
286 | $port = $hcpp->get_port( $name, $user, $domain );
287 |
288 | $hcpp->delete_port( $name, $user, $domain );
289 | ```
290 |
291 | All the methods above expect three parameters:
292 |
293 | | Parameter | Description |
294 | |---|---|
295 | | name | The service name (will be used as a variable name)|
296 | | user | The username associated with the port; or system wide port if omitted|
297 | | domain | The domain associated with the port; or user defined port if ommitted|
298 |
299 | Use the `allocate_port` method to reserve a port for a service. This could be invoked when an action hook occurs for adding a domain. For instance, if you wish to allocate a port for a NodeJS Express app for a given domain name (i.e. example.com); invoke the method like this:
300 |
301 | ```
302 | global $hcpp;
303 | $hcpp->add_action( 'pre_add_web_domain_backend', function( $args ) {
304 | $user = $args[0]; // johnsmith
305 | $domain = $args[1]; // example.com
306 | $hcpp->allocate_port( 'myapp', $user, $domain );
307 | });
308 |
309 | ```
310 |
311 | The code above will generate a configuration file at `/usr/local/hestia/data/hcpp/ports/johnsmitg/example.com.ports`. The file will contain the following port defintion in an Nginx conf file format that defines a variable value:
312 |
313 | ```
314 | set $myapp_port 50000;
315 | ```
316 |
317 | An Nginx Proxy template can then use the `include` directive to directly include the file and utilize the variable `$myapp_port` to setup a reverse proxy to serve the NodeJS Express app. By using the Pluginable API, you are guaranteed a unique port number across all domains, users, and the Hestia Control Panel system. Likewise, an Nginx Proxy template could reference a user allocated port from any domain, by including the file (i.e. where username is johnsmith) at `/usr/local/hestia/data/hcpp/ports/johnsmith/user.ports`. System wide defined ports can be referenced from `/usr/local/hestia/data/hcpp/ports/system.ports`.
318 |
319 | While the `.ports` files are in Nginx conf format for convenience, any application or service can easily parse the variable and port number to leverage a unique port allocation for their service (i.e. an Xdebug port could be configured via ini_set). The `/usr/local/hestia/data/hcpp/ports` path is apart of the open_basedir path which allows hosted PHP processes read-only access to the files. For user and domain .ports files; the files can only be read by the given HestiaCP user.
320 |
321 |
322 |
323 | ### Automatic Updates
324 | Plugins can leverage obtaining automatic updates from publicly hosted git repos (i.e. GitHub, GitLab, etc.). Plugins that are disabled from the configuration panel will not update. To implement this feature is simple; just provide a valid, publicly accesible `Plugin URI` field in the header of the `plugin.php` file. The most recent tag release that matches the nomenclature of `v#.#.#` (i.e. `v1.0.0`) will be queried and obtained on a daily basis. Matches that fail the expression (i.e. `v1.0.0-beta1` or `v2.0.1b3`) will be ignored.
325 |
326 | The plugin folder must have been initially installed using git and therefore should have a .git folder present for automatic update checking to work. When the HCPP object's `public $logging = true` option is set (see next section ***Debug Logging***); update checking will occur at a higher frequency of every 5 minutes (vs once daily) to assist with testing.
327 |
328 | An optional update script can be included with the plugin. Unlike the install and uninstall scripts; the update script does not need to be registered. Updates do not trigger the install script; but you may wish to invoke it on update's behalf. The update script will be passed two parameters; the current installed version (i.e. `v1.0.0`) and the newly installed version (i.e. `v2.0.0`). The optional update script is executed if present and only after after the repo has been updated. The update script feature allows plugin authors to make critical changes and apply patches if necessary to accomodate specific upgrade version migrations.
329 |
330 |
331 |
332 | ### Debug Logging
333 | You can view all the possible hook names that the hestiacp-pluginable API can respond to by turning logging on. Logging logs operations via $hcpp->log function to /tmp/hcpp.log. To turn on logging, simply include a file named logging in the hooks folder.
334 |
335 | To turn on logging:
336 | ```
337 | sudo touch /etc/hestiacp/hooks/logging
338 | ```
339 |
340 | To turn off logging:
341 | ```
342 | sudo rm /etc/hestiacp/hooks/logging
343 | ```
344 |
345 | Optionally, remove the log file:
346 | ```
347 | sudo rm /tmp/hcpp.log
348 | ```
349 |
350 | Note: the hcpp.log file is automatically created for writing by both trusted root and admin users because Hestia sometimes executes privileged processes. Also, HestiaCP UI process does not have PHP access to /var/log/hestia due to open_basedir restrictions. /tmp/hcpp.log is a 'safe' file path. If you need to self-truncate the log simply use the command:
351 |
352 | ```
353 | truncate -s 0 /tmp/hcpp.log
354 | ```
355 | or
356 | ```
357 | : > /tmp/hcpp.log
358 | ```
359 |
360 | ## Support the creator
361 | You can help this author's open source development endeavors by donating any amount to Stephen J. Carnam @ Virtuosoft. Your donation, no matter how large or small helps pay for essential time and resources to create MIT and GPL licensed projects that you and the world can benefit from. Click the link below to donate today :)
362 |
363 |
364 |
365 | [ Donate to this Project ][KBD]
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 | [KBD]: https://virtuosoft.com/donate
374 |
375 | https://virtuosoft.com/donate
376 |
--------------------------------------------------------------------------------
/append.php:
--------------------------------------------------------------------------------
1 | getExtension() == "php") {
13 | $fileKey = pathinfo( $file->getFilename(), PATHINFO_FILENAME );
14 | if ( strpos( $fileKey, 'append' ) === 0 && strpos( $filePath, '.disabled/append' ) === false ) {
15 | $appendsArray[$fileKey] = $file->getPathname();
16 | }
17 | }
18 | }
19 |
20 | // Sort our append arrays by key, default 'append' to append_10.
21 | foreach( $appendsArray as $key => $value ) {
22 | if ( $key == "append" ) {
23 | $appendsArray["append_10"] = $value;
24 | unset( $appendsArray[$key] );
25 | }
26 | }
27 |
28 | // Sort numerically by the priority number
29 | usort( $appendsArray, function( $a, $b ) {
30 | $a = explode( '_', $a )[1];
31 | $b = explode( '_', $b )[1];
32 | return $a - $b;
33 | });
34 |
35 |
36 | // Load and execute the append files in the order they were sorted
37 | foreach( $appendsArray as $key => $value ) {
38 | require_once( $value );
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/virtuosoft-dev/hestiacp-pluginable/e860bf898c826fc106c8b6982fde80693f7706fa/example.png
--------------------------------------------------------------------------------
/hcpp_hooks.php:
--------------------------------------------------------------------------------
1 | class_name = $self->name;
21 | $this->script_file = $self->getFileName();
22 | $public_methods = $self->getMethods( \ReflectionMethod::IS_PUBLIC );
23 |
24 | if ( empty ( $public_methods ) ) {
25 | return;
26 | }
27 | foreach ( $public_methods as $method ) {
28 | if ( $method->name != '__construct' ){
29 |
30 | // Check if name begins with a valid plugin prefix
31 | global $hcpp;
32 | foreach ( $hcpp->prefixes as $p ){
33 | if ( strpos( $method->name, $p ) === 0 ){
34 |
35 | // Assume for action/filter hook definition
36 | $name = $method->name;
37 | $priority = $hcpp->getRightMost( $name, '_' );
38 | if ( is_numeric( $priority ) ){
39 | $priority = (int) $priority;
40 | $name = $hcpp->delRightMost( $name, '_' );
41 | }else{
42 | $priority = 10;
43 | }
44 | $hcpp->add_action( $name, array( $this, $method->name ), $priority );
45 | }
46 | }
47 | }
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/local.conf:
--------------------------------------------------------------------------------
1 | #
2 | # Our HestiaCP-Pluginable feature to intercept calls to Hestia's bin/
3 | # commands and invoke plugin actions/filters.
4 | #
5 |
6 | # Check if bin_actions is set and if it is, then return
7 | if [ -n "$bin_actions" ]; then
8 | return
9 | fi
10 |
11 | # Set bin_actions to prevent re-entry
12 | export bin_actions=1
13 |
14 | # Get the script name
15 | script_name=$(basename "$0")
16 |
17 | # Encode each argument to handle spaces and special characters
18 | encoded_args=()
19 | for arg in "$@"; do
20 | encoded_args+=("$(printf '%q' "$arg")")
21 | done
22 |
23 | # Invoke php script to run the original v-* command, allowing for plugin hooks
24 | # to modify arguments and output.
25 | php -f /etc/hestiacp/hooks/pluginable.php "$script_name" "${encoded_args[@]}"
26 | exit
--------------------------------------------------------------------------------
/pluginable.php:
--------------------------------------------------------------------------------
1 | $method)) {
35 | $func = $this->$method;
36 | return call_user_func_array($func, $args);
37 | }
38 | }
39 |
40 | /**
41 | * Our object contructor
42 | */
43 | public function __construct() {
44 | $this->logging = file_exists( '/etc/hestiacp/hooks/logging' );
45 | $this->add_action( 'v_check_user_password', [ $this, 'run_install_scripts' ] );
46 | $this->add_action( 'v_check_user_password', [ $this, 'run_uninstall_scripts' ] );
47 | }
48 |
49 | /**
50 | * Add a plugin action/filter
51 | *
52 | * @param string $tag The name of the action/filter to hook the $function_to_add to.
53 | * @param callable $function_to_add The name of the function to be called.
54 | * @param int $priority Optional, default is 10. Determines the execution priority, lower occurring first.
55 | */
56 | public function add_action( $tag, $function_to_add, $priority = 10) {
57 | $priority = str_pad($priority, 3, '0', STR_PAD_LEFT);
58 | $idx = $priority . '_' . $tag . '_' . $this->hcpp_filter_count;
59 | $this->hcpp_filter_count++;
60 | $this->hcpp_filters[$tag][$idx] = $function_to_add;
61 | ksort($this->hcpp_filters[$tag]);
62 | return true;
63 | }
64 |
65 | /**
66 | * Add a custom page to the HestiaCP UI that maintains the header, menu, and footer.
67 | *
68 | * @param string $p The 'p' GET parameter to match to display the custom page.
69 | * @param string $file The file to include when the 'p' GET parameter matches.
70 | */
71 | public function add_custom_page( $p, $file ) {
72 | $this->custom_pages[$p] = $file;
73 | }
74 |
75 | /**
76 | * Allocate a unique port number for a service. This function will check for an existing port allocation.
77 | * If one is found, it will be returned. If not, a new port will be allocated and returned. If neither
78 | * user nor domain is specified, the port will be allocated for the system; otherwise, if only user is
79 | * specified, the port will be allocated for the user; if domain is specified, the port will be allocated
80 | * specifically for the domain (user required for domain option).
81 | *
82 | * @param string $name The name of the service to allocate a port for.
83 | * @param string $user The optional username to allocate the port for.
84 | * @param string $domain The optional domain to allocate the port for.
85 | * @return int The port number allocated or zero if an error occurred.
86 | */
87 | public function allocate_port( $name, $user = '', $domain = '' ) {
88 |
89 | // Check for existing port
90 | $port = $this->get_port( $name, $user, $domain );
91 |
92 | // Return existing port
93 | if ( $port != 0 ) {
94 | return $port;
95 | }
96 |
97 | // Determine which ports file to update
98 | $file = '';
99 | if ( $user == '' && $domain == '' ) { // System port
100 | $file = "$this->folder_ports/system.ports";
101 | }
102 | if ( $user != '' && $domain == '' ) { // User port
103 | $file = "$this->folder_ports/$user/user.ports";
104 | }
105 | if ( $user != '' && $domain != '' ) { // Domain port
106 | $file = "$this->folder_ports/$user/$domain.ports";
107 | }
108 | if ( $file == '' ) {
109 | return 0;
110 | }
111 |
112 | // Create the ports folder if it doesn't exist
113 | if ( !is_dir( dirname( $file ) ) ) {
114 | mkdir( dirname( $file ), 0755, true );
115 | }
116 |
117 | // Update the ports file with the next available port
118 | $port = $this->find_next_port();
119 | file_put_contents( $file, "set \$$name $port;\n", FILE_APPEND );
120 | if ( strpos( $file, 'system.ports' ) == false ) {
121 | chmod( $file, 0640 );
122 | chown( $file, $user );
123 | chgrp( $file, $user );
124 | }
125 | return $port;
126 | }
127 |
128 | /**
129 | * Define our append method to filter the output of the control panel.
130 | */
131 | public function append() {
132 | $this->do_action( 'hcpp_append' );
133 |
134 | // Get the DOMXPath object
135 | $html = ob_get_clean();
136 | if ( $html == "" ) $html = "";
137 | try {
138 | $dom = new DOMDocument();
139 | libxml_use_internal_errors( true );
140 | $dom->loadHTML( $html );
141 | libxml_clear_errors();
142 | $xpath = new DOMXPath($dom);
143 | }catch( Exception $e ) {
144 | $this->log( 'Error in $hcpp->append: ' . $e->getMessage() );
145 | echo $html;
146 | return;
147 | }
148 |
149 | // Get the path
150 | if ( isset( $_GET['p'] ) ) {
151 | $path = $_GET['p'];
152 | }else{
153 | $request_url = $_SERVER['REQUEST_URI'];
154 | $parsed_url = parse_url( $request_url );
155 | $path = trim( $parsed_url['path'], '/' );
156 | }
157 | $path = str_replace( ['/index.php', '/', '-'], ['', '_', '_'], $path );
158 |
159 | // Run the path specific actions for xpath
160 | if ( $path != 'index.php' ) {
161 | $xpath = $this->do_action( 'hcpp_' . $path . '_xpath', $xpath );
162 | }
163 |
164 | // Run all pages actions after specifics for xpath
165 | $xpath = $this->do_action( 'hcpp_all_xpath', $xpath );
166 | $dom = $xpath->document;
167 | $html = $dom->saveHTML();
168 |
169 | // Run the path specific actions for html
170 | if ( $path != 'index.php' ) {
171 | $html = $this->do_action( 'hcpp_' . $path . '_html', $html );
172 | }
173 |
174 | // Run all pages actions after specifics for html
175 | $html = $this->do_action( 'hcpp_all_html', $html );
176 | echo $html;
177 | }
178 |
179 | /**
180 | * Copy a folder recursively, quickly, and retain/restore executable permissions.
181 | */
182 | public function copy_folder( $src, $dst, $user ) {
183 | // Append / to source and destination if necessary
184 | global $hcpp;
185 | if (substr($src, -1) != '/') {
186 | $src .= '/';
187 | }
188 | $dst = rtrim( $dst, '/' );
189 | $hcpp->log("copy_folder $src to $dst for $user");
190 | if ( ! is_dir( $dst ) ) {
191 | mkdir( $dst, 0750, true );
192 | chown( $dst, $user );
193 | chgrp( $dst, $user );
194 | }
195 | $cmd = 'cp -RTp ' . $src . ' ' . $dst . ' && chown -R ' . $user . ':' . $user . ' ' . $dst;
196 | shell_exec( $cmd );
197 | $cmd = 'find "' . $dst . '" -type f -perm /111 -exec chmod +x {} \;';
198 | shell_exec( $cmd );
199 | $cmd = 'find "' . $dst . '" -type d -perm /111 -exec chmod +x {} \;';
200 | shell_exec( $cmd );
201 | }
202 |
203 | /**
204 | * Delete a service port allocation.
205 | *
206 | * @param string $name The name of the service to delete the port allocation for.
207 | * @param string $user The optional username to delete the port for; if blank, the system port will be deleted.
208 | * @param string $domain The optional domain to delete the port for (requires $user); if blank, the user port will be deleted.
209 | */
210 | public function delete_port( $name, $user = '', $domain = '' ) {
211 |
212 | // Exit if ports folder doesn't exist
213 | if ( !is_dir( $this->folder_ports ) ) {
214 | return;
215 | }
216 |
217 | // Determine which ports file to update
218 | $file = '';
219 | if ( $user == '' && $domain == '' ) { // System port
220 | $file = "$this->folder_ports/system.ports";
221 | }
222 | if ( $user != '' && $domain == '' ) { // User port
223 | $file = "$this->folder_ports/$user/user.ports";
224 | }
225 | if ( $user != '' && $domain != '' ) { // Domain port
226 | $file = "$this->folder_ports/$user/$domain.ports";
227 | }
228 | if ( $file == '' ) {
229 | return 0;
230 | }
231 |
232 | // Check for existing ports file
233 | if ( !file_exists( $file ) ) {
234 | return;
235 | }
236 |
237 | // Update the file, removing the port allocation
238 | $new_content = "";
239 | $content = file_get_contents( $file );
240 | $content = explode( "\n", $content );
241 | foreach( $content as $line ) {
242 | if ( strpos( $line, "set \$$name " ) === false ) {
243 | $new_content .= "$line\n";
244 | }
245 | }
246 | $new_content = trim( $new_content );
247 | file_put_contents( $file, $new_content );
248 | }
249 |
250 | /**
251 | * Invoke specific plugin action/filter hook.
252 | *
253 | * @param string $tag The name of the action/filter hook.
254 | * @param mixed $arg Optional. Arguments to pass to the functions hooked to the action/filter.
255 | * @return mixed The filtered value after all hooked functions are applied to it.
256 | */
257 | public function do_action( $tag, $arg = '' ) {
258 | if ($this->logging) {
259 | $this->log( 'do action as ' . trim( shell_exec( 'whoami' ) ) . ', ' . $tag );
260 | $this->log( $arg );
261 | }
262 | if ( ! isset( $this->hcpp_filters[$tag] ) ) return $arg;
263 |
264 | $args = array();
265 | if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
266 | $args[] =& $arg[0];
267 | else
268 | $args[] = $arg;
269 | for ( $a = 2, $num = func_num_args(); $a < $num; $a++ )
270 | $args[] = func_get_arg($a);
271 |
272 | foreach ( $this->hcpp_filters[$tag] as $func ) {
273 | try {
274 | $arg = call_user_func_array( $func, $args );
275 | } catch (Exception $e) {
276 |
277 | // Echo out the error message if an exception occurs
278 | echo 'Error: do_action failed ' . $e->getMessage();
279 | $this->log( 'Error: do_action failed ' . $e->getMessage() );
280 | }
281 |
282 | if ($arg != null) {
283 | $args = array();
284 | if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
285 | $args[] =& $arg[0];
286 | else
287 | $args[] = $arg;
288 | for ( $a = 2, $num = func_num_args(); $a < $num; $a++ )
289 | $args[] = func_get_arg($a);
290 | }
291 | }
292 | if (is_array($args) && 1 == count($args)) {
293 | return $args[0];
294 | }else{
295 | return $args;
296 | }
297 | }
298 |
299 | /**
300 | * Find the github repo's tag marked latest
301 | *
302 | * @param string $url The git repo URL.
303 | * @return string The latest release tag.
304 | */
305 | public function find_latest_repo_tag($url) {
306 | $this->log('Finding latest release tag for ' . $url);
307 |
308 | // Remove the trailing ".git" if it exists
309 | $url = preg_replace('/\.git$/', '', $url);
310 |
311 | // Extract the owner and repository name from the GitHub URL
312 | if (preg_match('/github\.com\/([^\/]+)\/([^\/]+)/', $url, $matches)) {
313 | $owner = $matches[1];
314 | $repo = $matches[2];
315 |
316 | // GitHub API URL for the latest release
317 | $apiUrl = "https://api.github.com/repos/$owner/$repo/releases/latest";
318 |
319 | // Set up the HTTP headers for the API request
320 | $headers = [
321 | 'User-Agent: HestiaCP-Pluginable',
322 | 'Accept: application/vnd.github.v3+json'
323 | ];
324 |
325 | // Initialize a cURL session
326 | $ch = curl_init();
327 | curl_setopt($ch, CURLOPT_URL, $apiUrl);
328 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
329 | curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
330 |
331 | // Execute the cURL request
332 | $response = curl_exec($ch);
333 | $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
334 | curl_close($ch);
335 |
336 | // Check if the request was successful
337 | if ($httpCode === 200) {
338 | $data = json_decode($response, true);
339 | if (isset($data['tag_name'])) {
340 | $this->log('Latest release tag found: ' . $data['tag_name']);
341 | return $data['tag_name'];
342 | }
343 | } else {
344 | $this->log('Failed to fetch latest release tag. HTTP Code: ' . $httpCode);
345 | }
346 | } else {
347 | $this->log('Invalid GitHub URL: ' . $url);
348 | }
349 | return null;
350 | }
351 |
352 | /**
353 | * Find the next unique service port number.
354 | *
355 | * @return int The next available port number.
356 | */
357 | public function find_next_port() {
358 |
359 | // Get list of existing Nginx port files
360 | $files = array();
361 | $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $this->folder_ports ) );
362 | foreach( $iterator as $file ) {
363 | if ( !$file->isDir() && $file->getExtension() == 'ports' ) {
364 | $files[] = $file->getPathname();
365 | }
366 | }
367 |
368 | // Read all port numbers from files
369 | $used_ports = [];
370 | foreach( $files as $file ) {
371 | $content = file_get_contents( $file );
372 | $content = explode( "\n", $content );
373 |
374 | // Gather all port numbers
375 | foreach( $content as $line ) {
376 | $parse = explode( ' ', $line );
377 | if ( isset( $parse[2] ) ) {
378 | $used_ports[] = intval( $parse[2] );
379 | }
380 | }
381 | }
382 |
383 | // Find first available port from starting port
384 | $port = $this->start_port;
385 | while( in_array( $port, $used_ports ) ) {
386 | $port++;
387 | }
388 |
389 | // Ensure port is available for service
390 | while( !$this->is_service_port_free( $port ) ) {
391 | $port++;
392 | }
393 | return $port;
394 | }
395 |
396 | /**
397 | * Get the port number allocated to a service.
398 | *
399 | * @param string $name The name of the service to get the port for.
400 | * @param string $user The optional username to obtain the port for; if blank, the system port will be returned.
401 | * @param string $domain The optional domain to obtain the port for (requires $user); if blank, the user port will be returned.
402 | * @return int The port number allocated or zero if not found.
403 | */
404 | public function get_port( $name, $user = '', $domain = '' ) {
405 |
406 | // Create ports folder if it doesn't exist
407 | if ( !is_dir( $this->folder_ports ) ) {
408 | mkdir( $this->folder_ports, 0755, true );
409 | return 0;
410 | }
411 |
412 | // Determine which ports file to read
413 | $file = '';
414 | if ( $user == '' && $domain == '' ) { // System port
415 | $file = "$this->folder_ports/system.ports";
416 | }
417 | if ( $user != '' && $domain == '' ) { // User port
418 | $file = "$this->folder_ports/$user/user.ports";
419 | }
420 | if ( $user != '' && $domain != '' ) { // Domain port
421 | $file = "$this->folder_ports/$user/$domain.ports";
422 | }
423 | if ( $file == '' ) {
424 | return 0;
425 | }
426 |
427 | // Check for existing port
428 | $port = 0;
429 | if ( file_exists( $file ) ) {
430 | $content = file_get_contents( $file );
431 | $content = explode( "\n", $content );
432 | foreach( $content as $line ) {
433 | $parse = explode( ' ', $line );
434 | if ( isset( $parse[1] ) && $parse[1] == "\$$name" ) {
435 | $port = intval( $parse[2] );
436 | break;
437 | }
438 | }
439 | }
440 | return $port;
441 | }
442 |
443 | /**
444 | * Get the repo's version tag for the given repo's folder.
445 | *
446 | * @param string $folder The folder to get the repo's version tag for.
447 | * @return string The repo's version tag.
448 | */
449 | public function get_repo_folder_tag( $folder ) {
450 | $tag = '';
451 | if ( is_dir( $folder . '/.git' ) ) {
452 | $cmd = "cd $folder && git describe --tags --abbrev=0 2>&1"; // Redirect stderr to stdout
453 | $tag = trim( shell_exec( $cmd ) );
454 | if ( strpos( $tag, 'fatal' ) !== false ) {
455 | $cmd = "cd $folder && git describe --all 2>&1"; // Redirect stderr to stdout
456 | $tag = trim( shell_exec( $cmd ) );
457 | $tag = explode( '/', $tag );
458 | $tag = end( $tag );
459 | }
460 | if ( strpos( $tag, 'fatal' ) !== false ) {
461 | $tag = '';
462 | }
463 | }
464 | return $tag;
465 | }
466 |
467 | /**
468 | * Insert HTML content into the element with the specified DOMXPath query selector.
469 | *
470 | * @param DOMXPath $xpath The DOMXPath object to use for querying the DOM.
471 | * @param string $query The query selector to use for selecting the target element.
472 | * @param string $html The HTML content to insert into the target element.
473 | * @param bool $prepend Optional. If true, the HTML content will be prepended to the target element.
474 | *
475 | * @return DOMXPath The updated DOMXPath object with the HTML content inserted.
476 | */
477 | public function insert_html( $xpath, $query, $html, $prepend = false ) {
478 |
479 | // Append the pluginable plugins to the plugins section
480 | $div_plugins = $xpath->query( $query );
481 | if ($div_plugins->length > 0) {
482 | $xml = $xpath->document->createDocumentFragment();
483 |
484 | // Use DOMDocument to validate and clean up the HTML string
485 | $tempDom = new DOMDocument();
486 | libxml_use_internal_errors(true);
487 | $tempDom->loadHTML('
' . $html . '
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
488 | libxml_clear_errors();
489 |
490 | // Import the validated HTML into the fragment
491 | foreach ($tempDom->documentElement->childNodes as $child) {
492 | $node = $xpath->document->importNode($child, true);
493 | $xml->appendChild($node);
494 | }
495 |
496 | // Prepend or append the fragment to the target node
497 | if ($prepend) {
498 | $div_plugins->item(0)->insertBefore($xml, $div_plugins->item(0)->firstChild);
499 | } else {
500 | $div_plugins->item(0)->appendChild($xml);
501 | }
502 | } else {
503 | $this->log('No element found using query selector: ' . $query);
504 | }
505 | return $xpath;
506 | }
507 |
508 | /**
509 | * Check if a TCP port is free for running a service.
510 | *
511 | * @param int $port The port number to check.
512 | * @param string $host The host to check the port on (default is '127.0.0.1').
513 | * @return bool True if the port is free, false if it is in use.
514 | */
515 | function is_service_port_free( $port, $host = '127.0.0.1' ) {
516 | $socket = @socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
517 | if ( $socket === false ) {
518 | // Failed to create socket
519 | return false;
520 | }
521 |
522 | $result = @socket_bind( $socket, $host, $port );
523 | if ( $result === false ) {
524 | // Failed to bind socket, port is in use
525 | socket_close( $socket );
526 | return false;
527 | }
528 |
529 | // Successfully bound socket, port is free
530 | socket_close( $socket );
531 | return true;
532 | }
533 |
534 | /**
535 | * Define our install method to install the pluginable system.
536 | */
537 | public function install() {
538 |
539 | // Create plugins folder
540 | @mkdir( '/usr/local/hestia/plugins', 0755, true );
541 |
542 | // Create the HCPP directory structure
543 | @mkdir( '/usr/local/hestia/data/hcpp/installed', 0755, true );
544 | @mkdir( '/usr/local/hestia/data/hcpp/uninstallers', 0755, true );
545 |
546 | // Append to /etc/hestiacp/local.conf
547 | $local_conf = '';
548 | if ( file_exists( '/etc/hestiacp/local.conf' ) ) {
549 | $local_conf = file_get_contents( '/etc/hestiacp/local.conf' );
550 | }
551 | if ( strpos( $local_conf, 'source /etc/hestiacp/hooks/local.conf' ) === false ) {
552 | $local_conf .= "\nsource /etc/hestiacp/hooks/local.conf\n";
553 | file_put_contents( '/etc/hestiacp/local.conf', $local_conf );
554 | }
555 |
556 | // Copy the prepend/append/pluginable system to /usr/local/hestia/data/hcpp
557 | copy( '/etc/hestiacp/hooks/prepend.php', '/usr/local/hestia/data/hcpp/prepend.php' );
558 | copy( '/etc/hestiacp/hooks/append.php', '/usr/local/hestia/data/hcpp/append.php' );
559 |
560 | // Copy v-invoke-plugin to /usr/local/hestia/bin to allow invocation from API
561 | copy( '/etc/hestiacp/hooks/v-invoke-plugin', '/usr/local/hestia/bin/v-invoke-plugin' );
562 | chmod( '/usr/local/hestia/bin/v-invoke-plugin', 0755 );
563 |
564 | // Install jQuery 3.7.1
565 | shell_exec( 'wget -O /usr/local/hestia/web/js/dist/jquery-3.7.1.min.js https://code.jquery.com/jquery-3.7.1.min.js' );
566 |
567 | // Patch /usr/local/hestia/php/lib/php.ini
568 | $this->patch_file(
569 | '/usr/local/hestia/php/lib/php.ini',
570 | "auto_append_file =\n",
571 | 'auto_append_file = /etc/hestiacp/hooks/pluginable.php'
572 | );
573 | $this->patch_file(
574 | '/usr/local/hestia/php/lib/php.ini',
575 | "auto_prepend_file =\n",
576 | 'auto_prepend_file = /etc/hestiacp/hooks/pluginable.php'
577 | );
578 |
579 | // Patch Hestia templates php-fpm templates ..templates/web/php-fpm/*.tpl
580 | $folderPath = "/usr/local/hestia/data/templates/web/php-fpm";
581 | $files = glob( "$folderPath/*.tpl" );
582 | foreach( $files as $file ) {
583 | if ( strpos( $file, 'no-php.tpl' ) !== false ) {
584 | continue;
585 | }
586 | // Patch php-fpm templates open_basedir to include /usr/local/hestia/plugins and /usr/local/hestia/data/hcpp
587 | $this->patch_file(
588 | $file,
589 | "\nphp_admin_value[open_basedir] =",
590 | "\nphp_admin_value[open_basedir] = /home/%user%/.composer:/home/%user%/web/%domain%/public_html:/home/%user%/web/%domain%/private:/home/%user%/web/%domain%/public_shtml:/home/%user%/tmp:/tmp:/var/www/html:/bin:/usr/bin:/usr/local/bin:/usr/share:/opt:/usr/local/hestia/plugins:/usr/local/hestia/data/hcpp\n;php_admin_value[open_basedir] ="
591 | );
592 |
593 | // Patch php-fpm templates to support plugins prepend/append system
594 | $this->patch_file(
595 | $file,
596 | "\nphp_admin_value[open_basedir] =",
597 | "\nphp_admin_value[auto_prepend_file] = /usr/local/hestia/data/hcpp/prepend.php\n\nphp_admin_value[auto_append_file] = /usr/local/hestia/data/hcpp/append.php\nphp_admin_value[open_basedir] ="
598 | );
599 | }
600 |
601 | // Patch /usr/local/hestia/func/domain.sh
602 | $this->patch_file(
603 | '/usr/local/hestia/func/domain.sh',
604 | 'if [[ $backend_template =~ ^.*PHP-([0-9])\_([0-9])$ ]]; then',
605 | 'if [[ $backend_template =~ ^.*PHP-([0-9])\_([0-9])(.*)$ ]]; then'
606 | );
607 | $this->patch_file(
608 | '/usr/local/hestia/func/domain.sh',
609 | '${BASH_REMATCH[1]}.${BASH_REMATCH[2]}',
610 | '${BASH_REMATCH[1]}.${BASH_REMATCH[2]}${BASH_REMATCH[3]}'
611 | );
612 |
613 | // Comment out disable_functions in php.ini
614 | // (undo https://github.com/hestiacp/hestiacp/blob/main/CHANGELOG.md#1810---service-release)
615 | shell_exec( 'sed -i \'s/^disable_functions =/;disable_functions =/g\' /etc/php/*/fpm/php.ini' );
616 | shell_exec( 'sed -i \'s/^disable_functions =/;disable_functions =/g\' /etc/php/*/cli/php.ini' );
617 |
618 | // Install the hcpp_rebooted action hook service
619 | $serviceFile = '/etc/systemd/system/hcpp_rebooted.service';
620 |
621 | // Check if the service file already exists
622 | if (!file_exists($serviceFile)) {
623 | $serviceContent = "[Unit]
624 | Description=Trigger hcpp_rebooted action hook
625 | After=network.target
626 |
627 | [Service]
628 | Type=oneshot
629 | ExecStartPre=/bin/sleep 10
630 | ExecStart=/usr/bin/php /etc/hestiacp/hooks/pluginable.php --rebooted
631 |
632 | [Install]
633 | WantedBy=multi-user.target
634 | ";
635 |
636 | // Remove leading spaces from each line
637 | $serviceContent = preg_replace('/^\s+/m', '', $serviceContent);
638 |
639 | file_put_contents($serviceFile, $serviceContent);
640 | // Enable the service
641 | exec('systemctl enable hcpp_rebooted.service');
642 | echo "Installed hcpp_rebooted.service\n";
643 | } else {
644 | echo "hcpp_rebooted.service already exists. Skipping.\n";
645 | }
646 | echo "Install complete";
647 | }
648 |
649 | /**
650 | * Write a log message to the /tmp/hcpp.log file. Why here? Because
651 | * we can't log UI events to /var/log/hestia/ because open_basedir,
652 | * and we are logging privledged (root) and (admin) process space
653 | * events and they are isolated. /tmp/ is the only safe place to
654 | * write w/out causing runtime issues.
655 | *
656 | * @param mixed $msg The message or object to write to the log.
657 | */
658 | public function log( $msg ) {
659 | if ( $this->logging == false ) return;
660 |
661 | // Only write initial file if we're root and set permissions accordingly
662 | if ( ! file_exists( '/tmp/hcpp.log' ) ) {
663 | if ( posix_getpwuid( posix_geteuid() )['name'] == 'root' ) {
664 | touch( '/tmp/hcpp.log' );
665 | chmod( '/tmp/hcpp.log', 0666 );
666 | }else{
667 | return;
668 | }
669 | }
670 |
671 | // Write timestamp and message as JSON to log file
672 | $logFile = '/tmp/hcpp.log';
673 | $t = (new DateTime('Now'))->format('H:i:s.') . substr( (new DateTime('Now'))->format('u'), 0, 2);
674 | $msg = json_encode( $msg, JSON_PRETTY_PRINT );
675 | $msg = $t . ' ' . $msg;
676 | $msg = substr( $msg, 0, 4096 );
677 | $msg .= "\n";
678 |
679 | // Use PHP's native error logging function
680 | error_log( $msg, 3, $logFile );
681 | }
682 |
683 | /**
684 | * patch_file function.
685 | *
686 | * Tests if the given file exists and does not contain the content of replace;
687 | * if missing it performs a search and replace on the file.
688 | *
689 | * @param string $file The file to patch.
690 | * @param string $search The search string.
691 | * @param string $replace The replace string.
692 | * @param boolean $backup If true, backup the file before patching.
693 | */
694 | public function patch_file( $file, $search, $replace, $backup = true ) {
695 | if ( file_exists( $file ) ) {
696 | $content = file_get_contents( $file );
697 | if ( !strstr( $content, $replace ) && strstr( $content, $search ) ) {
698 |
699 | // Backup file before patch with timestamp of patch yyyy_mm_dd_hh_mm
700 | $backup_file = $file . '.bak_' . date('Y_m_d_H_i');
701 | if ( !file_exists( $backup_file ) && $backup ) {
702 | copy( $file, $backup_file );
703 | }
704 | $content = str_replace( $search, $replace, $content );
705 | file_put_contents( $file, $content );
706 | $this->log( "Patched $file with $replace");
707 | }else{
708 | if ( strstr( $content, $replace ) ) {
709 | $this->log( "Already patched $file with $replace" );
710 | }
711 | }
712 |
713 | // Report patch_file failures, Hestia version may not be compatible
714 | if (!strstr( $content, $replace ) && !strstr( $content, $search ) ) {
715 | $this->log( "!!! Failed to patch $file with $replace" );
716 | }
717 |
718 | }else{
719 |
720 | // Report patch_file failures, Hestia version may not be compatible
721 | $this->log( "!!! Failed to patch $file not found, with $replace" );
722 | }
723 | }
724 |
725 | /**
726 | * Define our prepend method to capture the output of the control panel.
727 | */
728 | public function prepend() {
729 | $this->do_action( 'hcpp_prepend' );
730 | ob_start();
731 | $this->do_action( 'hcpp_ob_started' );
732 | }
733 |
734 | /**
735 | * Generate random alpha numeric for passwords, seeds, etc.
736 | *
737 | * @param int $length The length of characters to return.
738 | * @param string $chars The set of possible characters to choose from.
739 | * @return string The resulting randomly generated string.
740 | */
741 | public function random_chars( $length = 10, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' ) {
742 | $string = '';
743 | $max_index = strlen( $chars ) - 1;
744 | for ( $i = 0; $i < $length; $i++ ) {
745 | $string .= $chars[random_int( 0, $max_index )]; // random_int is more crypto secure
746 | }
747 | return $string;
748 | }
749 |
750 | /**
751 | * Register a script to be exectued once when the plugin is first present
752 | * in /usr/local/hestia/plugins.
753 | */
754 | public function register_install_script( $file ) {
755 |
756 | // Check that the installed flag file doesn't already exist
757 | $plugin_name = basename( dirname( $file ) );
758 | if ( !file_exists( "/usr/local/hestia/data/hcpp/installed/$plugin_name" ) ) {
759 |
760 | // Remember the plugin_name to run its install script
761 | $this->log( "Registering install script for $plugin_name");
762 | $this->installers[] = $file;
763 | }
764 | }
765 |
766 | /**
767 | * Register a plugin with the HestiaCP Pluginable object and create an instance of it.
768 | *
769 | * @param object $plugin The plugin class to register and create.
770 | */
771 | public function register_plugin( $class ) {
772 | $property = strtolower( (new \ReflectionClass( $class ))->getShortName() );
773 | $this->$property = new $class();
774 | $this->plugins[] = $this->$property;
775 | }
776 |
777 | /**
778 | * Register a script to be executed after the plugin folder has been
779 | * from /usr/local/hestia/plugins deleted.
780 | */
781 | public function register_uninstall_script( $file ) {
782 |
783 | // Check if the uninstallers file already exists, if not; copy it over
784 | $plugin_name = basename( dirname( $file ) );
785 | if ( !file_exists( "/usr/local/hestia/data/hcpp/uninstallers/$plugin_name" ) ) {
786 | copy( $file, "/usr/local/hestia/data/hcpp/uninstallers/$plugin_name" );
787 | shell_exec( "chmod 700 /usr/local/hestia/data/hcpp/uninstallers/$plugin_name" );
788 | }
789 | }
790 |
791 | /**
792 | * Define our remove method to remove the pluginable system.
793 | */
794 | public function remove() {
795 |
796 | // Remove data folder,local.conf, v-invoke-plugin, and restore original php.ini
797 | shell_exec( 'rm -rf /usr/local/hestia/data/hcpp' );
798 | shell_exec( 'rm -f /etc/hestiacp/local.conf' );
799 | shell_exec( 'rm -f /usr/local/hestia/bin/v-invoke-plugin' );
800 | $this->restore_backup( '/usr/local/hestia/php/lib/php.ini' );
801 |
802 | // Remove jQuery 3.7.1
803 | shell_exec( 'rm -f /usr/local/hestia/web/js/dist/jquery-3.7.1.min.js' );
804 |
805 | // Restore Hestia templates php-fpm templates ..templates/web/php-fpm/*.tpl
806 | $folderPath = "/usr/local/hestia/data/templates/web/php-fpm";
807 | $files = glob( "$folderPath/*.tpl" );
808 | foreach( $files as $file ) {
809 | if ( strpos( $file, 'no-php.tpl' ) !== false ) {
810 | continue;
811 | }
812 |
813 | // Restore php-fpm templates
814 | $this->restore_backup( $file );
815 | }
816 |
817 | // Restore /usr/local/hestia/func/domain.sh
818 | $this->restore_backup( '/usr/local/hestia/func/domain.sh' );
819 |
820 | // Re-enable disable_functions in php.ini
821 | // (undo https://github.com/hestiacp/hestiacp/blob/main/CHANGELOG.md#1810---service-release)
822 | shell_exec( 'sed -i \'s/^;disable_functions =/disable_functions =/g\' /etc/php/*/fpm/php.ini' );
823 | shell_exec( 'sed -i \'s/^;disable_functions =/disable_functions =/g\' /etc/php/*/cli/php.ini' );
824 |
825 | // Disable and remove the hcpp_rebooted service
826 | $serviceFile = '/etc/systemd/system/hcpp_rebooted.service';
827 | exec('systemctl disable hcpp_rebooted.service');
828 | exec('systemctl stop hcpp_rebooted.service');
829 |
830 | // Remove the service file
831 | if (file_exists($serviceFile)) {
832 | unlink($serviceFile);
833 | echo "Removed hcpp_rebooted.service\n";
834 | } else {
835 | echo "hcpp_rebooted.service does not exist. Skipping removal.\n";
836 | }
837 |
838 | // Reload systemd to apply changes
839 | exec('systemctl daemon-reload');
840 | }
841 |
842 | /**
843 | * Define our method to restore a file from a backup.
844 | *
845 | * @param string $file The file to restore.
846 | */
847 |
848 | public function restore_backup( $file ) {
849 | // Get the directory and base name of the file
850 | $dir = dirname( $file );
851 | $base = basename( $file );
852 |
853 | // Find all backup files for the given file
854 | $backup_files = glob( "$dir/$base.bak_*" );
855 |
856 | // Check if there are any backup files
857 | if ( empty( $backup_files) ) {
858 | $this->log( "No backup files found for $file" );
859 | return false;
860 | }
861 |
862 | // Sort the backup files by date (oldest first)
863 | usort( $backup_files, function( $a, $b ) {
864 | return filemtime( $a ) - filemtime( $b );
865 | });
866 |
867 | // Choose the oldest backup file
868 | $oldest_backup = $backup_files[0];
869 |
870 | // Restore the contents of the original file from the oldest backup file
871 | if ( copy( $oldest_backup, $file ) ) {
872 | // Remove the backup file after restoration
873 | unlink( $oldest_backup );
874 | $this->log( "Restored $file from $oldest_backup and removed the backup file" );
875 | return true;
876 | } else {
877 | $this->log( "Failed to restore $file from $oldest_backup" );
878 | return false;
879 | }
880 | }
881 |
882 | /**
883 | * Run a trusted API command and return JSON if applicable.
884 | *
885 | * @param string $cmd The API command to execute along with it's arguments.
886 | * @return mixed The output of the command; automatically returns JSON decoded if applicable.
887 | */
888 | public function run( $cmd ) {
889 | $cmd = 'sudo /usr/local/hestia/bin/' . $cmd;
890 | $output = shell_exec( $cmd );
891 | if ( strpos( $cmd, ' json') !== false ) {
892 | return json_decode( $output, true );
893 | }else{
894 | return $output;
895 | }
896 | }
897 |
898 | /**
899 | * Run install scripts for plugins that have been installed
900 | */
901 | public function run_install_scripts( $args = null ) {
902 | foreach( $this->installers as $file ) {
903 | $plugin_name = basename( dirname( $file ) );
904 | if ( $this->str_ends_with( $plugin_name, '.disabled' ) ) {
905 | continue;
906 | }
907 |
908 | // Mark installed flag file to prevent it from running again
909 | touch ( "/usr/local/hestia/data/hcpp/installed/$plugin_name" );
910 | $this->log( "Running install script for $plugin_name" );
911 | $cmd = 'cd ' . dirname( $file ) . ' && ';
912 | $cmd .= "nohup $file ";
913 | $cmd .= ' > /dev/null 2>&1 &';
914 | $this->log( $cmd );
915 | $this->log( shell_exec( $cmd ) );
916 | $this->do_action( 'hcpp_plugin_installed', $plugin_name );
917 | }
918 |
919 | // foreach( $this->plugins as $plugin ) {
920 | // if ( file_)
921 | // }
922 | return $args;
923 | }
924 |
925 | /**
926 | * Run uninstall scripts for plugins that have been removed
927 | */
928 | public function run_uninstall_scripts( $args = null ) {
929 | $uninstallers = glob( '/usr/local/hestia/data/hcpp/uninstallers/*' );
930 | foreach( $uninstallers as $file ) {
931 | $plugin_name = pathinfo( $file, PATHINFO_FILENAME );
932 |
933 | if ( ! is_dir( "/usr/local/hestia/plugins/$plugin_name" ) &&
934 | ! is_dir( "/usr/local/hestia/plugins/$plugin_name.disabled" ) ) {
935 |
936 | $this->log( "Running uninstall script for $plugin_name" );
937 | $cmd = "cd /usr/local/hestia/data/hcpp/uninstallers && ";
938 | $cmd .= "$file && ";
939 | $cmd .= "rm -f $file && "; // remove uninstall script when done
940 | $cmd .= "rm -f /usr/local/hestia/data/hcpp/installed/$plugin_name"; // remove installed flag file
941 | $this->log( $cmd );
942 | $this->log( shell_exec( $cmd ) );
943 | $this->do_action( 'hcpp_plugin_uninstalled', $plugin_name );
944 | }
945 | }
946 | return $args;
947 | }
948 |
949 | /**
950 | * Run an arbituary command as the given user.
951 | *
952 | * @param string $user The Linux user account to run the given command as.
953 | * @param string $cmd The command to execute.
954 | * @return string The output of the command.
955 | */
956 | public function runuser( $user, $cmd ) {
957 | $args = [ $user, $cmd ];
958 | $args = $this->do_action( 'hcpp_runuser', $args );
959 | $cmd = $args[1];
960 | $user = $args[0];
961 | $cmd = "runuser -s /bin/bash -l {$user} -c " . escapeshellarg( 'cd /home/' . $user . ' && ' . $cmd );
962 | global $hcpp;
963 | $hcpp->log( $cmd );
964 | $cmd = $this->do_action( 'hcpp_runuser_exec', $cmd );
965 | $result = shell_exec( $cmd );
966 | $result = $this->do_action( 'hcpp_runuser_result', $result );
967 | return $result;
968 | }
969 |
970 | /**
971 | * Perform self update of the pluginable (hooks folder) from the git repo.
972 | */
973 | public function self_update() {
974 | // Only run if autoupdate is enabled
975 | if ( strpos( $this->run('v-list-sys-hestia-autoupdate'), 'Enabled') == false ) {
976 | return;
977 | }
978 | sleep(mt_rand(1, 30)); // stagger actual update check
979 | $this->log( 'Running self update...' );
980 | $url = 'https://github.com/virtuosoft-dev/hestiacp-pluginable';
981 | $installed_version = $this->get_repo_folder_tag( '/etc/hestiacp/hooks' );
982 | $latest_version = $this->find_latest_repo_tag( $url );
983 | $this->log( 'Installed version: ' . $installed_version . ', Latest version: ' . $latest_version );
984 | if ( ltrim($installed_version, 'v') != ltrim($latest_version, 'v') && $latest_version != '' ) {
985 |
986 | // Do a force reset on the repo to avoid merge conflicts, and obtain found latest version
987 | $cmd = 'cd /etc/hestiacp/hooks && git reset --hard';
988 | $cmd .= ' && git clean -f -d';
989 | $cmd .= ' && git fetch origin tag ' . $latest_version . ' && git checkout tags/' . $latest_version;
990 | $this->log( 'Update HestiaCP-Pluginable from ' . $installed_version . ' to ' . $latest_version);
991 | $this->log( $cmd );
992 | $this->log( shell_exec( $cmd ) );
993 |
994 | // Run the post_install.sh script
995 | $cmd = 'cd /etc/hestiacp/hooks && /etc/hestiacp/hooks/post_install.sh';
996 | $this->log( shell_exec( $cmd ) );
997 | }
998 | }
999 |
1000 | /**
1001 | * Append a new line to Hestia's shell formatted table
1002 | *
1003 | * @param string $table The existing table as a string
1004 | * @param string $new_line The new line to append to the table
1005 | */
1006 | public function shell_table_append( $table, $new_line ) {
1007 |
1008 | // Append new data
1009 | $table = trim( $table );
1010 | $lines = explode( "\n", $table );
1011 | $lines[] = $new_line;
1012 |
1013 | // Parse the lines into a 2D array
1014 | $data = array_map( function ( $line ) {
1015 | return preg_split( '/\s+/', $line );
1016 | }, $lines );
1017 |
1018 | // Determine the maximum width of each column
1019 | $maxWidths = array_reduce( $data, function ( $widths, $row ) {
1020 | foreach ( $row as $i => $cell ) {
1021 | $widths[ $i ] = max( $widths[ $i ] ?? 0, strlen( $cell ) );
1022 | }
1023 | return $widths;
1024 | }, [] );
1025 |
1026 | // Format the table with proper column widths
1027 | $formattedTable = array_map( function ( $row ) use ( $maxWidths ) {
1028 | return implode( ' ', array_map( function ( $cell, $i ) use ( $maxWidths ) {
1029 | return str_pad( $cell, $maxWidths[ $i ] );
1030 | }, $row, array_keys( $row ) ) );
1031 | }, $data );
1032 |
1033 | // Convert the formatted table back to a string
1034 | return implode( "\n", $formattedTable );
1035 | }
1036 |
1037 | /**
1038 | * Update plugins from their given git repo.
1039 | */
1040 | public function update_plugins() {
1041 | // Only run if autoupdate is enabled
1042 | if ( strpos( $this->run('v-list-sys-hestia-autoupdate'), 'Enabled') == false ) {
1043 | return;
1044 | }
1045 | sleep(mt_rand(1, 30)); // stagger actual update check
1046 | $this->log( 'Running update plugins...' );
1047 | $pluginsDir = '/usr/local/hestia/plugins';
1048 | $subfolders = glob( $pluginsDir . '/*', GLOB_ONLYDIR );
1049 | foreach ( $subfolders as $subfolder ) {
1050 |
1051 | // Skip disabled plugins
1052 | if ( $this->str_ends_with( $subfolder, '.disabled' ) ) {
1053 | continue;
1054 | }
1055 | $pluginFilePath = $subfolder . '/plugin.php';
1056 | $pluginGitFolder = $subfolder . '/.git';
1057 | if ( file_exists( $pluginFilePath ) && is_dir( $pluginGitFolder ) ) {
1058 | $fileLines = file($pluginFilePath);
1059 |
1060 | // Search for the line containing 'Plugin URI:'
1061 | $url = '';
1062 | foreach ($fileLines as $line) {
1063 | if (strpos($line, 'Plugin URI:') !== false) {
1064 | $url = trim( $this->delLeftMost( $line, 'Plugin URI:' ) );
1065 | break;
1066 | }
1067 | }
1068 |
1069 | // If the plugin is a git repo with a URL, update it
1070 | if ( $url != '' ) {
1071 |
1072 | // Get the installed version number of the plugin
1073 | $installed_version = $this->get_repo_folder_tag( $subfolder );
1074 | $latest_version = $this->find_latest_repo_tag( $url );
1075 | if ( ltrim($installed_version, 'v') != ltrim($latest_version,'v') && $latest_version != '' && strlen( $installed_version ) < 18 ) {
1076 |
1077 | // Do a force reset on the repo to avoid merge conflicts, and obtain found latest version
1078 | $cmd = 'cd ' . $subfolder . ' && git reset --hard';
1079 | $cmd .= ' && git clean -f -d';
1080 | $cmd .= ' && git fetch origin tag ' . $latest_version . ' && git checkout tags/' . $latest_version;
1081 | $this->log( 'Update ' . $subfolder . ' from ' . $installed_version . ' to ' . $latest_version);
1082 | $this->log( $cmd );
1083 | $this->log( shell_exec( $cmd ) );
1084 |
1085 | // Run the update script if it exists
1086 | if ( file_exists( $subfolder . '/update' ) ) {
1087 | $cmd = 'cd ' . $subfolder . ' && ./update ' . escapeshellarg( $installed_version ) . ' ' . escapeshellarg( $latest_version );
1088 | $this->log( $cmd );
1089 | $this->log( shell_exec( $cmd ) );
1090 | }
1091 | }
1092 | }
1093 | }
1094 | }
1095 | }
1096 |
1097 | // *************************************************************************
1098 | // * Conveniently used string parsing and query functions used by this and
1099 | // * other plugins. Linear version, lifted from github/steveorevo/GString
1100 | // *************************************************************************
1101 |
1102 | /**
1103 | * Deletes the right most string from the found search string
1104 | * starting from right to left, including the search string itself.
1105 | *
1106 | * @return string
1107 | */
1108 | public function delRightMost( $sSource, $sSearch ) {
1109 | for ( $i = strlen( $sSource ); $i >= 0; $i = $i - 1 ) {
1110 | $f = strpos( $sSource, $sSearch, $i );
1111 | if ( $f !== false ) {
1112 | return substr( $sSource, 0, $f );
1113 | break;
1114 | }
1115 | }
1116 | return $sSource;
1117 | }
1118 |
1119 | /**
1120 | * Deletes the left most string from the found search string
1121 | * starting from
1122 | *
1123 | * @return string
1124 | */
1125 | public function delLeftMost( $sSource, $sSearch ) {
1126 | for ( $i = 0; $i < strlen( $sSource ); $i = $i + 1 ) {
1127 | $f = strpos( $sSource, $sSearch, $i );
1128 | if ( $f !== false ) {
1129 | return substr( $sSource, $f + strlen( $sSearch ), strlen( $sSource ) );
1130 | break;
1131 | }
1132 | }
1133 | return $sSource;
1134 | }
1135 |
1136 | /**
1137 | * Returns the left most string from the found search string
1138 | * starting from left to right, excluding the search string itself.
1139 | *
1140 | * @return string
1141 | */
1142 | public function getLeftMost( $sSource, $sSearch ) {
1143 | for ( $i = 0; $i < strlen( $sSource ); $i = $i + 1 ) {
1144 | $f = strpos( $sSource, $sSearch, $i );
1145 | if ( $f !== false ) {
1146 | return substr( $sSource, 0, $f );
1147 | break;
1148 | }
1149 | }
1150 | return $sSource;
1151 | }
1152 |
1153 | /**
1154 | * Returns the right most string from the found search string
1155 | * starting from right to left, excluding the search string itself.
1156 | *
1157 | * @return string
1158 | */
1159 | public function getRightMost( $sSource, $sSearch ) {
1160 | for ( $i = strlen( $sSource ); $i >= 0; $i = $i - 1 ) {
1161 | $f = strpos( $sSource, $sSearch, $i );
1162 | if ( $f !== false ) {
1163 | return substr( $sSource, $f + strlen( $sSearch ), strlen( $sSource ) );
1164 | }
1165 | }
1166 | return $sSource;
1167 | }
1168 |
1169 | /**
1170 | * PHP 7 compatible poly fills
1171 | */
1172 | public function str_ends_with(string $haystack, string $needle) {
1173 | $needle_len = strlen($needle);
1174 | return ($needle_len === 0 || 0 === substr_compare($haystack, $needle, - $needle_len));
1175 | }
1176 | function str_starts_with($haystack, $needle) {
1177 | return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
1178 | }
1179 | }
1180 | }
1181 |
1182 | // Create the hcpp object if it doesn't already exist
1183 | if ( !isset( $hcpp ) || $hcpp === null ) {
1184 | $hcpp = new HCPP();
1185 | require_once( __DIR__ . '/hcpp_hooks.php' );
1186 |
1187 | // Load any plugins
1188 | $plugins = glob( '/usr/local/hestia/plugins/*' );
1189 | $require_onces = [];
1190 | foreach($plugins as $p) {
1191 | if ( $hcpp->str_ends_with( $p, '.disabled' ) ) {
1192 | continue;
1193 | }
1194 | $plugin_file = $p . '/plugin.php';
1195 | if ( $plugin_file != "/usr/local/hestia/plugins/index.php/plugin.php" ) {
1196 | if ( file_exists( $plugin_file ) ) {
1197 | $prefix = strtolower( $hcpp->getRightMost( $p, '/' ) );
1198 |
1199 | // Load prefixes first for HCPP_Hooks to be able to find the plugin
1200 | $hcpp->prefixes[] = $prefix . '_';
1201 | $require_onces[] = $plugin_file;
1202 | }
1203 | }
1204 | }
1205 |
1206 | // Load the plugin files
1207 | foreach( $require_onces as $require_once ) {
1208 | require_once( $require_once );
1209 | }
1210 |
1211 | // Run prepend code for web requests or bin_actions/install/remove for cli
1212 | if ( php_sapi_name() !== 'cli' ) {
1213 |
1214 | /**
1215 | * Route to any added custom pages
1216 | */
1217 | $hcpp->add_action( 'hcpp_ob_started', function() use ($hcpp) {
1218 | if ( ! isset( $_GET['p'] ) ) {
1219 | return;
1220 | }
1221 | $page = filter_input(INPUT_GET, 'p', FILTER_SANITIZE_STRING);
1222 | if ( isset( $hcpp->custom_pages[ $page ] ) && file_exists( $hcpp->custom_pages[ $page ] ) ) {
1223 |
1224 | // Main include
1225 | $TAB = strtoupper( $page );
1226 | require_once( $_SERVER["DOCUMENT_ROOT"] . "/inc/main.php" );
1227 | require_once( $_SERVER["DOCUMENT_ROOT"] . "/templates/header.php" );
1228 | $panel = top_panel(empty($_SESSION["look"]) ? $_SESSION["user"] : $_SESSION["look"], $TAB);
1229 | require_once( $_SERVER["DOCUMENT_ROOT"] . "/inc/policies.php" );
1230 |
1231 | // Include custom page
1232 | require_once( $hcpp->custom_pages[ $page ] );
1233 | require_once( $_SERVER["DOCUMENT_ROOT"] . "/templates/footer.php" );
1234 | $hcpp->append();
1235 | }else{
1236 |
1237 | // Abandon buffer and redirect to 404 page
1238 | ob_end_clean();
1239 | header("Location: /error/404.html");
1240 | }
1241 | exit();
1242 |
1243 | });
1244 | $hcpp->prepend();
1245 |
1246 | // Restore jQuery in header
1247 | $hcpp->add_action('hcpp_all_xpath', function($xpath) use ($hcpp) {
1248 | try {
1249 | $scriptElement = $xpath->document->createElement('script');
1250 | $scriptElement->setAttribute('src', '/js/dist/jquery-3.7.1.min.js');
1251 | $xpath->query('/html/head')->item(0)->appendChild($scriptElement);
1252 | }catch( Exception $e ) {
1253 | $hcpp->log( $e->getMessage() );
1254 | }
1255 | return $xpath;
1256 | });
1257 |
1258 | // List pluginable plugins in the HestiaCP UI's edit server page
1259 | $hcpp->add_action('hcpp_edit_server_xpath', function($xpath) use ($hcpp) {
1260 |
1261 | // Insert css style for version tag
1262 | $style = '';
1263 | $xpath = $hcpp->insert_html( $xpath, '/html/head', $style );
1264 |
1265 | // Process any POST request submissions
1266 | foreach( $_REQUEST as $k => $v ) {
1267 | if ( $hcpp->str_starts_with( $k, 'hcpp_' ) ) {
1268 | $plugin = substr( $k, 5 );
1269 | $hcpp->run( 'v-invoke-plugin hcpp_config ' . escapeshellarg( $v ) . ' ' . escapeshellarg( $plugin ) );
1270 | }
1271 | }
1272 |
1273 | // Gather list of plugins and install state
1274 | $plugins = glob( '/usr/local/hestia/plugins/*' );
1275 | foreach( $plugins as $p ) {
1276 |
1277 | // Extract name form plugin.php header or default to folder name
1278 | if ( !file_exists( $p . '/plugin.php' ) ) {
1279 | continue;
1280 | }
1281 | $label = file_get_contents( $p . '/plugin.php' );
1282 | $name = basename( $p, '.disabled' );
1283 | if ( strpos( $label, 'Plugin Name: ') !== false ) {
1284 | $label = $hcpp->delLeftMost( $label, 'Plugin Name: ' );
1285 | $label = trim( $hcpp->getLeftMost( $label, "\n") );
1286 | }else{
1287 | $label = $name;
1288 | }
1289 |
1290 | // Extract version if git repo
1291 | $version = '';
1292 | $version = $hcpp->run( 'v-invoke-plugin get_plugin_version ' . $name );
1293 |
1294 | // Inject the pluginable plugin into the page
1295 | $h = '