diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..62cc078 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +flexisip-account-manager/ +rpmbuild/ diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/Makefile b/Makefile index 2370b65..055b6f3 100644 --- a/Makefile +++ b/Makefile @@ -5,11 +5,10 @@ rpm: mkdir $(OUTPUT_DIR)/flexisip-account-manager mkdir -p $(OUTPUT_DIR)/rpmbuild/SPECS mkdir -p $(OUTPUT_DIR)/rpmbuild/SOURCES - cp src/*.php $(OUTPUT_DIR)/flexisip-account-manager/ + cp -R src/ $(OUTPUT_DIR)/flexisip-account-manager/ + cp -R conf/ $(OUTPUT_DIR)/flexisip-account-manager/ cp README.md $(OUTPUT_DIR)/flexisip-account-manager/ - cp src/*.conf $(OUTPUT_DIR)/flexisip-account-manager/ - mkdir -p $(OUTPUT_DIR)/flexisip-account-manager/httpd - cp httpd/flexisip-account-manager.conf $(OUTPUT_DIR)/flexisip-account-manager/httpd + cp -R httpd/ $(OUTPUT_DIR)/flexisip-account-manager/ cp flexisip-account-manager.spec $(OUTPUT_DIR)/rpmbuild/SPECS/ tar cvf flexisip-account-manager.tar.gz -C $(OUTPUT_DIR) flexisip-account-manager mv flexisip-account-manager.tar.gz $(OUTPUT_DIR)/rpmbuild/SOURCES/flexisip-account-manager.tar.gz diff --git a/README.md b/README.md index 73c6153..a4e3280 100644 --- a/README.md +++ b/README.md @@ -1,97 +1,73 @@ ### 1. Install RPM package with dependencies -------------------------------------------- -# RPM package should install necessary dependencies automatically -# Check that the PHP version is 5.4 or higher +RPM package should install necessary dependencies automatically. -yum install flexisip-account-manager-1.0-1.0.x86_64.rpm +`yum install bc-flexisip-account-manager` + +This package depends on `rh-php71` which will be installed in `/opt/rh/rh-php71/`. +If you don't have any other php installed on your server, use the following to be able to use php commands: + +`ln -s /opt/rh/rh-php71/root/usr/bin/php /usr/bin/php` ### 2. Configure Apache server ------------------------------ -# Edit factory apache configuration file and replace the following parameters with the correct values: -# ServerName, ServerAdmin, ErrorLog, CustomLog, SSLCertificateFile, SSLCertificateKeyFile -# Copy this file to the configuration folder of the apache server with a new name +The RPM will create a `flexisip-account-manager.conf` file inside `/opt/rh/httpd24/root/etc/httpd/conf.d/` -cp /etc/flexisip-account-manager/apache.conf /etc/httpd/conf.d/flexisip-account-manager.conf +It simply contains an Alias directive, up to you to configure your virtual host correctly. -# If your apache server is brand new you might need to add a ServerName in httpd.conf -# Start the apache server with the root user - -systemctl start httpd - -# If the httpd service doesn't start properly it might be a log folder permission issue -# Check that httpd can write logs in destination folder, if not you can use /var/log/httpd +Once you're done, reload the configuration inside httpd: `service httpd24-httpd reload` ### 3. Install and setup MySQL database --------------------------------------- -# Install the mariadb-server package and start the mariadb service - -yum install mariadb-server -systemctl start mariadb - -# Configure the newly installed mariadb server -# When asked for root password press Enter and create a new root password - -mysql_secure_installation - -# Create a database and a user with the rights to read and write -# Replace and in the following command - -mysql -u root -p -create database flexisip; -grant all on flexisip.* to @'localhost' identified by ''; -flush privileges; -exit +For the account manager to work, you need a mysql database with a user that has read/write access. ### 4. Configure XMLRPC server ------------------------------ -# The RPM package has installed XMLRPC configuration files in /etc/flexisip-account-manager/ -# Edit these files with the correct values +The RPM package has installed the configuration files in `/etc/flexisip-account-manager/` -vim /etc/flexisip-account-manager/xmlrpc.conf -vim /etc/flexisip-account-manager/internationalization.conf +Each file name should be explicit on which settings it contains. If you have any doubt, leave the default value. +At least you MUST edit the following file and fill the values you used in previous step: -# Create the necessary tables in the database using our script +`nano /etc/flexisip-account-manager/db.conf` -cd /opt/belledonne-communications/share/flexisip-account-manager -php xmlrpc.php create_tables -php xmlrpc.php create_algo_table +Now you can create the necessary tables in the database using our script: -# For remote provisioning create a default.rc file on /opt/belledonne-communications/ and set the values you want -# Client side, set the provisioning uri to the same host but to provisioning.php instead of xmlrpc.php +`php /opt/belledonne-communications/share/flexisip-account-manager/tools/create_tables.php` -### 5. Miscellaneous +### 5. Install OVH SMS gateway dependency (optionnal) + +To install OVH SMS PHP API create a `composer.json` file in `/opt/belledonne-communications/`: + +`echo '{ "name": "XMLRPC SMS API", "description": "XMLRPC SMS API", "require": { "ovh/php-ovh-sms": "dev-master" } }' > /opt/belledonne-communications/share/flexisip-account-manager/composer.json` + +Then download and install [composer](https://getcomposer.org/download/). + +Finally start composer: + +`cd /opt/belledonne-communications/share/flexisip-account-manager/ && composer install` + +### 6. Miscellaneous -------------------- -# To install OVH SMS PHP API create composer.json in /opt/belledonne-communications/ +- For remote provisioning create a `default.rc` file in `/opt/belledonne-communications/` and set the values you want +client side, set the provisioning uri to the same host but to `provisioning.php` instead of `xmlrpc.php`. -echo '{ "name": "XMLRPC SMS API", "description": "XMLRPC SMS API", "require": { "ovh/php-ovh-sms": "dev-master" } }' > /var/www/html/composer.json +- If SELinux forbids mail sending you can try this command: +`setsebool -P httpd_can_sendmail=1` -# Then execute the following command +- On CentOS firewalld might be running: +`firewall-cmd --state` -cd /opt/belledonne-communications && composer install +- If it is running you can add a rule to allow https traffic: +`firewall-cmd --zone public --permanent --add-port=444/tcp && firewall-cmd --reload` -# If you have not installed an OVH SMS API you might need to comment out the following lines in xmlrpc-sms.php +- If you use the standard https port (443) or http (80) the following command might be better: +`firewall-cmd --zone public --permanent --add-service={http,https} && firewall-cmd --reload` -require __DIR__ . '/vendor/autoload.php'; -use \Ovh\Sms\SmsApi; - -# if SELinux forbids mail sending you can try this command - -setsebool -P httpd_can_sendmail=1 - -# On CentOS firewalld might be running: -firewall-cmd --state - -# If it is running you can add a rule to allow https traffic -firewall-cmd --zone public --permanent --add-port=444/tcp && firewall-cmd --reload - -# If you use the standard https port (443) or http (80) the following command might be better -firewall-cmd --zone public --permanent --add-service={http,https} && firewall-cmd --reload - -# Also it can listen on IPv6 only -# To fix that, edit the ssl.conf in /etc/httpd/conf.d/ dir and add/set: Listen 0.0.0.0:444 https +- Also it can listen on IPv6 only. +To fix that, edit `/opt/rh/httpd24/root/etc/httpd/conf.d/ssl.conf` and add/set: `Listen 0.0.0.0:444 https` diff --git a/conf/accounts.conf b/conf/accounts.conf new file mode 100644 index 0000000..f06b110 --- /dev/null +++ b/conf/accounts.conf @@ -0,0 +1,58 @@ +?;:[]{}\| + */ +define("GENERATED_PASSWORD_CHARACTERS", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789``-=~!@#$%^&*()_+,./<>?;:[]{}\|"); + +/* + * The length of the passwords that will be generated. + * + * Default value: 8 + */ +define("GENERATED_PASSWORD_LENGTH", 8); + +/* + * If set to True, a created account will automatically be activated and it's expiration date set to now + TRIAL_DURATION_DAYS, + * otherwise expiration date for trial will be set when account is activated via a different xml rpc call. + */ +define('AUTO_ACTIVATE_ACCOUNT', False); + +/* + * Send an email to activate the account when it is created. + */ +define('SEND_ACTIVATION_EMAIL', True); + +/* + * Send a sms to activate the phone account when it is created. + */ +define('SEND_ACTIVATION_SMS', True); + +/* + * If false, creating an account with an email that is already used for another account will trigger an error + */ +define('ALLOW_SAME_EMAILS_ON_MULTILPLE_ACCOUNTS', True); + +/* + * If true, when an account creation request is received for an existing number, assumes recover procedure + */ +define('RECOVER_ACCOUNT_IF_EXISTS', False); + +?> \ No newline at end of file diff --git a/conf/auth.conf b/conf/auth.conf new file mode 100644 index 0000000..e174879 --- /dev/null +++ b/conf/auth.conf @@ -0,0 +1,34 @@ + \ No newline at end of file diff --git a/conf/db.conf b/conf/db.conf new file mode 100644 index 0000000..58b318d --- /dev/null +++ b/conf/db.conf @@ -0,0 +1,87 @@ + \ No newline at end of file diff --git a/conf/emails.conf b/conf/emails.conf new file mode 100644 index 0000000..edb9341 --- /dev/null +++ b/conf/emails.conf @@ -0,0 +1,56 @@ +Start your sip.linphone.org service

Hello,

Activation pending for using your Linphone account.
Please use the link bellow to activate your account :

%link%

 

Regards,
The Linphone team.

'); + +?> \ No newline at end of file diff --git a/conf/hooks.conf b/conf/hooks.conf new file mode 100644 index 0000000..6b5869f --- /dev/null +++ b/conf/hooks.conf @@ -0,0 +1,22 @@ + \ No newline at end of file diff --git a/conf/inapp.conf b/conf/inapp.conf new file mode 100644 index 0000000..cb7eeaf --- /dev/null +++ b/conf/inapp.conf @@ -0,0 +1,90 @@ + \ No newline at end of file diff --git a/conf/logs.conf b/conf/logs.conf new file mode 100644 index 0000000..22c9087 --- /dev/null +++ b/conf/logs.conf @@ -0,0 +1,35 @@ + \ No newline at end of file diff --git a/conf/provisioning.conf b/conf/provisioning.conf new file mode 100644 index 0000000..0dabf28 --- /dev/null +++ b/conf/provisioning.conf @@ -0,0 +1,10 @@ + \ No newline at end of file diff --git a/conf/sms.conf b/conf/sms.conf new file mode 100644 index 0000000..9183dab --- /dev/null +++ b/conf/sms.conf @@ -0,0 +1,124 @@ + 'Your Linphone validation code is #CODE#', // This one isn't required but if present it MUST be equal to SMS_OVH_US_TEMPLATE + 'FR' => 'Votre code de validation Linphone est #CODE#', +); + +?> \ No newline at end of file diff --git a/conf/tests.conf b/conf/tests.conf new file mode 100644 index 0000000..fd6d5761 --- /dev/null +++ b/conf/tests.conf @@ -0,0 +1,26 @@ + \ No newline at end of file diff --git a/flexisip-account-manager.spec b/flexisip-account-manager.spec index 1cd0a45..d419f9e 100644 --- a/flexisip-account-manager.spec +++ b/flexisip-account-manager.spec @@ -8,13 +8,13 @@ #%define _datadir %{_datarootdir} #%define _docdir %{_datadir}/doc -%define build_number 2 +%define build_number 3 #%if %{build_number} #%define build_number_ext -%{build_number} #%endif Name: bc-flexisip-account-manager -Version: 1.0.2 +Version: 1.1.0 Release: %{build_number}%{?dist} Summary: SIP account management xml-rpc server, for use with flexisip server suite. @@ -26,7 +26,7 @@ Source0: flexisip-account-manager.tar.gz #BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot # dependencies -Requires: rh-php71-php rh-php71-php-xmlrpc rh-php71-php-mysqlnd rh-php71-php-mbstring +Requires: rh-php71-php rh-php71-php-xmlrpc rh-php71-php-pdo rh-php71-php-mysqlnd rh-php71-php-mbstring %description PHP server for Linphone and Flexisip providing module for account creation. @@ -38,12 +38,12 @@ PHP server for Linphone and Flexisip providing module for account creation. %install rm -rf "$RPM_BUILD_ROOT" mkdir -p "$RPM_BUILD_ROOT/opt/belledonne-communications/share/flexisip-account-manager" -cp -R *.php "$RPM_BUILD_ROOT/opt/belledonne-communications/share/flexisip-account-manager" -cp -R README* "$RPM_BUILD_ROOT/opt/belledonne-communications/share/flexisip-account-manager" +cp -R src/* "$RPM_BUILD_ROOT/opt/belledonne-communications/share/flexisip-account-manager/" +cp README* "$RPM_BUILD_ROOT/opt/belledonne-communications/share/flexisip-account-manager/" mkdir -p "$RPM_BUILD_ROOT/etc/flexisip-account-manager" -cp -R *.conf "$RPM_BUILD_ROOT/etc/flexisip-account-manager" +cp -R conf/* "$RPM_BUILD_ROOT/etc/flexisip-account-manager/" mkdir -p $RPM_BUILD_ROOT/opt/rh/httpd24/root/etc/httpd/conf.d -cp httpd/flexisip-account-manager.conf "$RPM_BUILD_ROOT/opt/rh/httpd24/root/etc/httpd/conf.d" +cp httpd/flexisip-account-manager.conf "$RPM_BUILD_ROOT/opt/rh/httpd24/root/etc/httpd/conf.d/" %post @@ -57,7 +57,13 @@ fi %files -/opt/belledonne-communications/share/flexisip-account-manager/*.php +/opt/belledonne-communications/share/flexisip-account-manager/api/account/*.php +/opt/belledonne-communications/share/flexisip-account-manager/config/*.php +/opt/belledonne-communications/share/flexisip-account-manager/database/*.php +/opt/belledonne-communications/share/flexisip-account-manager/misc/*.php +/opt/belledonne-communications/share/flexisip-account-manager/objects/*.php +/opt/belledonne-communications/share/flexisip-account-manager/tools/*.php +/opt/belledonne-communications/share/flexisip-account-manager/xmlrpc/*.php /opt/belledonne-communications/share/flexisip-account-manager/README* %config(noreplace) /etc/flexisip-account-manager/*.conf @@ -67,6 +73,8 @@ fi rm -rf $RPM_BUILD_ROOT %changelog +* Thu Jul 4 2019 Sylvain Berfini +- New files layout * Fri Jun 28 2019 Johan Pascal - * Fri May 18 2018 Matthieu TANON diff --git a/httpd/flexisip-account-manager.conf b/httpd/flexisip-account-manager.conf index 833280e..78367f5 100644 --- a/httpd/flexisip-account-manager.conf +++ b/httpd/flexisip-account-manager.conf @@ -1,7 +1,6 @@ -Alias /flexisip-account-manager /opt/belledonne-communications/share/flexisip-account-manager - +Alias /flexisip-account-manager /opt/belledonne-communications/share/flexisip-account-manager/xmlrpc + Options FollowSymLinks MultiViews AllowOverride None Require all granted - diff --git a/src/admin.php b/src/admin.php deleted file mode 100644 index 9a234ad..0000000 --- a/src/admin.php +++ /dev/null @@ -1,73 +0,0 @@ -#! /bin/php -= 2) { - $action = $argv[1]; - if ($action == "list_accounts") { - $accounts = db_get_accounts(); - foreach ($accounts as $account) { - echo $account['username'] . '@' . $account['domain'] . ' activation status is ' . $account['activated'] . " (activation code is " . $account['activation_code'] . "): IP " . $account['ip_address'] . ", user-agent " . $account['user_agent'] . "\r\n"; - } - } else if ($action == "delete_account") { - if ($argc >= 3) { - $login = $argv[2]; - $domain = SIP_DOMAIN; - if ($argc >= 4) { - $domain = $argv[3]; - } - if (!db_account_is_existing($login, $domain)) { - echo "Error: account " . $login . " on domain " . $domain . " doesn't exist." . "\r\n"; - exit; - } - db_alias_delete($login, $domain); - db_account_delete($login, $domain); - if (startswith($login, "+")) { - db_delete_sms($login); - } - echo "Account " . $login . " successfuly deleted." . "\r\n"; - } else { - echo "Proper way to use is php admin.php delete_account [domain]" . "\r\n"; - } - } else if ($action == "activate_account") { - if ($argc >= 3) { - $login = $argv[2]; - $domain = SIP_DOMAIN; - if ($argc >= 4) { - $domain = $argv[3]; - } - if (!db_account_is_existing($login, $domain)) { - echo "Error: account " . $login . " on domain " . $domain . " doesn't exist." . "\r\n"; - exit; - } - db_account_super_activate($login, $domain); - echo "Account " . $login . " succesfuly super activated." . "\r\n"; - } else { - echo "Proper way to use is php admin.php activate_account [domain]" . "\r\n"; - } - } else if ($action == "help") { - echo "Possible commands are:" . "\r\n"; - echo "help" . "\r\n"; - echo "list_accounts" . "\r\n"; - echo "activate_account" . "\r\n"; - echo "delete_account [domain]" . "\r\n"; - } -} else { - echo "Proper way to use is php admin.php action [params]" . "\r\n"; - echo "Try php admin.php help to see all possible actions." . "\r\n"; - exit; -} - -?> diff --git a/src/api/account/create.php b/src/api/account/create.php new file mode 100644 index 0000000..57aa3e0 --- /dev/null +++ b/src/api/account/create.php @@ -0,0 +1,92 @@ +. +*/ + +header("Access-Control-Allow-Origin: *"); +header("Content-Type: application/json; charset=UTF-8"); + +include_once __DIR__ . '/../../database/database.php'; +include_once __DIR__ . '/../../objects/account.php'; +include_once __DIR__ . '/../../objects/password.php'; +include_once __DIR__ . '/../../objects/alias.php'; +include_once __DIR__ . '/../../misc/utilities.php'; + +$database = new Database(); +$db = $database->getConnection(); + +$account = new Account($db); + +$data = json_decode(file_get_contents("php://input")); +if ((!empty($data->username) || !empty($data->phone)) && (!empty($data->password) || GENERATE_PASSWORD_ENABLED) && (!empty($data->phone) || !empty($data->email))) { + $account->username = empty($data->username) ? $data->phone : $data->username; + $account->domain = empty($data->domain) ? SIP_DOMAIN : $data->domain; + $account->email = empty($data->email) ? null : $data->email; + $account->activated = AUTO_ACTIVATE_ACCOUNT ? '1' : '0'; + $account->confirmation_key = empty($data->phone) ? uniqid() : generate_4_digits_code(); + $account->ip_address = getIp(); + $account->user_agent = empty($data->user_agent) ? $_SERVER['HTTP_USER_AGENT'] : $data->user_agent; + $account->expire_time = empty($data->expire_time) ? null : $data->expire_time; + + if (!$account->getOne()) { + if ($account->create()) { + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = empty($data->algorithm) ? 'MD5' : $data->algorithm; + + if (GENERATE_PASSWORD_ENABLED) { + $password->password = hash_password($account->username, generate_password(), $account->domain, $password->algorithm); + } else { + $password->password = empty($data->password) + ? hash_password($account->username, generate_password(), $account->domain, $password->algorithm) + : $data->password; + } + if (!$password->create()) { + http_response_code(503); + echo json_encode(array("message" => "Unable to create password for account.")); + return; + } + + if (!empty($data->phone) && $data->phone != $account->username) { + $alias = new Alias($db); + $alias->account_id = $account->id; + $alias->alias = $data->phone; + $alias->domain = $account->domain; + if (!$alias->create()) { + http_response_code(503); + echo json_encode(array("message" => "Unable to create alias for account.")); + return; + } + } + + http_response_code(201); + echo json_encode(array("message" => "Account was created.")); + } else { + http_response_code(503); + echo json_encode(array("message" => "Unable to create account.")); + } + } else { + http_response_code(503); + echo json_encode(array("message" => "Account already exists")); + } +} else { + http_response_code(400); + echo json_encode(array("message" => "Unable to create account, data is incomplete.")); +} + +?> \ No newline at end of file diff --git a/src/api/account/delete.php b/src/api/account/delete.php new file mode 100644 index 0000000..b9e792b --- /dev/null +++ b/src/api/account/delete.php @@ -0,0 +1,82 @@ +. +*/ + +header("Access-Control-Allow-Origin: *"); +header("Content-Type: application/json; charset=UTF-8"); + +include_once __DIR__ . '/../../database/database.php'; +include_once __DIR__ . '/../../objects/account.php'; +include_once __DIR__ . '/../../objects/password.php'; +include_once __DIR__ . '/../../objects/alias.php'; +include_once __DIR__ . '/../../misc/utilities.php'; + +$logger = Logger::getInstance(); + +$database = new Database(); +$db = $database->getConnection(); + +$account = new Account($db); + +$data = json_decode(file_get_contents("php://input")); +if (!empty($data->id) || !empty($data->username)) { + if (!empty($data->id)) { + $account->id = $data->id; + } else if (!empty($data->username)) { + $account->username = $data->username; + if (!empty($data->domain)) { + $account->domain = $data->domain; + } + } + + if ($account->getOne()) { + $password = new Password($db); + $password->account_id = $account->id; + + $alias = new Alias($db); + $alias->account_id = $account->id; + + if ($account->delete()) { + if (!$password->delete()) { + $logger->error("Failed to delete password(s) for account id " . $password->account_id); + } + + if ($alias->getOne()) { + if (!$alias->delete()) { + $logger->error("Failed to delete alias for account id " . $alias->account_id); + } + } + + http_response_code(200); + echo json_encode(array("message" => "Account was deleted.")); + } else { + http_response_code(503); + echo json_encode(array("message" => "Unable to delete account.")); + } + } else { + http_response_code(404); + echo json_encode(array("message" => "Account doesn't exist")); + } +} else { + http_response_code(400); + echo json_encode(array("message" => "Unable to delete account, data is incomplete.")); +} + + +?> \ No newline at end of file diff --git a/src/api/account/get.php b/src/api/account/get.php new file mode 100644 index 0000000..35f8b44 --- /dev/null +++ b/src/api/account/get.php @@ -0,0 +1,72 @@ +. +*/ + +header("Access-Control-Allow-Origin: *"); +header("Content-Type: application/json; charset=UTF-8"); + +include_once __DIR__ . '/../../database/database.php'; +include_once __DIR__ . '/../../objects/account.php'; +include_once __DIR__ . '/../../objects/password.php'; +include_once __DIR__ . '/../../objects/alias.php'; + +$database = new Database(); +$db = $database->getConnection(); + +$account = new Account($db); +$account->id = isset($_GET['id']) ? $_GET['id'] : null; +$account->username = isset($_GET['username']) ? $_GET['username'] : null; +$account->domain = isset($_GET['domain']) ? $_GET['domain'] : null; + +$account->getOne(); +if (!empty($account->id) && !empty($account->username) && !empty($account->domain)) { + $account_item = array( + "id" => $account->id, + "username" => $account->username, + "domain" => $account->domain, + "activated" => $account->activated, + "alias" => $account->alias, + "passwords" => array() + ); + + $pwd = new Password($db); + $pwd->account_id = $account->id; + + $stmt = $pwd->getAll(); + $num = $stmt->rowCount(); + if ($num > 0) { + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + extract($row); + $password_item = array( + "id" => $id, + "password" => $password, + "algorithm" => $algorithm + ); + $account_item["passwords"][$algorithm] = $password_item; + } + } + + http_response_code(200); + echo json_encode($account_item); +} else { + http_response_code(404); + echo json_encode(array("message" => "Account doesn't exist")); +} + +?> \ No newline at end of file diff --git a/src/api/account/list.php b/src/api/account/list.php new file mode 100644 index 0000000..10fc607 --- /dev/null +++ b/src/api/account/list.php @@ -0,0 +1,56 @@ +. +*/ + +header("Access-Control-Allow-Origin: *"); +header("Content-Type: application/json; charset=UTF-8"); + +include_once __DIR__ . '/../../database/database.php'; +include_once __DIR__ . '/../../objects/account.php'; + +$database = new Database(); +$db = $database->getConnection(); + +$account = new Account($db); + +$stmt = $account->getAll(); +$num = $stmt->rowCount(); + +if ($num > 0) { + $accounts = array(); + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + extract($row); + $account_item = array( + "id" => $id, + "username" => $username, + "domain" => $domain, + "activated" => $activated, + "alias" => $alias + ); + array_push($accounts, $account_item); + } + + http_response_code(200); + echo json_encode($accounts); +} else { + http_response_code(404); + echo json_encode(array("message" => "No account found")); +} + +?> \ No newline at end of file diff --git a/src/api/account/update.php b/src/api/account/update.php new file mode 100644 index 0000000..88316ed --- /dev/null +++ b/src/api/account/update.php @@ -0,0 +1,108 @@ +. +*/ + +header("Access-Control-Allow-Origin: *"); +header("Content-Type: application/json; charset=UTF-8"); + +include_once __DIR__ . '/../../database/database.php'; +include_once __DIR__ . '/../../objects/account.php'; +include_once __DIR__ . '/../../objects/password.php'; +include_once __DIR__ . '/../../objects/alias.php'; +include_once __DIR__ . '/../../misc/utilities.php'; + +$logger = Logger::getInstance(); + +$database = new Database(); +$db = $database->getConnection(); + +$account = new Account($db); + +$data = json_decode(file_get_contents("php://input")); +if (!empty($data->id) || !empty($data->username)) { + if (!empty($data->id)) { + $account->id = $data->id; + } else if (!empty($data->username)) { + $account->username = $data->username; + if (!empty($data->domain)) { + $account->domain = $data->domain; + } + } + + if ($account->getOne()) { + $account->username = empty($data->username) ? $data->phone : $data->username; + $account->domain = empty($data->domain) ? SIP_DOMAIN : $data->domain; + $account->email = empty($data->email) ? null : $data->email; + $account->activated = is_activated($data->activated) ? "1" : "0"; + + $password = new Password($db); + $password->account_id = $account->id; + + $alias = new Alias($db); + $alias->account_id = $account->id; + + if ($account->update()) { + if (!empty($data->password)) { + $password->algorithm = empty($data->algorithm) ? 'MD5' : $data->algorithm; + $getOne = $password->getOne(); + // Wait after getOne as it will override data if found + $password->password = $data->password; + if ($getOne) { + if (!$password->update()) { + $logger->error("Failed to update password for account id " . $alias->account_id); + } + } else { + if (!$password->create()) { + $logger->error("Failed to create password for account id " . $alias->account_id); + } + } + } + + if (!empty($data->phone)) { + $getOne = $alias->getOne(); + // Wait after getOne as it will override data if found + $alias->alias = $data->phone; + $alias->domain = $account->domain; + if ($getOne) { + if (!$alias->update()) { + $logger->error("Failed to update alias for account id " . $alias->account_id); + } + } else { + if (!$alias->create()) { + $logger->error("Failed to create alias for account id " . $alias->account_id); + } + } + } + + http_response_code(200); + echo json_encode(array("message" => "Account was updated.")); + } else { + http_response_code(503); + echo json_encode(array("message" => "Unable to update account.")); + } + } else { + http_response_code(404); + echo json_encode(array("message" => "Account doesn't exist")); + } +} else { + http_response_code(400); + echo json_encode(array("message" => "Unable to update account, data is incomplete.")); +} + +?> \ No newline at end of file diff --git a/src/authentication.php b/src/authentication.php deleted file mode 100644 index d56ba78..0000000 --- a/src/authentication.php +++ /dev/null @@ -1,81 +0,0 @@ - diff --git a/src/config/config.php b/src/config/config.php new file mode 100644 index 0000000..df65788 --- /dev/null +++ b/src/config/config.php @@ -0,0 +1,34 @@ +. +*/ + +define("PATH_TO_CONFIG", "/etc/flexisip-account-manager"); + +include_once PATH_TO_CONFIG . '/accounts.conf'; +include_once PATH_TO_CONFIG . '/auth.conf'; +include_once PATH_TO_CONFIG . '/db.conf'; +include_once PATH_TO_CONFIG . '/emails.conf'; +include_once PATH_TO_CONFIG . '/hooks.conf'; +include_once PATH_TO_CONFIG . '/inapp.conf'; +include_once PATH_TO_CONFIG . '/logs.conf'; +include_once PATH_TO_CONFIG . '/provisioning.conf'; +include_once PATH_TO_CONFIG . '/sms.conf'; +include_once PATH_TO_CONFIG . '/tests.conf'; + +?> \ No newline at end of file diff --git a/src/database/database.php b/src/database/database.php new file mode 100644 index 0000000..415059a --- /dev/null +++ b/src/database/database.php @@ -0,0 +1,41 @@ +. +*/ + +include_once __DIR__ . '/../config/config.php'; +include_once __DIR__ . '/../misc/logging.php'; + +class Database { + public $conn; + + public function getConnection() { + $this->conn = null; + + try { + $this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD); + $this->conn->exec("set names utf8"); + } catch(PDOException $exception) { + Logger::getInstance()->error("Connection error: " . $exception->getMessage()); + } + + return $this->conn; + } +} + +?> \ No newline at end of file diff --git a/src/hooks.php b/src/hooks.php deleted file mode 100644 index d6a7c8b..0000000 --- a/src/hooks.php +++ /dev/null @@ -1,17 +0,0 @@ - \ No newline at end of file diff --git a/src/internationalization.conf b/src/internationalization.conf deleted file mode 100644 index 78a4650..0000000 --- a/src/internationalization.conf +++ /dev/null @@ -1,7 +0,0 @@ - 'Your Linphone validation code is #CODE#', // This one isn't required but if present it MUST be equal to SMS_OVH_US_TEMPLATE - 'FR' => 'Votre code de validation Linphone est #CODE#', - ); -?> \ No newline at end of file diff --git a/src/logging.php b/src/logging.php deleted file mode 100644 index 623ac52..0000000 --- a/src/logging.php +++ /dev/null @@ -1,17 +0,0 @@ - \ No newline at end of file diff --git a/src/misc/email.php b/src/misc/email.php new file mode 100644 index 0000000..b16e144 --- /dev/null +++ b/src/misc/email.php @@ -0,0 +1,90 @@ +. +*/ + +include_once __DIR__ . '/../config/config.php'; +include_once __DIR__ . '/../misc/logging.php'; + +function send_email($email, $subject, $text, $html) { + $site = EMAIL_SITE; + $from = EMAIL_FROM_ADDR; + $name = EMAIL_FROM_NAME; + $to = $email; + $from = $name." <".$from.">"; + + $limite = "_----------=_parties_".md5(uniqid (rand())); + + $headers = "Reply-to: ".$from."\n"; + $headers .= "From: ".$from."\n"; + $headers .= "Return-Path: ".$from."\n"; + $headers .= "X-Sender: <".$site.">\n"; + $headers .= "X-Mailer: PHP\n"; + $headers .= "X-auth-smtp-user: ".$from." \n"; + $headers .= "X-abuse-contact: ".$from." \n"; + $headers .= "X-auth-smtp-user: ".$from." \n"; + $headers .= "X-abuse-contact: ".$from." \n"; + $headers .= "Date: ".date("D, j M Y G:i:s O")."\n"; + $headers .= "MIME-Version: 1.0\n"; + $headers .= "Content-Type: multipart/alternative; boundary=\"".$limite."\""; + + $message = ""; + + $message .= "--".$limite."\n"; + $message .= "Content-Type: text/plain; charset=\"utf-8\"\n"; + $message .= "Content-Transfer-Encoding: 8bit\n\n"; + $message .= $text; + + $message .= "\n\n--".$limite."\n"; + $message .= "Content-Type: text/html; charset=\"utf-8\"\n"; + $message .= "Content-Transfer-Encoding: 8bit;\n\n"; + $message .= $html; + + $message .= "\n--".$limite."--"; + + $params = "-f" . EMAIL_FROM_ADDR . " -O DeliveryMode=b"; + $result = mail($email, $subject, $message, $headers, $params); + if (!$result) { + Logger::getInstance()->error("[EMAIL] Email delivery declined !"); + } +} + +function send_email_with_activation_link($email, $key) { + if( !EMAIL_ENABLED ){ + Logger::getInstance()->warning("[EMAIL] Emails are disabled"); + return "WARNING_EMAILS_DISABLED"; + } + + $pageURL = 'http'; + if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} + $pageURL .= "://"; + + $link = $pageURL . EMAIL_ACTIVATION_LINK; + $link = str_replace("%key%", $key, $link); + Logger::getInstance()->debug("[EMAIL] Activation link is " . $link); + + $body = str_replace("%link%", $link, EMAIL_ACTIVATION_BODY); + Logger::getInstance()->debug("[EMAIL] Activation body is " . $body); + $body_html = str_replace("%link%", $link, EMAIL_ACTIVATION_BODY_HTML); + Logger::getInstance()->debug("[EMAIL] Activation html body is " . $body_html); + + send_email($email, EMAIL_ACTIVATION_SUBJECT, $body, $body_html); + Logger::getInstance()->message("[EMAIL] Email sent to email " . $email . " to activate the account"); +} + +?> \ No newline at end of file diff --git a/src/misc/logging.php b/src/misc/logging.php new file mode 100644 index 0000000..fa0a653 --- /dev/null +++ b/src/misc/logging.php @@ -0,0 +1,88 @@ +. +*/ + +include_once __DIR__ . '/../config/config.php'; + +class Logger { + private static $instance = null; + + private $log_file; + + public function __construct() { + if (!LOGS_ENABLED) { + return; + } + if (USE_ONE_LOG_FILE) { + $this->log_file = LOG_FILE; + } else { + if (!file_exists(LOG_DIR)) { + mkdir(LOG_DIR, 0777, true); + } + $this->log_file = LOG_DIR . "/" . date('d-M-Y') . '.logs'; + } + } + + public static function getInstance() + { + if (!self::$instance) { + self::$instance = new Logger(); + } + + return self::$instance; + } + + function mylog($level, $message) { + if (!LOGS_ENABLED) { + return; + } + + if (is_array($message)) { + $message = implode(" ", $message); + } + + $now = getdate(); + $month = sprintf("%02d", $now["mon"]); + $day = sprintf("%02d", $now["mday"]); + $hours = sprintf("%02d", $now["hours"]); + $minutes = sprintf("%02d", $now["minutes"]); + $seconds = sprintf("%02d", $now["seconds"]); + $log_msg = "[" . $day . "/" . $month . "/" . $now["year"] . " " . $hours . ":" . $minutes . ":" . $seconds . "] [" . $level . "] " . $message . "\r\n"; + + file_put_contents($this->log_file, $log_msg, FILE_APPEND); + } + + function error($message) { + $this->mylog("Error", $message); + } + + function warning($message) { + $this->mylog("Warning", $message); + } + + function message($message) { + $this->mylog("Message", $message); + } + + function debug($message) { + $this->mylog("Debug", $message); + } +} + +?> \ No newline at end of file diff --git a/src/misc/sms.php b/src/misc/sms.php new file mode 100644 index 0000000..3bacc47 --- /dev/null +++ b/src/misc/sms.php @@ -0,0 +1,172 @@ +. +*/ + +// The following can't be put inside a function... +// So comment it out if not using the OVH SMS API +require __DIR__ . '/../../vendor/autoload.php'; +use \Ovh\Sms\SmsApi; + +include_once __DIR__ . '/../config/config.php'; +include_once __DIR__ . '/../misc/logging.php'; +include_once __DIR__ . '/../xmlrpc/results_values.php'; +include_once __DIR__ . '/utilities.php'; + +// Internationalization + +function get_sms_string_for_lang($lang) { + global $SMS_OVH_TEMPLATE; + if (isset($SMS_OVH_TEMPLATE[$lang])) { + return $SMS_OVH_TEMPLATE[$lang]; + } + Logger::getInstance()->warning("SMS template not found for lang " . $lang . ", using US template"); + return SMS_OVH_US_TEMPLATE; +} + +// SMS API + +function send_sms_ovh($phone, $key, $lang) { + if (!SMS_API_ENABLED) { + Logger::getInstance()->warning("[SMS] SMS API disabled"); + return SMS_DISABLED; + } + + $sms = new SmsApi(SMS_OVH_API_KEY, SMS_OVH_API_SECRET, SMS_OVH_ENDPOINT, SMS_OVH_CONSUMER_KEY); + $accounts = $sms->getAccounts(); + $sms->setAccount($accounts[0]); + if (SMS_USE_SENDER) { + $senders = $sms->getSenders(); + + /* The account must be validated in the OVH interface and by OVH itself */ + if (count($senders) == 0) { + Logger::getInstance()->warning("[SMS] No sender found, creating one " . SMS_OVH_SENDER . " / " . SMS_OVH_REASON . " : " . SMS_OVH_DESC); + $sms->addSender(SMS_OVH_SENDER, SMS_OVH_REASON, SMS_OVH_DESC); + $senders = $sms->getSenders(); + } + } + + $message = $sms->createMessage(); + if (SMS_USE_SENDER && count($senders) > 0) { + foreach ($senders as $sender) { + if ($sender == SMS_OVH_SENDER) { + if ($sms->checkSender($sender)) { + // Check if sender exists and is valid, otherwise it will create an exception and sms won't be sent + Logger::getInstance()->message("[SMS] Found valid sender " . $sender . ", using it"); + $message->setSender($sender); + break; + } else { + Logger::getInstance()->error("[SMS] Found sender " . $sender . " but it is not valid"); + } + } + } + } + $message->addReceiver($phone); + $message->setIsMarketing(FALSE); + + $text = get_sms_string_for_lang($lang); + $text = str_replace("#CODE#", $key, $text); + $result = $message->send($text); + + $credits_removed = $result['totalCreditsRemoved']; + Logger::getInstance()->message("[SMS] " . $credits_removed . " credit removed"); + $invalid_receiver = $result['invalidReceivers']; + $valid_receiver = $result['validReceivers']; + if (count($invalid_receiver) > 0) { + Logger::getInstance()->error("[SMS] phone number " . $phone . " seems invalid"); + } else if (count($valid_receiver) > 0) { + Logger::getInstance()->message("[SMS] " . $text . " sent to " . $phone); + } else { + Logger::getInstance()->warning("[SMS] Both valid and invalid receiver lists are empty..."); + } +} + +function send_sms_legacy($phone, $password) { + if (!SMS_API_ENABLED) { + Logger::getInstance()->warning("[SMS] SMS API disabled"); + return SMS_DISABLED; + } + + $url = SMS_API_URL; + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); + curl_setopt($ch, CURLOPT_USERPWD, SMS_API_USERNAME . ":" . SMS_API_PASSWORD); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/x-www-form-urlencoded' + )); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( + 'mobile' => $phone, + 'password' => $password, + ))); + $result = curl_exec($ch); + Logger::getInstance()->message("[SMS] SMS confirmation sent to " . $phone . " using password " . $password . ", request result is " . $result); + curl_close($ch); +} + +function send_sms($phone, $key, $lang, $password) { + if (!SMS_API_ENABLED) { + Logger::getInstance()->warning("[SMS] SMS API disabled"); + return SMS_DISABLED; + } + + if (startswith($phone, TESTS_PHONE_PREFIX)) { + Logger::getInstance()->error("[SMS] Not sending sms to fake number used for tests purposes: " . $phone); + return TEST_ACCOUNTS_DISABLED; + } + + $now_date = new DateTime('now'); + $now = $now_date->getTimestamp() * 1000; + + if (db_has_sms_already_been_sent_to($phone)) { + $count = db_get_sms_count($phone); + $time = db_get_last_sms($phone); + $diff = $now - $time; + if ($count >= SMS_COUNT_LIMIT_IN_PERIOD and $diff < SMS_TIME_PERIOD) { + Logger::getInstance()->error("[SMS] Last sms was sent at " . $time . ", time elapsed since then is " . $diff . "ms which is less than the configured time period " . SMS_TIME_PERIOD); + return MAX_SMS_ALLOWED_EXCEEDED; + } else if ($diff >= SMS_TIME_PERIOD) { + db_update_sms($phone, $now, 1); + } else { + $count = $count + 1; + db_update_sms($phone, $now, $count); + } + } else { + db_insert_sms($phone, $now); + } + + + if (SMS_OVH_API_KEY != NULL && SMS_OVH_API_KEY != "" && SMS_OVH_API_SECRET != NULL && SMS_OVH_API_SECRET != "" && SMS_OVH_CONSUMER_KEY != NULL && SMS_OVH_CONSUMER_KEY != "" && SMS_OVH_ENDPOINT != NULL && SMS_OVH_ENDPOINT != "") { + try { + send_sms_ovh($phone, $key, $lang); + return OK; + } catch (Exception $e) { + Logger::getInstance()->error("[OVH-SMS] Exception: " . $e->getMessage()); + } + } else if (SMS_API_URL != NULL && SMS_API_URL != "" && SMS_API_USERNAME != NULL && SMS_API_USERNAME != "" && SMS_API_PASSWORD != NULL && SMS_API_PASSWORD != "") { + send_sms_legacy($phone, $password); + return OK; + } else { + Logger::getInstance()->error("[SMS] No SMS API configured, discarding sms..."); + return OK; + } + return SMS_API_FAILURE; +} + +?> \ No newline at end of file diff --git a/src/misc/utilities.php b/src/misc/utilities.php new file mode 100644 index 0000000..7c4e5b3 --- /dev/null +++ b/src/misc/utilities.php @@ -0,0 +1,125 @@ +. +*/ + +include_once __DIR__ . '/../config/config.php'; +include_once __DIR__ . '/logging.php'; +if (EMAIL_ENABLED) { + include_once __DIR__ . '/email.php'; +} +if (SMS_API_ENABLED) { + include_once __DIR__ . '/sms.php'; +} + +function startswith($hay, $needle) { + return substr($hay, 0, strlen($needle)) === $needle; +} + +function endswith($hay, $needle) { + return $needle === "" || (($temp = strlen($hay) - strlen($needle)) >= 0 and strpos($hay, $needle, $temp) !== FALSE); +} + +function getIp() { + $ip = $_SERVER['REMOTE_ADDR']; + if (!empty($_SERVER['HTTP_CLIENT_IP'])) { + $ip = $_SERVER['HTTP_CLIENT_IP']; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; + } + return $ip; +} + +function get_trial_expiration_date() { + $expiration_date = new DateTime('now +' . TRIAL_DURATION_DAYS . ' days'); + $expiration = $expiration_date->getTimestamp() * 1000; + return $expiration; +} + +function is_activated($activated) { + return $activated == "1" || $activated == 1 || $activated; +} + +// XMLRPC parameters + +function check_parameter($param, $param_name = "username") { + if ($param == NULL || $param == "") { + Logger::getInstance()->warning("Parameter " . $param_name . " is missing"); + return false; + } + return true; +} + +function get_algo($algo) { + if ($algo == NULL || $algo == "") { + Logger::getInstance()->warning("Algo parameter wasn't found, assume MD5"); + return "MD5"; + } + if ($algo == "MD5" || $algo == "SHA-256" || $algo == "clrtxt") { + return $algo; + } + Logger::getInstance()->error("Algo " . $algo . " is not supported"); + return NULL; +} + +function get_domain($param) { + if ($param == NULL || $param == "") { + Logger::getInstance()->warning("Domain parameter wasn't found, assume " . SIP_DOMAIN); + $param = SIP_DOMAIN; + } + return $param; +} + +function get_lang($param) { + if ($param == NULL || $param == "") { + Logger::getInstance()->warning("lang parameter wasn't found, use US"); + return 'US'; + } else if (strlen($param) > 2) { + $param = substr($param, 0, 2); + } + return strtoupper($param); +} + +// Password + +function hash_password($user, $password, $domain, $algo) { + $hashed_password = $password; + if ($algo == "" || $algo == "MD5") $hashed_password = hash("md5", $user . ":" . $domain . ":" . $password); + if ($algo == "SHA-256") $hashed_password = hash("sha256", $user . ":" . $domain . ":" . $password); + return $hashed_password; +} + +function generate_password() { + $generated_password = substr(str_shuffle(GENERATED_PASSWORD_CHARACTERS), 0, GENERATED_PASSWORD_LENGTH); + return $generated_password; +} + +function generate_4_digits_code() { + $generated_password = substr(str_shuffle("0123456789"), 0, 4); + return $generated_password; +} + +function password_match($pwd1, $pwd2) { + if ($pwd1 != $pwd2) { + Logger::getInstance()->error("Password doesn't match"); + return false; + } + return true; +} + +?> diff --git a/src/mysqli-db.php b/src/mysqli-db.php deleted file mode 100644 index 0633f9d..0000000 --- a/src/mysqli-db.php +++ /dev/null @@ -1,48 +0,0 @@ -connect_errno) { - mylog("[ERROR][DB] Connection failed: " . $conn->connect_errno . " - " . $conn->connect_error); - } - return $conn; -} - -function linphonedb_escape($conn, $param) { - return mysqli_real_escape_string($conn, $param); -} - -function linphonedb_query($queryStr, $conn) { - $result = mysqli_query($conn, $queryStr); - if (! $result) { - mylog("[ERROR][DB] Invalid query: " . $conn->connect_errno . " - " . $conn->connect_error); - return ""; - } - // cannot log result because fetch needed - // mylog("[DB] Query: " . $queryStr); - return $result; -} - -function linphonedb_fetch($result) { - if ($result->num_rows === 0) { - mylog("[ERROR][DB] Result is empty..."); - } - $row = mysqli_fetch_array($result, MYSQLI_NUM); - return $row; -} - -function linphonedb_clean($result) { - if (!is_bool($result)) { // some query may return a boolean, in that case we must not call free - mysqli_free_result($result); - } -} - -function linphonedb_close($conn) { - mysqli_close($conn); -} - -?> diff --git a/src/objects/account.php b/src/objects/account.php new file mode 100644 index 0000000..fb4f354 --- /dev/null +++ b/src/objects/account.php @@ -0,0 +1,275 @@ +. +*/ + +class Account { + private $conn; + + public $id; + public $username; + public $domain; + public $email; + public $activated; + public $confirmation_key; + public $ip_address; + public $user_agent; + public $creation_time; + public $expire_time; + public $alias; + + public function __construct($db) { + $this->conn = $db; + } + + public function __toString() { + $to_string = "Account: "; + if (!empty($this->id)) { + $to_string = $to_string . "id=" . $this->id . ", "; + } + if (!empty($this->username)) { + $to_string = $to_string . "username=" . $this->username . ", "; + } + if (!empty($this->domain)) { + $to_string = $to_string . "domain=" . $this->domain . ", "; + } + if (!empty($this->email)) { + $to_string = $to_string . "email=" . $this->email . ", "; + } + if (!empty($this->activated)) { + $to_string = $to_string . "activated=" . $this->activated . ", "; + } + if (!empty($this->confirmation_key)) { + $to_string = $to_string . "confirmation_key=" . $this->confirmation_key . ", "; + } + if (!empty($this->alias)) { + $to_string = $to_string . "alias=" . $this->alias . ", "; + } + return substr($to_string, 0, -2); + } + + function dropTable() { + $query = "DROP TABLE IF EXISTS " . ACCOUNTS_DB_TABLE; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Dropping table " . ACCOUNTS_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function createTable() { + $query = "CREATE TABLE IF NOT EXISTS " . ACCOUNTS_DB_TABLE . " ( + id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT, + username VARCHAR(64) NOT NULL, + domain VARCHAR(64) NOT NULL, + email VARCHAR(64), + activated VARCHAR(1) NOT NULL DEFAULT '0', + confirmation_key VARCHAR(14) DEFAULT NULL, + ip_address VARCHAR(39) NOT NULL, + user_agent VARCHAR(256) NOT NULL, + creation_time DATETIME NOT NULL, + expire_time DATETIME, + PRIMARY KEY (id), UNIQUE KEY identity (username, domain))"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Creating table " . ACCOUNTS_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function delete() { + $query = "DELETE FROM " . ACCOUNTS_DB_TABLE . " WHERE id = ?"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + $this->id = htmlspecialchars(strip_tags($this->id)); + $stmt->bindParam(1, $this->id); + + Logger::getInstance()->debug("Deleting " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function create() { + $query = "INSERT INTO " . ACCOUNTS_DB_TABLE . " SET username=:username, domain=:domain, email=:email, + confirmation_key=:confirmation_key, ip_address=:ip_address, user_agent=:user_agent, creation_time=:creation_time"; + + if (USE_IN_APP_PURCHASES) { + $query = $query . ", expire_time=DATE_ADD(NOW(), INTERVAL " . EXPIRATION_DELAY . " MINUTE)"; + $this->expire_time = htmlspecialchars(strip_tags($this->expire_time)); + } + + $this->creation_time = date('Y-m-d H:i:s'); + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->username = htmlspecialchars(strip_tags($this->username)); + $this->domain = htmlspecialchars(strip_tags($this->domain)); + $this->email = htmlspecialchars(strip_tags($this->email)); + $this->confirmation_key = htmlspecialchars(strip_tags($this->confirmation_key)); + $this->ip_address = htmlspecialchars(strip_tags($this->ip_address)); + $this->user_agent = htmlspecialchars(strip_tags($this->user_agent)); + $this->creation_time = htmlspecialchars(strip_tags($this->creation_time)); + + $stmt->bindParam(":username", $this->username); + $stmt->bindParam(":domain", $this->domain); + $stmt->bindParam(":email", $this->email); + $stmt->bindParam(":confirmation_key", $this->confirmation_key); + $stmt->bindParam(":ip_address", $this->ip_address); + $stmt->bindParam(":user_agent", $this->user_agent); + $stmt->bindParam(":creation_time", $this->creation_time); + + Logger::getInstance()->debug("Creating " . (string)$this); + if ($stmt->execute()) { + $this->id = $this->conn->lastInsertId(); + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function update() { + $query = "UPDATE " . ACCOUNTS_DB_TABLE . " SET username=:username, domain=:domain, activated=:activated"; + + if (!empty($this->email)) { + $query = $query . ", email=:email"; + } + if (!empty($this->confirmation_key)) { + $query = $query . ", confirmation_key=:confirmation_key"; + } + if (USE_IN_APP_PURCHASES) { + $query = $query . ", expire_time=:expire_time"; + } + + $query = $query . " WHERE id=:id"; + + $stmt = $this->conn->prepare($query); + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $this->username = htmlspecialchars(strip_tags($this->username)); + $this->domain = htmlspecialchars(strip_tags($this->domain)); + $this->activated = htmlspecialchars(strip_tags($this->activated)); + + $stmt->bindParam(":username", $this->username); + $stmt->bindParam(":domain", $this->domain); + $stmt->bindParam(":activated", $this->activated); + $stmt->bindParam(":id", $this->id); + + if (!empty($this->email)) { + $this->email = htmlspecialchars(strip_tags($this->email)); + $stmt->bindParam(":email", $this->email); + } + if (!empty($this->confirmation_key)) { + $this->confirmation_key = htmlspecialchars(strip_tags($this->confirmation_key)); + $stmt->bindParam(":confirmation_key", $this->confirmation_key); + } + if (USE_IN_APP_PURCHASES) { + $this->expire_time = htmlspecialchars(strip_tags($this->expire_time)); + $stmt->bindParam(":expire_time", $this->expire_time); + } + + Logger::getInstance()->debug("Updating " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function getAll() { + $query = "SELECT ac.id, ac.username, ac.domain, ac.activated, ac.confirmation_key, al.alias FROM " . ACCOUNTS_DB_TABLE . + " ac LEFT JOIN " . ALIAS_DB_TABLE . " al ON ac.id = al.account_id"; + $stmt = $this->conn->prepare($query); + Logger::getInstance()->debug("GetAll " . (string)$this); + $stmt->execute(); + return $stmt; + } + + function getOne() { + $query = "SELECT ac.id, ac.username, ac.domain, ac.activated, ac.confirmation_key, al.alias FROM " . ACCOUNTS_DB_TABLE . + " ac LEFT JOIN " . ALIAS_DB_TABLE . " al ON ac.id = al.account_id"; + + if (!empty($this->id)) { + $query = $query . " WHERE ac.id = ?"; + $this->id = htmlspecialchars(strip_tags($this->id)); + } else if (!empty($this->username)) { + $query = $query . " WHERE ac.username = ?"; + $this->username = htmlspecialchars(strip_tags($this->username)); + if (!empty($this->domain)) { + $query = $query . " AND ac.domain = ?"; + $this->domain = htmlspecialchars(strip_tags($this->domain)); + } + } else if (!empty($this->email)) { + $query = $query . " WHERE ac.email = ?"; + $this->email = htmlspecialchars(strip_tags($this->email)); + } else { + return false; + } + + $query = $query . " LIMIT 0,1"; + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + if (!empty($this->id)) { + $stmt->bindParam(1, $this->id); + } else if (!empty($this->username)) { + $stmt->bindParam(1, $this->username); + if (!empty($this->domain)) { + $stmt->bindParam(2, $this->domain); + } + } else if (!empty($this->email)) { + $stmt->bindParam(1, $this->email); + } + + Logger::getInstance()->debug("GetOne " . (string)$this); + if ($stmt->execute()) { + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row == null) { + Logger::getInstance()->message("Couldn't find account matching " . (string)$this); + return false; + } + + $this->id = $row['id']; + $this->username = $row['username']; + $this->domain = $row['domain']; + $this->activated = $row['activated']; + $this->confirmation_key = $row['confirmation_key']; + $this->alias = $row['alias']; + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } +} + +?> \ No newline at end of file diff --git a/src/objects/alias.php b/src/objects/alias.php new file mode 100644 index 0000000..d3a0289 --- /dev/null +++ b/src/objects/alias.php @@ -0,0 +1,233 @@ +. +*/ + +class Alias { + private $conn; + + public $id; + public $account_id; + public $alias; + public $domain; + + public function __construct($db) { + $this->conn = $db; + } + + public function __toString() { + $to_string = "Alias: "; + if (!empty($this->id)) { + $to_string = $to_string . "id=" . $this->id . ", "; + } + if (!empty($this->account_id)) { + $to_string = $to_string . "account_id=" . $this->account_id . ", "; + } + if (!empty($this->alias)) { + $to_string = $to_string . "alias=" . $this->alias . ", "; + } + if (!empty($this->domain)) { + $to_string = $to_string . "domain=" . $this->domain . ", "; + } + return substr($to_string, 0, -2); + } + + function dropTable() { + $query = "DROP TABLE IF EXISTS " . ALIAS_DB_TABLE; + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Dropping table " . ALIAS_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function createTable() { + $query = "CREATE TABLE IF NOT EXISTS " . ALIAS_DB_TABLE . " ( + id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT, + account_id INTEGER(11) UNSIGNED NOT NULL, + alias VARCHAR(64) NOT NULL, + domain VARCHAR(64) NOT NULL, + PRIMARY KEY (id), UNIQUE KEY identity (alias, domain))"; + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Creating table " . ALIAS_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function delete() { + $query = "DELETE FROM " . ALIAS_DB_TABLE; + + if (!empty($this->id)) { + $query = $query . " WHERE id = ?"; + $this->id = htmlspecialchars(strip_tags($this->id)); + } else if (!empty($this->account_id)) { + $query = $query . " WHERE account_id = ?"; + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + } else if (!empty($this->alias)) { + $query = $query . " WHERE alias = ?"; + $this->alias = htmlspecialchars(strip_tags($this->alias)); + if (!empty($this->domain)) { + $query = $query . " AND domain = ?"; + $this->domain = htmlspecialchars(strip_tags($this->domain)); + } + } else { + return false; + } + + + $stmt = $this->conn->prepare($query); + $this->id = htmlspecialchars(strip_tags($this->id)); + + if (!empty($this->id)) { + $stmt->bindParam(1, $this->id); + } else if (!empty($this->account_id)) { + $stmt->bindParam(1, $this->account_id); + } else if (!empty($this->alias)) { + $stmt->bindParam(1, $this->alias); + if (!empty($this->domain)) { + $stmt->bindParam(2, $this->domain); + } + } + + Logger::getInstance()->debug("Deleting " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function create() { + $query = "INSERT INTO " . ALIAS_DB_TABLE . " SET account_id=:account_id, alias=:alias, domain=:domain"; + + $stmt = $this->conn->prepare($query); + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + $this->alias = htmlspecialchars(strip_tags($this->alias)); + $this->domain = htmlspecialchars(strip_tags($this->domain)); + + $stmt->bindParam(":account_id", $this->account_id); + $stmt->bindParam(":alias", $this->alias); + $stmt->bindParam(":domain", $this->domain); + + Logger::getInstance()->debug("Creating " . (string)$this); + if ($stmt->execute()) { + $this->id = $this->conn->lastInsertId(); + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function update() { + $query = "UPDATE " . ALIAS_DB_TABLE . " SET account_id=:account_id, alias=:alias, domain=:domain WHERE id=:id"; + + $stmt = $this->conn->prepare($query); + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + $this->alias = htmlspecialchars(strip_tags($this->alias)); + $this->domain = htmlspecialchars(strip_tags($this->domain)); + + $stmt->bindParam(":account_id", $this->account_id); + $stmt->bindParam(":alias", $this->alias); + $stmt->bindParam(":domain", $this->domain); + $stmt->bindParam(":id", $this->id); + + Logger::getInstance()->debug("Updating " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function getAll() { + $query = "SELECT id, account_id, alias, domain FROM " . ALIAS_DB_TABLE; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + Logger::getInstance()->debug("GetAll " . (string)$this); + $stmt->execute(); + + return $stmt; + } + + function getOne() { + $query = "SELECT id, account_id, alias, domain FROM " . ALIAS_DB_TABLE; + + if (!empty($this->id)) { + $query = $query . " WHERE id = ?"; + $this->id = htmlspecialchars(strip_tags($this->id)); + } else if (!empty($this->account_id)) { + $query = $query . " WHERE account_id = ?"; + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + } else if (!empty($this->alias)) { + $query = $query . " WHERE alias = ?"; + $this->alias = htmlspecialchars(strip_tags($this->alias)); + if (!empty($this->domain)) { + $query = $query . " AND domain = ?"; + $this->domain = htmlspecialchars(strip_tags($this->domain)); + } + } else { + return false; + } + + $query = $query . " LIMIT 0,1"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + if (!empty($this->id)) { + $stmt->bindParam(1, $this->id); + } else if (!empty($this->account_id)) { + $stmt->bindParam(1, $this->account_id); + } else if (!empty($this->alias)) { + $stmt->bindParam(1, $this->alias); + if (!empty($this->domain)) { + $stmt->bindParam(2, $this->domain); + } + } + + Logger::getInstance()->debug("GetOne " . (string)$this); + if ($stmt->execute()) { + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row == null) { + Logger::getInstance()->message("Couldn't find alias matching " . (string)$this); + return false; + } + + $this->id = $row['id']; + $this->account_id = $row['account_id']; + $this->alias = $row['alias']; + $this->domain = $row['domain']; + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } +} + +?> \ No newline at end of file diff --git a/src/objects/device.php b/src/objects/device.php new file mode 100644 index 0000000..3e89ad5 --- /dev/null +++ b/src/objects/device.php @@ -0,0 +1,176 @@ +. +*/ + +class Device { + private $conn; + + public $id; + public $manufacturer; + public $model; + public $status; + public $delay; + public $hardware_echo_canceller; + + public function __construct($db) { + $this->conn = $db; + } + + public function __toString() { + $to_string = "Device: "; + if (!empty($this->id)) { + $to_string = $to_string . "id=" . $this->id . ", "; + } + if (!empty($this->manufacturer)) { + $to_string = $to_string . "manufacturer=" . $this->manufacturer . ", "; + } + if (!empty($this->model)) { + $to_string = $to_string . "model=" . $this->model . ", "; + } + if (!empty($this->status)) { + $to_string = $to_string . "status=" . $this->status . ", "; + } + if (!empty($this->delay)) { + $to_string = $to_string . "delay=" . $this->delay . ", "; + } + if (!empty($this->hardware_echo_canceller)) { + $to_string = $to_string . "hardware_echo_canceller=" . $this->hardware_echo_canceller . ", "; + } + return substr($to_string, 0, -2); + } + + function dropTable() { + $query = "DROP TABLE IF EXISTS " . DEVICES_DB_TABLE; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Dropping table " . DEVICES_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function createTable() { + $query = "CREATE TABLE IF NOT EXISTS " . DEVICES_DB_TABLE . " ( + id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT, + manufacturer VARCHAR(64) NOT NULL, + model VARCHAR(34) NOT NULL, + status VARCHAR(34) NOT NULL, + delay INTEGER(4) NOT NULL DEFAULT 0, + hardware_echo_canceller TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (id))"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Creating table " . DEVICES_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function delete() { + $query = "DELETE FROM " . DEVICES_DB_TABLE . " WHERE id = ?"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $stmt->bindParam(1, $this->id); + + Logger::getInstance()->debug("Deleting " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function create() { + $query = "INSERT INTO " . DEVICES_DB_TABLE . " SET manufacturer=:manufacturer, model=:model, status=:status, + delay=:delay, hardware_echo_canceller=:hardware_echo_canceller"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->manufacturer = htmlspecialchars(strip_tags($this->manufacturer)); + $this->model = htmlspecialchars(strip_tags($this->model)); + $this->status = htmlspecialchars(strip_tags($this->status)); + $this->delay = htmlspecialchars(strip_tags($this->delay)); + $this->hardware_echo_canceller = htmlspecialchars(strip_tags($this->hardware_echo_canceller)); + + $stmt->bindParam(":manufacturer", $this->manufacturer); + $stmt->bindParam(":model", $this->model); + $stmt->bindParam(":status", $this->status); + $stmt->bindParam(":delay", $this->delay); + $stmt->bindParam(":hardware_echo_canceller", $this->hardware_echo_canceller); + + Logger::getInstance()->debug("Creating " . (string)$this); + if ($stmt->execute()) { + $this->id = $this->conn->lastInsertId(); + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function update() { + $query = "UPDATE " . DEVICES_DB_TABLE . " SET manufacturer=:manufacturer, model=:model, status=:status, + delay=:delay, hardware_echo_canceller=:hardware_echo_canceller WHERE id=:id"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $this->manufacturer = htmlspecialchars(strip_tags($this->manufacturer)); + $this->model = htmlspecialchars(strip_tags($this->model)); + $this->status = htmlspecialchars(strip_tags($this->status)); + $this->delay = htmlspecialchars(strip_tags($this->delay)); + $this->hardware_echo_canceller = htmlspecialchars(strip_tags($this->hardware_echo_canceller)); + + $stmt->bindParam(":manufacturer", $this->manufacturer); + $stmt->bindParam(":model", $this->model); + $stmt->bindParam(":status", $this->status); + $stmt->bindParam(":delay", $this->delay); + $stmt->bindParam(":hardware_echo_canceller", $this->hardware_echo_canceller); + $stmt->bindParam(":id", $this->id); + + Logger::getInstance()->debug("Updating " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function getAll() { + $query = "SELECT id, manufacturer, model, status, delay, hardware_echo_canceller FROM " . DEVICES_DB_TABLE; + $stmt = $this->conn->prepare($query); + Logger::getInstance()->debug("GetAll " . (string)$this); + $stmt->execute(); + return $stmt; + } +} + +?> \ No newline at end of file diff --git a/src/objects/password.php b/src/objects/password.php new file mode 100644 index 0000000..65fa127 --- /dev/null +++ b/src/objects/password.php @@ -0,0 +1,207 @@ +. +*/ + +class Password { + private $conn; + + public $id; + public $account_id; + public $password; + public $algorithm; + + public function __construct($db) { + $this->conn = $db; + } + + public function __toString() { + $to_string = "Password: "; + if (!empty($this->id)) { + $to_string = $to_string . "id=" . $this->id . ", "; + } + if (!empty($this->account_id)) { + $to_string = $to_string . "account_id=" . $this->account_id . ", "; + } + if (!empty($this->password)) { + $to_string = $to_string . "password=********"/* . $this->password*/ . ", "; + } + if (!empty($this->algorithm)) { + $to_string = $to_string . "algorithm=" . $this->algorithm . ", "; + } + return substr($to_string, 0, -2); + } + + function dropTable() { + $query = "DROP TABLE IF EXISTS " . ACCOUNTS_ALGO_DB_TABLE; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Dropping table " . ACCOUNTS_ALGO_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function createTable() { + $query = "CREATE TABLE IF NOT EXISTS " . ACCOUNTS_ALGO_DB_TABLE . " ( + id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT, + account_id INTEGER(11) UNSIGNED NOT NULL, + password VARCHAR(255), + algorithm VARCHAR(10), + PRIMARY KEY (id), UNIQUE KEY account (account_id, algorithm))"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Creating table " . ACCOUNTS_ALGO_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function delete() { + $query = "DELETE FROM " . ACCOUNTS_ALGO_DB_TABLE; + + if (!empty($this->id)) { + $query = $query . " WHERE id = ?"; + $this->id = htmlspecialchars(strip_tags($this->id)); + } else if (!empty($this->account_id)) { + $query = $query . " WHERE account_id = ?"; + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + if (!empty($this->algorithm)) { + $query = $query . " AND algorithm = ?"; + $this->algorithm = htmlspecialchars(strip_tags($this->algorithm)); + } + } else { + return false; + } + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->id = htmlspecialchars(strip_tags($this->id)); + if (!empty($this->id)) { + $stmt->bindParam(1, $this->id); + } else if (!empty($this->account_id)) { + $stmt->bindParam(1, $this->account_id); + if (!empty($this->algorithm)) { + $stmt->bindParam(2, $this->algorithm); + } + } + + Logger::getInstance()->debug("Deleting " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function create() { + $query = "INSERT INTO " . ACCOUNTS_ALGO_DB_TABLE . " SET account_id=:account_id, password=:password, algorithm=:algorithm"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + $this->password = htmlspecialchars(strip_tags($this->password)); + $this->algorithm = htmlspecialchars(strip_tags($this->algorithm)); + + $stmt->bindParam(":account_id", $this->account_id); + $stmt->bindParam(":password", $this->password); + $stmt->bindParam(":algorithm", $this->algorithm); + + Logger::getInstance()->debug("Creating " . (string)$this); + if ($stmt->execute()) { + $this->id = $this->conn->lastInsertId(); + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function update() { + $query = "UPDATE " . ACCOUNTS_ALGO_DB_TABLE . " SET account_id=:account_id, password=:password, algorithm=:algorithm WHERE id=:id"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + $this->password = htmlspecialchars(strip_tags($this->password)); + $this->algorithm = htmlspecialchars(strip_tags($this->algorithm)); + + $stmt->bindParam(":account_id", $this->account_id); + $stmt->bindParam(":password", $this->password); + $stmt->bindParam(":algorithm", $this->algorithm); + $stmt->bindParam(":id", $this->id); + + Logger::getInstance()->debug("Updating " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function getAll() { + $query = "SELECT id, password, algorithm FROM " . ACCOUNTS_ALGO_DB_TABLE . " WHERE account_id = ?"; + + $stmt = $this->conn->prepare($query); + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + $stmt->bindParam(1, $this->account_id); + Logger::getInstance()->debug("GetAll " . (string)$this); + $stmt->execute(); + + return $stmt; + } + + function getOne() { + $query = "SELECT id, password, algorithm FROM " . ACCOUNTS_ALGO_DB_TABLE . " WHERE account_id = ? AND algorithm = ? LIMIT 0,1"; + + $stmt = $this->conn->prepare($query); + $this->account_id = htmlspecialchars(strip_tags($this->account_id)); + $this->algorithm = htmlspecialchars(strip_tags($this->algorithm)); + $stmt->bindParam(1, $this->account_id); + $stmt->bindParam(2, $this->algorithm); + + Logger::getInstance()->debug("GetOne " . (string)$this); + if ($stmt->execute()) { + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row == null) { + Logger::getInstance()->message("Couldn't find password matching " . (string)$this); + return false; + } + + $this->id = $row['id']; + $this->password = $row['password']; + $this->algorithm = $row['algorithm']; + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } +} + +?> \ No newline at end of file diff --git a/src/objects/sms.php b/src/objects/sms.php new file mode 100644 index 0000000..f237d62 --- /dev/null +++ b/src/objects/sms.php @@ -0,0 +1,180 @@ +. +*/ + +class SMS { + private $conn; + + public $id; + public $phone; + public $last_sms; + public $count; + + public function __construct($db) { + $this->conn = $db; + } + + public function __toString() { + $to_string = "SMS: "; + if (!empty($this->id)) { + $to_string = $to_string . "id=" . $this->id . ", "; + } + if (!empty($this->phone)) { + $to_string = $to_string . "phone=" . $this->phone . ", "; + } + if (!empty($this->last_sms)) { + $to_string = $to_string . "last_sms=" . $this->last_sms . ", "; + } + if (!empty($this->count)) { + $to_string = $to_string . "count=" . $this->count . ", "; + } + return substr($to_string, 0, -2); + } + + function dropTable() { + $query = "DROP TABLE IF EXISTS " . SMS_DB_TABLE; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Dropping table " . SMS_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function createTable() { + $query = "CREATE TABLE IF NOT EXISTS " . SMS_DB_TABLE . " ( + id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT, + phone VARCHAR(64), + last_sms BIGINT(15) UNSIGNED DEFAULT 0, + count TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (id), UNIQUE KEY phone (phone))"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + Logger::getInstance()->debug("Creating table " . SMS_DB_TABLE); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function delete() { + $query = "DELETE FROM " . $this->table_name . " WHERE id = ?"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $stmt->bindParam(1, $this->id); + + Logger::getInstance()->debug("Deleting " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function create() { + $query = "INSERT INTO " . $this->table_name . " SET phone=:phone, last_sms=:last_sms, count=:count"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->phone = htmlspecialchars(strip_tags($this->phone)); + $this->last_sms = htmlspecialchars(strip_tags($this->last_sms)); + $this->count = htmlspecialchars(strip_tags($this->count)); + + $stmt->bindParam(":phone", $this->phone); + $stmt->bindParam(":last_sms", $this->last_sms); + $stmt->bindParam(":count", $this->count); + + Logger::getInstance()->debug("Creating " . (string)$this); + if ($stmt->execute()) { + $this->id = $this->conn->lastInsertId(); + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function update() { + $query = "UPDATE " . $this->table_name . " SET phone=:phone, last_sms=:last_sms, count=:count WHERE id=:id"; + + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); + $stmt = $this->conn->prepare($query); + + $this->id = htmlspecialchars(strip_tags($this->id)); + $this->phone = htmlspecialchars(strip_tags($this->phone)); + $this->last_sms = htmlspecialchars(strip_tags($this->last_sms)); + $this->count = htmlspecialchars(strip_tags($this->count)); + + $stmt->bindParam(":phone", $this->phone); + $stmt->bindParam(":last_sms", $this->last_sms); + $stmt->bindParam(":count", $this->count); + $stmt->bindParam(":id", $this->id); + + Logger::getInstance()->debug("Updating " . (string)$this); + if ($stmt->execute()) { + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } + + function getAll() { + $query = "SELECT id, phone, last_sms, count FROM " . SMS_DB_TABLE; + $stmt = $this->conn->prepare($query); + Logger::getInstance()->debug("GetAll " . (string)$this); + $stmt->execute(); + return $stmt; + } + + function getOne() { + $query = "SELECT id, phone, last_sms, count FROM " . SMS_DB_TABLE . " WHERE phone = ?"; + $stmt = $this->conn->prepare($query); + $this->phone = htmlspecialchars(strip_tags($this->phone)); + $stmt->bindParam(1, $this->phone); + + Logger::getInstance()->debug("GetOne " . (string)$this); + if ($stmt->execute()) { + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if ($row == null) { + Logger::getInstance()->message("Couldn't find SMS matching " . (string)$this); + return false; + } + + $this->id = $row['id']; + $this->phone = $row['phone']; + $this->last_sms = $row['last_sms']; + $this->count = $row['count']; + return true; + } + Logger::getInstance()->error($stmt->errorInfo()); + return false; + } +} + +?> \ No newline at end of file diff --git a/src/provisioning.php b/src/provisioning.php deleted file mode 100644 index d14b231..0000000 --- a/src/provisioning.php +++ /dev/null @@ -1,26 +0,0 @@ -'; -$xml = $xml . ''; -foreach ($rc_array as $section => $values) { - $xml = $xml . '
'; - foreach ($values as $key => $value) { - if (REMOTE_PROVISIONING_OVERWRITE_ALL) { - $xml = $xml . '' . $value . ''; - } else { - $xml = $xml . '' . $value . ''; - } - } - $xml = $xml . '
'; -} -$xml = $xml . '
'; - -header('Content-type: text/xml'); -echo $xml; - -?> diff --git a/src/sms-sender.php b/src/sms-sender.php deleted file mode 100644 index 9011b91..0000000 --- a/src/sms-sender.php +++ /dev/null @@ -1,25 +0,0 @@ - \r\n"; -} - -?> diff --git a/src/tools/create_tables.php b/src/tools/create_tables.php new file mode 100644 index 0000000..7da8089 --- /dev/null +++ b/src/tools/create_tables.php @@ -0,0 +1,58 @@ +#!/usr/bin/env php + +. +*/ + +include_once __DIR__ . '/../database/database.php'; +include_once __DIR__ . '/../objects/account.php'; +include_once __DIR__ . '/../objects/alias.php'; +include_once __DIR__ . '/../objects/device.php'; +include_once __DIR__ . '/../objects/password.php'; +include_once __DIR__ . '/../objects/sms.php'; + +$database = new Database(); +$db = $database->getConnection(); + +$account = new Account($db); +if (!$account->createTable()) { + Logger::getInstance()->error("Couldn't create account table"); +} + +$alias = new Alias($db); +if (!$alias->createTable()) { + Logger::getInstance()->error("Couldn't create alias table"); +} + +$device = new Device($db); +if (!$device->createTable()) { + Logger::getInstance()->error("Couldn't create device table"); +} + +$password = new Password($db); +if (!$password->createTable()) { + Logger::getInstance()->error("Couldn't create password table"); +} + +$sms = new SMS($db); +if (!$sms->createTable()) { + Logger::getInstance()->error("Couldn't create sms table"); +} + +?> \ No newline at end of file diff --git a/src/utilities.php b/src/utilities.php deleted file mode 100644 index fa75f2b..0000000 --- a/src/utilities.php +++ /dev/null @@ -1,161 +0,0 @@ -= 0 and strpos($hay, $needle, $temp) !== FALSE); -} - -function getIp() { - $ip = $_SERVER['REMOTE_ADDR']; - if (!empty($_SERVER['HTTP_CLIENT_IP'])) { - $ip = $_SERVER['HTTP_CLIENT_IP']; - } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { - $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; - } - return $ip; -} - -// Internationalization - -function get_lang($param) { - if ($param == NULL || $param == "") { - mylog("[WARN] lang parameter wasn't found, use US"); - return 'US'; - } else if (strlen($param) > 2) { - $param = substr($param, 0, 2); - } - return strtoupper($param); -} - -function get_sms_string_for_lang($lang) { - global $SMS_OVH_TEMPLATE; - if (isset($SMS_OVH_TEMPLATE[$lang])) { - return $SMS_OVH_TEMPLATE[$lang]; - } - mylog("[WARN] SMS template not found for lang " . $lang . ", using US template"); - return SMS_OVH_US_TEMPLATE; -} - -// Password - -function hash_password($user, $password, $domain, $algo) { - if(strcmp($algo,"")==0 || strcmp($algo,"MD5")==0) $hashed_password = hash("md5", $user . ":" . $domain . ":" . $password); - if(strcmp($algo,"SHA-256")==0) $hashed_password = hash("sha256", $user . ":" . $domain . ":" . $password); - return $hashed_password; -} - -function generate_password() { - $generated_password = substr(str_shuffle(GENERATED_PASSWORD_CHARACTERS), 0, GENERATED_PASSWORD_LENGTH); - return $generated_password; -} - -function generate_4_digits_code() { - $generated_password = substr(str_shuffle("0123456789"), 0, 4); - return $generated_password; -} - -function get_trial_expiration_date() { - $expiration_date = new DateTime('now +' . TRIAL_DURATION_DAYS . ' days'); - $expiration = $expiration_date->getTimestamp() * 1000; - return $expiration; -} - -function check_parameter($param, $param_name = "username") { - if ($param == NULL || $param == "") { - mylog("[WARN] " . $param_name . " is missing"); - return false; - } - return true; -} - -function get_algo($algo) { - if ($algo == NULL || $algo == "") { - return "MD5"; - } - if (strcmp($algo, "MD5") == 0 || strcmp($algo, "SHA-256") == 0 || strcmp($algo, "clrtxt") == 0) { - return $algo; - } - mylog("[ERROR] Algo " . $algo . " is not supported"); - return NULL; -} - -function get_domain($param) { - if ($param == NULL || $param == "") { - mylog("[WARN] domain parameter wasn't found, use " . SIP_DOMAIN); - $param = SIP_DOMAIN; - } - return $param; -} - -// Email - -function send_email($email, $subject, $text, $html) { - $site = EMAIL_SITE; - $from = EMAIL_FROM_ADDR; - $name = EMAIL_FROM_NAME; - $to = $email; - $from = $name." <".$from.">"; - - $limite = "_----------=_parties_".md5(uniqid (rand())); - - $headers = "Reply-to: ".$from."\n"; - $headers .= "From: ".$from."\n"; - $headers .= "Return-Path: ".$from."\n"; - $headers .= "X-Sender: <".$site.">\n"; - $headers .= "X-Mailer: PHP\n"; - $headers .= "X-auth-smtp-user: ".$from." \n"; - $headers .= "X-abuse-contact: ".$from." \n"; - $headers .= "X-auth-smtp-user: ".$from." \n"; - $headers .= "X-abuse-contact: ".$from." \n"; - $headers .= "Date: ".date("D, j M Y G:i:s O")."\n"; - $headers .= "MIME-Version: 1.0\n"; - $headers .= "Content-Type: multipart/alternative; boundary=\"".$limite."\""; - - $message = ""; - - $message .= "--".$limite."\n"; - $message .= "Content-Type: text/plain; charset=\"utf-8\"\n"; - $message .= "Content-Transfer-Encoding: 8bit\n\n"; - $message .= $text; - - $message .= "\n\n--".$limite."\n"; - $message .= "Content-Type: text/html; charset=\"utf-8\"\n"; - $message .= "Content-Transfer-Encoding: 8bit;\n\n"; - $message .= $html; - - $message .= "\n--".$limite."--"; - - $params = "-f" . EMAIL_FROM_ADDR . " -O DeliveryMode=b"; - $result = mail($email, $subject, $message, $headers, $params); - if (!$result) { - mylog("[ERROR][EMAIL] Email delivery declined !"); - } -} - -function send_email_with_activation_link($email, $key) { - if( !EMAIL_ENABLED ){ - mylog("[WARN] [EMAIL] Emails are disabled"); - return "WARNING_EMAILS_DISABLED"; - } - - $pageURL = 'http'; - if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} - $pageURL .= "://"; - - $link = $pageURL . EMAIL_ACTIVATION_LINK; - $link = str_replace("%key%", $key, $link); - mylog("[EMAIL] Activation link is " . $link); - - $body = str_replace("%link%", $link, EMAIL_ACTIVATION_BODY); - mylog("[EMAIL] Activation body is " . $body); - $body_html = str_replace("%link%", $link, EMAIL_ACTIVATION_BODY_HTML); - mylog("[EMAIL] Activation html body is " . $body_html); - - send_email($email, EMAIL_ACTIVATION_SUBJECT, $body, $body_html); - mylog("[EMAIL] Email sent to email " . $email . " to activate the account"); -} - -?> diff --git a/src/xmlrpc-accounts.php b/src/xmlrpc-accounts.php deleted file mode 100644 index 5017e99..0000000 --- a/src/xmlrpc-accounts.php +++ /dev/null @@ -1,878 +0,0 @@ -= 1; - linphonedb_clean($result); - linphonedb_close($conn); - return $is_existing; -} - -function db_account_is_email_in_use($email) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT count(*) FROM " . ACCOUNTS_DB_TABLE . " WHERE email='" . linphonedb_escape($conn, $email) . "'", $conn); - $row = linphonedb_fetch($result); - $is_in_use = $row[0] >= 1; - linphonedb_clean($result); - linphonedb_close($conn); - return $is_in_use; -} - -function db_account_is_email_or_login_in_use($user_or_email) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT count(*) FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user_or_email) . "' OR email='" . linphonedb_escape($conn, $user_or_email) . "'", $conn); - $row = linphonedb_fetch($result); - $is_in_use = $row[0] >= 1; - linphonedb_clean($result); - linphonedb_close($conn); - return $is_in_use; -} - -function db_account_get_confirmation_key($user, $domain) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT confirmation_key FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user) . "' AND domain='" . linphonedb_escape($conn, $domain) . "'", $conn); - $row = linphonedb_fetch($result); - $key = $row[0]; - linphonedb_clean($result); - linphonedb_close($conn); - return $key; -} - -function db_account_get_password($user, $domain, $algo) { - $conn = linphonedb_connect(); - if(!strcmp($algo,"")) - $algo = "MD5"; - $result = linphonedb_query("SELECT password FROM " . ACCOUNTS_ALGO_DB_TABLE . " WHERE account_id=(SELECT id FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user) . "' AND domain='" . linphonedb_escape($conn, $domain) . "') AND algorithm='" . linphonedb_escape($conn, $algo) . "'", $conn); - $row = linphonedb_fetch($result); - $password = $row[0]; - linphonedb_clean($result); - linphonedb_close($conn); - return $password; -} - -function db_account_get_login_from_login_or_email($user_or_email) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT login FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user_or_email) . "' OR email='" . linphonedb_escape($conn, $user_or_email) . "'", $conn); - $row = linphonedb_fetch($result); - linphonedb_clean($result); - linphonedb_close($conn); - return $row[0]; -} - -function db_account_get_email_from_login_or_email($user_or_email) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT email FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user_or_email) . "' OR email='" . linphonedb_escape($conn, $user_or_email) . "'", $conn); - $row = linphonedb_fetch($result); - linphonedb_clean($result); - linphonedb_close($conn); - return $row[0]; -} - -function db_account_get_logins_from_email($email) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT login FROM " . ACCOUNTS_DB_TABLE . " WHERE email='" . linphonedb_escape($conn, $email) . "'", $conn); - $usernames = array(); - $i = 0; - while ($row = linphonedb_fetch($result)) { - $usernames[$i] = $row[0]; - $i = $i + 1; - } - linphonedb_clean($result); - linphonedb_close($conn); - return $usernames; -} - -function db_get_accounts() { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT login, domain, activated, confirmation_key, ip_address, user_agent FROM " . ACCOUNTS_DB_TABLE, $conn); - $accounts = array(); - $i = 0; - while ($row = linphonedb_fetch($result)) { - $account = array(); - $account['username'] = $row[0]; - $account['domain'] = $row[1]; - $account['activated'] = $row[2]; - $account['activation_code'] = $row[3]; - $account['ip_address'] = $row[4]; - $account['user_agent'] = $row[5]; - $accounts[$i] = $account; - $i = $i + 1; - } - linphonedb_clean($result); - linphonedb_close($conn); - return $accounts; -} - -// XMLRPC methods - -// args == [email] -function xmlrpc_recover_usernames_from_email($method, $args) { - $email = $args[0]; - mylog("[XMLRPC] xmlrpc_recover_usernames_from_email(" . $email . ")"); - - if (!check_parameter($email, "email")) { - return "ERROR_EMAIL_PARAMETER_NOT_FOUND"; - } - - if (db_account_is_email_in_use($email)) { - $usernames = db_account_get_logins_from_email($email); - //TODO: send email - return "OK"; - } else { - mylog("[ERROR] email not found in database"); - return "ERROR_EMAIL_DOESNT_EXIST"; - } -} - -// args = [username or email] -function xmlrpc_send_reset_password_email($method, $args) { - $user_or_email = $args[0]; - mylog("[XMLRPC] xmlrpc_send_reset_password_email(" . $user_or_email . ")"); - - if (!check_parameter($user_or_email, "username or email")) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if (db_account_is_email_or_login_in_use($user_or_email)) { - $user = db_account_get_login_from_login_or_email($user_or_email); - $email = db_account_get_email_from_login_or_email($user_or_email); - //TODO: send email - return "OK"; - } else { - mylog("[ERROR] username or email not found in database"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } -} - -function xmlrpc_send_activation_email($method, $args) { - $user_or_email = $args[0]; - mylog("[XMLRPC]xmlrpc_send_activation_email(" . $user_or_email . ")" ); - - if (!check_parameter($user_or_email, "username or email")) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if (db_account_is_email_or_login_in_use($user_or_email)) { - $user = db_account_get_login_from_login_or_email($user_or_email); - $email = db_account_get_email_from_login_or_email($user_or_email); - $hash = get_hash_from_email($email); - delete_link_in_database($hash); - //TODO: send email - return "OK"; - } else { - mylog("[ERROR] username or email not found in database"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } -} - -// args = [username, old hash, new hash, [domain], [algo]] -function xmlrpc_update_hash($method, $args) { - $user = $args[0]; - $hashed_old_password = $args[1]; - $hashed_new_password = $args[2]; - $domain = get_domain($args[3]); - $algo = get_algo($args[4]); - - mylog("[XMLRPC] xmlrpc_update_hash(" . $user . ", " . $domain . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - if (db_account_is_existing($user, $domain)) { - $db_hashed_password = db_account_get_password($user, $domain, $algo); - if (strcmp($db_hashed_password, $hashed_old_password) != 0) { - mylog("[ERROR] old password doesn't match"); - return "ERROR_PASSWORD_DOESNT_MATCH"; - } else { - db_account_update_password($user, $domain, $hashed_new_password, $algo); - mylog("Password updated successfully"); - return "OK"; - } - } else { - mylog("[ERROR] username not found in database"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } -} - -// args = [username, old password, new password, [domain], [algo]] -function xmlrpc_update_password($method, $args) { - $user = $args[0]; - $domain = get_domain($args[3]); - $algo = get_algo($algo[4]); - - mylog("[XMLRPC] xmlrpc_update_password(" . $user . ", " . $domain . ")"); - - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - $args[1] = hash_password($args[0], $args[1], $algo); - $args[2] = hash_password($args[0], $args[2], $algo); - - return xmlrpc_update_hash("xmlrpc_update_password", $args); -} - -// args = [username, password, new email, [domain], [algo]] -function xmlrpc_update_email($method, $args) { - $user = $args[0]; - $password = $args[1]; - $new_email = $args[2]; - $domain = get_domain($args[3]); - $algo = get_algo($args[4]); - - mylog("[XMLRPC] xmlrpc_update_email(" . $user . ", " . $domain . ", " . $new_email . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - if (db_account_is_existing($user, $domain)) { - $db_hashed_password = db_account_get_password($user, $domain, $algo); - $hashed_old_password = hash_password($user, $password, $domain, $algo); - if (strcmp($db_hashed_password, $hashed_old_password) != 0 and strcmp($db_hashed_password, $password) != 0) { - mylog("[ERROR] old password doesn't match"); - return "ERROR_PASSWORD_DOESNT_MATCH"; - } else { - $old_email = db_account_get_email_from_login_or_email($user); - if (strcmp($old_email, $new_email) == 0) { - mylog("New email same as previous one"); - return "ERROR_EMAIL_NEW_SAME_AS_OLD"; - } else { - if (db_account_is_email_in_use($new_email) && !ALLOW_SAME_EMAILS_ON_MULTILPLE_ACCOUNTS) { - return "ERROR_EMAIL_ALREADY_IN_USE"; - } else { - db_account_update_email($user, $domain, $new_email); - mylog("Email updated successfully"); - return "OK"; - } - } - } - } else { - mylog("[ERROR] username not found in database"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } -} - -// args = [username, [domain]] -function xmlrpc_is_account_activated($method, $args) { - $user = $args[0]; - $domain = get_domain($args[1]); - mylog("[XMLRPC] xmlrpc_is_account_activated(" . $user . ", " . $domain . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if (db_account_is_activated($user, $domain)) { - mylog("User account " . $user . " / " . $domain . " is activated"); - return "OK"; - } else { - if (db_account_is_existing($user, $domain)) { - return "NOK"; - } else { - mylog("[ERROR] User account " . $user . " / " . $domain . " doesn't exist"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } - } -} - -// args = [username, [domain]] -function xmlrpc_is_account_used($method, $args) { - $user = $args[0]; - $domain = get_domain($args[1]); - mylog("[XMLRPC] xmlrpc_is_account_used(" . $user . ", " . $domain . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if (db_account_is_existing($user, $domain)) { - mylog("[ERROR] User account " . $user . " / " . $domain . " exists"); - return "OK"; - } else { - mylog("[ERROR] User account " . $user . " / " . $domain . " doesn't exist"); - return "NOK"; - } -} - -// args = [email] -function xmlrpc_is_email_used($method, $args) { - $email = $args[0]; - mylog("[XMLRPC] xmlrpc_is_email_used(" . $email . ")"); - - if (!check_parameter($email, "email")) { - return "ERROR_EMAIL_PARAMETER_NOT_FOUND"; - } - - if (db_account_is_email_in_use($email)) { - mylog("[ERROR] User email " . $email . " exists"); - return "OK"; - } else { - mylog("[ERROR] User email " . $email . " doesn't exist"); - return "ERROR_EMAIL_DOESNT_EXIST"; - } -} - -// args = [username, key, [domain], [algo]] -function xmlrpc_activate_email_account($method, $args) { - $user = $args[0]; - $key = $args[1]; - $domain = get_domain($args[2]); - $algo = get_algo($args[3]); - - mylog("[XMLRPC] xmlrpc_activate_account(" . $user . ", " . $domain . ", " . $key . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - if (!db_account_is_existing($user, $domain)) { - mylog("[ERROR] User account " . $user . " / " . $domain . " doesn't exist"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } else if (db_account_is_activated($user, $domain)) { - mylog("[ERROR] User account " . $user . " / " . $domain . " is already activated"); - return "ERROR_ACCOUNT_ALREADY_ACTIVATED"; - } - - $key_db = db_account_get_confirmation_key($user, $domain); - if (strcmp($key, "ERROR") == 0 or strcmp($key, $key_db) != 0) { - if (strcmp($key_db, "ERROR") != 0) { - db_account_update_confirmation_key($user, $domain, "ERROR"); - } - mylog("[ERROR] Key doesn't match"); - return "ERROR_KEY_DOESNT_MATCH"; - } - - $expiration = NULL; - db_account_activate($user, $domain); - if (USE_IN_APP_PURCHASES) { - $expiration = get_trial_expiration_date(); - db_inapp_add_account($user, $domain, $expiration); - } - - if (CUSTOM_HOOKS) { - hook_on_account_activated($user, $domain, $expiration); - } - - $ha1 = db_account_get_password($user, $domain, $algo); - return $ha1; -} - -// args = [phone, username, key, [domain], [algo]] -function xmlrpc_activate_phone_account($method, $args) { - $phone = $args[0]; - $user = $args[1]; - $key = $args[2]; - $domain = get_domain($args[3]); - $algo = get_algo($args[4]); - - mylog("[XMLRPC] xmlrpc_activate_phone_account(" . $user . ", " . $domain . ", " . $key . ")"); - - if (!check_parameter($phone, "phone")) { - return "ERROR_PHONE_PARAMETER_NOT_FOUND"; - } else if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } else if (!startswith($phone, "+")) { - mylog("[ERROR] Phone doesn't start by +"); - return "ERROR_PHONE_ISNT_E164"; - } - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - if (!db_account_is_existing($user, $domain)) { - mylog("[ERROR] User account " . $user . " / " . $domain . " doesn't exist"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } - - $key_db = db_account_get_confirmation_key($user, $domain); - if (strcmp($key, "ERROR") == 0 or strcmp($key, $key_db) != 0) { - if (strcmp($key_db, "ERROR") != 0) { - db_account_update_confirmation_key($user, $domain, "ERROR"); - } - mylog("[ERROR] Key doesn't match"); - return "ERROR_KEY_DOESNT_MATCH"; - } - - // If this is a recovery, account is already activated, don't go through the following again - if (!db_account_is_activated($user, $domain)) { - $expiration = NULL; - db_account_activate($user, $domain); - db_alias_add($phone, $user, $domain); - if (USE_IN_APP_PURCHASES) { - $expiration = get_trial_expiration_date(); - db_inapp_add_account($user, $domain, $expiration); - } - - if (CUSTOM_HOOKS) { - hook_on_account_activated($user, $domain, $expiration); - } - } - - $ha1 = db_account_get_password($user, $domain, $algo); - return $ha1; -} - -// args = [username, email, [hash], useragent, [domain], [algo]] -function xmlrpc_create_email_account($method, $args) { - $user = $args[0]; - $email = $args[1]; - $domain = get_domain($args[4]); - $algo = get_algo($args[5]); - - mylog("[XMLRPC] xmlrpc_create_account(" . $user . ", " . $domain . ", " . $email . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } else if (db_account_is_existing($user, $domain)) { - mylog("[XMLRPC] account already in use"); - return "ERROR_ACCOUNT_ALREADY_IN_USE"; - } - - if (!check_parameter($email, "email")) { - return "ERROR_EMAIL_PARAMETER_NOT_FOUND"; - } else if (db_account_is_email_in_use($email) && !ALLOW_SAME_EMAILS_ON_MULTILPLE_ACCOUNTS) { - mylog("[XMLRPC] email already in use"); - return "ERROR_EMAIL_ALREADY_IN_USE"; - } - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - if (GENERATE_PASSWORD_ENABLED) { - $hashed_password = hash_password($user, generate_password(), $domain, $algo); - } else { - $hashed_password = $args[2]; - } - - $user_agent = $args[3]; - $key = uniqid(); - - mylog("[XMLRPC] Create account " . $user); - db_account_create($user, $hashed_password, $domain, $email, $key, getIp(), $user_agent, $algo); - - if (CUSTOM_HOOKS) { - hook_on_account_created($user, $domain, $hashed_password, $email); - } - - if (SEND_ACTIVATION_EMAIL) { - send_email_with_activation_link($email, $key); - } else if (AUTO_ACTIVATE_ACCOUNT) { - db_account_activate($user, $domain); - if (USE_IN_APP_PURCHASES) { - $expiration = get_trial_expiration_date(); - db_inapp_add_account($user, $domain, $expiration); - } - } - - return "OK"; -} - -// args = [phone, [username], [password], useragent, [domain], [lang], [algo]] -function xmlrpc_create_phone_account($method, $args) { - $phone = $args[0]; - $user = $args[1]; - $hashed_password = $args[2]; - $domain = get_domain($args[4]); - $lang = get_lang($args[5]); - $algo = get_algo($args[6]); - - mylog("[XMLRPC] xmlrpc_create_phone_account(" . $phone . ", " . $domain . ", " . $user . ")"); - - if (!check_parameter($phone, "phone")) { - return "ERROR_PHONE_PARAMETER_NOT_FOUND"; - } else if (!startswith($phone, "+")) { - mylog("[ERROR] Phone doesn't start by +"); - return "ERROR_PHONE_ISNT_E164"; - } - - if (!check_parameter($user)) { - $user = $phone; - } - - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - $recover_params = array( - 0 => $phone, - 1 => $domain, - 2 => $lang, - ); - if (db_account_is_existing($user, $domain)) { - if (RECOVER_ACCOUNT_IF_EXISTS) { - $recovered_user = xmlrpc_recover_phone_account($method, $recover_params); - if ($recovered_user == $user) return "OK"; - return "ERROR_CANT_RECOVER_ACCOUNT"; - } else { - return "ERROR_ACCOUNT_ALREADY_IN_USE"; - } - } else if (db_alias_is_in_use($phone, $domain)) { - if (RECOVER_ACCOUNT_IF_EXISTS) { - $recovered_user = xmlrpc_recover_phone_account($method, $recover_params); - if ($recovered_user == $user) return "OK"; - return "ERROR_CANT_RECOVER_ACCOUNT"; - } else { - return "ERROR_ALIAS_ALREADY_IN_USE"; - } - } - - $password = $hashed_password; - if (!check_parameter($hashed_password, "hashed password")) { - $password = generate_password(); - $hashed_password = hash_password($user, $password, $domain, $algo); - } - - $user_agent = $args[3]; - $key = generate_4_digits_code(); - - db_account_create($user, $hashed_password, $domain, NULL, $key, getIp(), $user_agent, $algo); - - if (CUSTOM_HOOKS) { - hook_on_account_created($user, $domain, $hashed_password, NULL); - } - - if (SEND_ACTIVATION_SMS) { - if (!SMS_API_ENABLED) { - // This is a hack to allow testing without sending SMS - return "OK"; - } - $ok = send_sms($phone, $key, $lang); - return $ok; - } else if (AUTO_ACTIVATE_ACCOUNT) { - db_account_activate($user, $domain); - if (USE_IN_APP_PURCHASES) { - $expiration = get_trial_expiration_date(); - db_inapp_add_account($user, $domain, $expiration); - } - } - - return "OK"; -} - -// args = [user, pwd, [domain], [algo]] -// /!\ This method must be used for tests purposes only /!\ -function xmlrpc_get_confirmation_key($method, $args) { - $user = $args[0]; - $password = $args[1]; - $domain = get_domain($args[2]); - $algo = get_algo($args[3]); - - mylog("[XMLRPC] xmlrpc_get_confirmation_key(" . $user . ", " . $domain . ")"); - - if (!check_parameter($user)) { - mylog("[ERROR] Username parameter not found"); - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } else if (!ALLOW_TEST_ACCOUNTS) { - mylog("[ERROR] Non test account unauthorized"); - return "ERROR_NON_TEST_ACCOUNTS_UNAUTHORIZED"; - } - - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - if (!db_account_is_existing($user, $domain)) { - mylog("[ERROR] User account " . $user . " / " . $domain . " doesn't exist"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } else { - $hashed_password = hash_password($user, $password, $domain, $algo); - $db_hashed_password = db_account_get_password($user, $domain, $algo); - if (strcmp($hashed_password, $db_hashed_password) != 0 and strcmp($password, $db_hashed_password) != 0) { - mylog("[ERROR] Password doesn't match"); - return "ERROR_PASSWORD_DOESNT_MATCH"; - } - } - - $key = db_account_get_confirmation_key($user, $domain); - mylog("[XMLRPC] returning key = " . $key); - return $key; -} - -// args = [user, pwd, [domain], [algo]] -// /!\ This method must be used for tests purposes only /!\ -function xmlrpc_delete_account($method, $args) { - $user = $args[0]; - $password = $args[1]; - $domain = get_domain($args[2]); - $algo = get_algo($args[3]); - - mylog("[XMLRPC] xmlrpc_delete_account(" . $user . ", " . $domain . ")"); - if ($algo == NULL) { - return "ERROR_ALGO_NOT_SUPPORTED"; - } - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } else if (!ALLOW_TEST_ACCOUNTS) { - return "ERROR_NON_TEST_ACCOUNTS_UNAUTHORIZED"; - } - - if (!db_account_is_existing($user, $domain)) { - mylog("[ERROR] User account " . $user . " / " . $domain . " doesn't exist"); - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } else { - $hashed_password = hash_password($user, $password, $domain, $algo); - $db_hashed_password = db_account_get_password($user, $domain, $algo); - if (strcmp($hashed_password, $db_hashed_password) != 0 and strcmp($password, $db_hashed_password) != 0) { - mylog("[ERROR] Password doesn't match"); - return "ERROR_PASSWORD_DOESNT_MATCH"; - } - } - db_alias_delete($user, $domain); - db_account_delete($user, $domain); - return "OK"; -} - -// args = [phone, [domain]] -function xmlrpc_is_phone_number_used($method, $args) { - $phone = $args[0]; - $domain = get_domain($args[1]); - - mylog("[XMLRPC] xmlrpc_is_phone_number_used(" . $phone . ")"); - - if (!check_parameter($phone, "phone")) { - return "ERROR_PHONE_PARAMETER_NOT_FOUND"; - } else if (!startswith($phone, "+")) { - return "ERROR_PHONE_ISNT_E164"; - } - - if (db_account_is_existing($phone, $domain)) { - return "OK_ACCOUNT"; - } else if (db_alias_is_in_use($phone, $domain)) { - return "OK_ALIAS"; - } - - return "NOK"; -} - -// args = [username, [domain]] -function xmlrpc_get_phone_number_for_account($method, $args) { - $user = $args[0]; - $domain = get_domain($args[1]); - - mylog("[XMLRPC] xmlrpc_get_phone_number_for_account(" . $user . ")"); - - if (!check_parameter($user)) { - return "ERROR_USERNAME_PARAMETER_NOT_FOUND"; - } - - if (!db_account_is_existing($user, $domain)) { - if (db_alias_is_in_use($user, $domain)) { - return $user; - } - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } - - $phone = db_alias_get_reverse($user, $domain); - if ($phone == NULL) { - return "ERROR_ALIAS_DOESNT_EXIST"; - } - - if (RECOVER_ACCOUNT_IF_EXISTS) { - return "ERROR_ACCOUNT_DOESNT_EXIST"; - } - - return $phone; -} - -// args = [phone, [domain], [lang]] -function xmlrpc_recover_phone_account($method, $args) { - $phone = $args[0]; - $domain = get_domain($args[1]); - $lang = get_lang($args[2]); - - mylog("[XMLRPC] xmlrpc_recover_phone_account(" . $phone . ")"); - - if (!check_parameter($phone, "phone")) { - return "ERROR_PHONE_PARAMETER_NOT_FOUND"; - } else if (!startswith($phone, "+")) { - return "ERROR_PHONE_ISNT_E164"; - } - - $user = NULL; - if (db_alias_is_in_use($phone, $domain)) { - $user = db_alias_get($phone, $domain); - } - if ($user != NULL || db_account_is_existing($phone, $domain)) { - if ($user == NULL) { - $user = $phone; - } - if (SEND_ACTIVATION_SMS) { - $key = generate_4_digits_code(); - db_account_update_confirmation_key($user, $domain, $key); - - $ok = send_sms($phone, $key, $lang); - if ($ok != "OK") { - return $ok; - } - } - return $user; - } - return "ERROR_ACCOUNT_DOESNT_EXIST"; -} - -function xmlrpc_accounts_register_methods($server) { - //TODO FIXME remove this methods later as it's a security risk - // /!\ This methods must be used for tests purposes only /!\ - xmlrpc_server_register_method($server, 'get_confirmation_key', 'xmlrpc_get_confirmation_key');// args = [user, pwd, [domain]], return confirmation_key - xmlrpc_server_register_method($server, 'delete_account', 'xmlrpc_delete_account');// args = [user, pwd, [domain]] - - xmlrpc_server_register_method($server, 'is_account_used', 'xmlrpc_is_account_used');// args = [username, [domain]], return "OK" or "NOK" - xmlrpc_server_register_method($server, 'is_account_activated', 'xmlrpc_is_account_activated');// args = [username, [domain]], return "OK" or "NOK" - xmlrpc_server_register_method($server, 'is_phone_number_used', 'xmlrpc_is_phone_number_used');// args = [phone], return "OK_ACCOUNT", "OK_ALIAS" or "NOK" - xmlrpc_server_register_method($server, 'activate_phone_account', 'xmlrpc_activate_phone_account');// args = [phone, username, key, [domain]], return ha1_password - xmlrpc_server_register_method($server, 'create_phone_account', 'xmlrpc_create_phone_account');// args = [phone, [username], [password], useragent, [domain], [lang]], return "OK" - xmlrpc_server_register_method($server, 'activate_email_account', 'xmlrpc_activate_email_account');// args = [username, key, [domain]], return ha1_password - xmlrpc_server_register_method($server, 'create_email_account', 'xmlrpc_create_email_account');// args = [username, email, [hash], useragent, [domain]], return "OK" - xmlrpc_server_register_method($server, 'get_phone_number_for_account', 'xmlrpc_get_phone_number_for_account');// args = [username, [domain]], return a phone number or an error - xmlrpc_server_register_method($server, 'recover_phone_account', 'xmlrpc_recover_phone_account');// args = [phone, [domain], [lang]], return username - - xmlrpc_server_register_method($server, 'update_password', 'xmlrpc_update_password');// args = [username, old password, new password, [domain]], return "OK" - xmlrpc_server_register_method($server, 'update_hash', 'xmlrpc_update_hash');// args = [username, old hash, new hash, [domain]], return "OK" - xmlrpc_server_register_method($server, 'update_email', 'xmlrpc_update_email');// args = [username, password, new email, [domain]], return "OK" -} - -?> diff --git a/src/xmlrpc-aliases.php b/src/xmlrpc-aliases.php deleted file mode 100644 index 237587e..0000000 --- a/src/xmlrpc-aliases.php +++ /dev/null @@ -1,203 +0,0 @@ - diff --git a/src/xmlrpc-compatibility.php b/src/xmlrpc-compatibility.php deleted file mode 100644 index 1accfaf..0000000 --- a/src/xmlrpc-compatibility.php +++ /dev/null @@ -1,75 +0,0 @@ - \ No newline at end of file diff --git a/src/xmlrpc-devices.php b/src/xmlrpc-devices.php deleted file mode 100644 index f85d9ef..0000000 --- a/src/xmlrpc-devices.php +++ /dev/null @@ -1,52 +0,0 @@ - \ No newline at end of file diff --git a/src/xmlrpc-sms.php b/src/xmlrpc-sms.php deleted file mode 100644 index 8ae7e9b..0000000 --- a/src/xmlrpc-sms.php +++ /dev/null @@ -1,208 +0,0 @@ -= 1; - linphonedb_clean($result); - linphonedb_close($conn); - return $already_sent; -} - -function db_insert_sms($phone, $time) { - $conn = linphonedb_connect(); - $result = linphonedb_query("INSERT INTO " . SMS_DB_TABLE . "(phone, last_sms, count) VALUES('" . linphonedb_escape($conn, $phone) . "', " . linphonedb_escape($conn, $time) . ", 1)", $conn); - linphonedb_clean($result); - linphonedb_close($conn); -} - -function db_get_sms_count($phone) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT count FROM " . SMS_DB_TABLE . " WHERE phone='" . linphonedb_escape($conn, $phone) . "'", $conn); - $row = linphonedb_fetch($result); - $sms_count = $row[0]; - linphonedb_clean($result); - linphonedb_close($conn); - return $sms_count; -} - -function db_get_last_sms($phone) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT last_sms FROM " . SMS_DB_TABLE . " WHERE phone='" . linphonedb_escape($conn, $phone) . "'", $conn); - $row = linphonedb_fetch($result); - $last_sms = $row[0]; - linphonedb_clean($result); - linphonedb_close($conn); - return $last_sms; -} - -function db_update_sms($phone, $time, $count) { - $conn = linphonedb_connect(); - $result = linphonedb_query("UPDATE " . SMS_DB_TABLE . " SET last_sms=" . linphonedb_escape($conn, $time) . ", count=" . linphonedb_escape($conn, $count) . " WHERE phone='" . linphonedb_escape($conn, $phone) . "'", $conn); - linphonedb_clean($result); - linphonedb_close($conn); -} - -function db_delete_sms($phone) { - $conn = linphonedb_connect(); - $result = linphonedb_query("DELETE FROM " . SMS_DB_TABLE . " WHERE phone='" . linphonedb_escape($conn, $phone) . "'", $conn); - linphonedb_clean($result); - linphonedb_close($conn); -} - -function send_sms_ovh($phone, $key, $lang) { - if (!SMS_API_ENABLED) { - mylog("[WARN][SMS] SMS API disabled"); - return "WARNING_SMS_API_DISABLED"; - } - - $sms = new SmsApi(SMS_OVH_API_KEY, SMS_OVH_API_SECRET, SMS_OVH_ENDPOINT, SMS_OVH_CONSUMER_KEY); - $accounts = $sms->getAccounts(); - $sms->setAccount($accounts[0]); - if (SMS_USE_SENDER) { - $senders = $sms->getSenders(); - - /* The account must be validated in the OVH interface and by OVH itself */ - if (count($senders) == 0) { - mylog("[WARN][SMS] No sender found, creating one " . SMS_OVH_SENDER . " / " . SMS_OVH_REASON . " : " . SMS_OVH_DESC); - $sms->addSender(SMS_OVH_SENDER, SMS_OVH_REASON, SMS_OVH_DESC); - $senders = $sms->getSenders(); - } - } - - $message = $sms->createMessage(); - if (SMS_USE_SENDER && count($senders) > 0) { - foreach ($senders as $sender) { - if ($sender == SMS_OVH_SENDER) { - if ($sms->checkSender($sender)) { - // Check if sender exists and is valid, otherwise it will create an exception and sms won't be sent - mylog("[SMS] Found valid sender " . $sender . ", using it"); - $message->setSender($sender); - break; - } else { - mylog("[ERROR][SMS] Found sender " . $sender . " but it is not valid"); - } - } - } - } - $message->addReceiver($phone); - $message->setIsMarketing(FALSE); - - $text = get_sms_string_for_lang($lang); - $text = str_replace("#CODE#", $key, $text); - $result = $message->send($text); - - $credits_removed = $result['totalCreditsRemoved']; - mylog("[SMS] " . $credits_removed . " credit removed"); - $invalid_receiver = $result['invalidReceivers']; - $valid_receiver = $result['validReceivers']; - if (count($invalid_receiver) > 0) { - mylog("[ERROR][SMS] phone number " . $phone . " seems invalid"); - } else if (count($valid_receiver) > 0) { - mylog("[SMS] " . $text . " sent to " . $phone); - } else { - mylog("[WARN][SMS] Both valid and invalid receiver lists are empty..."); - } -} - -function send_sms_legacy($phone, $password) { - if (!SMS_API_ENABLED) { - mylog("[WARN][SMS] SMS API disabled"); - return "WARNING_SMS_API_DISABLED"; - } - - $url = SMS_API_URL; - $ch = curl_init($url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_FAILONERROR, false); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); - curl_setopt($ch, CURLOPT_USERPWD, SMS_API_USERNAME . ":" . SMS_API_PASSWORD); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - 'Content-Type: application/x-www-form-urlencoded' - )); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array( - 'mobile' => $phone, - 'password' => $password, - ))); - $result = curl_exec($ch); - mylog("[SMS] SMS confirmation sent to " . $phone . " using password " . $password . ", request result is " . $result); - curl_close($ch); -} - -function send_sms($phone, $key, $lang, $password) { - if (!SMS_API_ENABLED) { - mylog("[WARN][SMS] SMS API disabled"); - return "WARNING_SMS_API_DISABLED"; - } - - if (startswith($phone, TESTS_PHONE_PREFIX)) { - mylog("[ERROR][SMS] Not sending sms to fake number used for tests purposes: " . $phone); - return "ERROR_NON_TEST_ACCOUNTS_UNAUTHORIZED"; - } - - $now_date = new DateTime('now'); - $now = $now_date->getTimestamp() * 1000; - - if (db_has_sms_already_been_sent_to($phone)) { - $count = db_get_sms_count($phone); - $time = db_get_last_sms($phone); - $diff = $now - $time; - if ($count >= SMS_COUNT_LIMIT_IN_PERIOD and $diff < SMS_TIME_PERIOD) { - mylog("[ERROR][SMS] Last sms was sent at " . $time . ", time elapsed since then is " . $diff . "ms which is less than the configured time period " . SMS_TIME_PERIOD); - return "ERROR_MAX_SMS_EXCEEDED"; - } else if ($diff >= SMS_TIME_PERIOD) { - db_update_sms($phone, $now, 1); - } else { - $count = $count + 1; - db_update_sms($phone, $now, $count); - } - } else { - db_insert_sms($phone, $now); - } - - - if (SMS_OVH_API_KEY != NULL && SMS_OVH_API_KEY != "" && SMS_OVH_API_SECRET != NULL && SMS_OVH_API_SECRET != "" && SMS_OVH_CONSUMER_KEY != NULL && SMS_OVH_CONSUMER_KEY != "" && SMS_OVH_ENDPOINT != NULL && SMS_OVH_ENDPOINT != "") { - try { - send_sms_ovh($phone, $key, $lang); - return "OK"; - } catch (Exception $e) { - mylog("[ERROR][OVH-SMS] Exception: " . $e->getMessage()); - } - } else if (SMS_API_URL != NULL && SMS_API_URL != "" && SMS_API_USERNAME != NULL && SMS_API_USERNAME != "" && SMS_API_PASSWORD != NULL && SMS_API_PASSWORD != "") { - send_sms_legacy($phone, $password); - return "OK"; - } else { - mylog("[ERROR][SMS] No SMS API configured, discarding sms..."); - return "OK"; - } - return "ERROR_CANT_SEND_SMS"; -} - -?> diff --git a/src/xmlrpc.conf b/src/xmlrpc.conf deleted file mode 100644 index 75f045a..0000000 --- a/src/xmlrpc.conf +++ /dev/null @@ -1,488 +0,0 @@ -?;:[]{}\| - */ -define("GENERATED_PASSWORD_CHARACTERS", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789``-=~!@#$%^&*()_+,./<>?;:[]{}\|"); - -/* - * The length of the passwords that will be generated. - * - * Default value: 8 - */ -define("GENERATED_PASSWORD_LENGTH", 8); - -/* - * If set to True, a created account will automatically be activated and it's expiration date set to now + TRIAL_DURATION_DAYS, - * otherwise expiration date for trial will be set when account is activated via a different xml rpc call. - */ -define('AUTO_ACTIVATE_ACCOUNT', False); - -/* - * If set to True, a created account will be flagged as trial with an expiration date set in TRIAL_DURATION_DAYS days in the future. - */ -define ('USE_IN_APP_PURCHASES', False); - -/* - * This value determines the number of days for trial starting when the account will be activated. - * - * Default value: 365 - */ -define('TRIAL_DURATION_DAYS', 365); - -/* - * This values sets the default timezone to use when computing the expiration dates when using inapp purchases - * - * Default value: 'Europe/Paris' - */ -define('DEFAULT_TIMEZONE', 'Europe/Paris'); - -/* - * Send an email to activate the account when it is created. - */ -define('SEND_ACTIVATION_EMAIL', True); - -/* - * Send a sms to activate the phone account when it is created. - */ -define('SEND_ACTIVATION_SMS', True); - -/* - * If false, creating an account with an email that is already used for another account will trigger an error - */ -define('ALLOW_SAME_EMAILS_ON_MULTILPLE_ACCOUNTS', True); - -/* - * If true, when an account creation request is received for an existing number, assumes recover procedure - */ -define('RECOVER_ACCOUNT_IF_EXISTS', False); - -/* ### Logs configuration ### */ - -/* - * Whever or not to log each function called. - * Passwords are never logged. - * - * Default value: True - */ -define("LOGS_ENABLED", True); - -/* - * The file in which to log calls. - * - * Default value: "/var/opt/belledonne-communications/log/account-manager.log" - */ -define("LOG_FILE", "/var/opt/belledonne-communications/log/account-manager.log"); - -/* ### Database configuration ### */ - -/* - * Whether or not use use persistent connections. - * - * Default value: False - */ -define("USE_PERSISTENT_CONNECTIONS", False); - -/* - * The host on which the database is located. - * - * Default value: localhost - */ -define("DB_HOST", "localhost"); - -/* - * The database username. - * - * Default value: flexisip - */ -define("DB_USER", "flexisip"); - -/* - * The database user's password. - * - * Default value: - */ -define("DB_PASSWORD", ""); - -/* - * The name of the database. - * - * Default value: flexisip - */ -define("DB_NAME", "flexisip"); - -/* - * The name of the accounts table. - * - * Default value: accounts - */ -define("ACCOUNTS_DB_TABLE", "accounts"); - -/* - * The name of the accounts_algo table. - * - * Default value: accounts_algo - */ -define("ACCOUNTS_ALGO_DB_TABLE", "accounts_algo"); - -/* - * The name of the inapp table. - * It is used to store informations about in-app purchases, accounts expiration, etc... - * - * Default value: inapp_purchases - */ -define("INAPP_DB_TABLE", "inapp_purchases"); - -/* - * The name of the aliases table. - * It is used to store links between an alias (phone number, facebook id, google email, ...) and a SIP address - * - * Default value: aliases - */ -define("ALIAS_DB_TABLE", "aliases"); - -/* - * The name of the devices table. - * It is used to store hardware information about devices running linphone - * - * Default value: devices - */ -define("DEVICES_DB_TABLE", "devices"); - -/* - * The name of the sms table. - * It is used to keep track of sent SMS - * - * Default value: sms - */ -define("SMS_DB_TABLE", "sms"); - -/* - * The delay in minutes before test account expiration. - * It is used to delete old test accounts from database; - * - * Default value: 180 - */ -define("EXPIRATION_DELAY", 180); - -/* ### Apple/ioS configuration ### */ - -/* - * The URL to use to validate an Apple in app purchase receipts. - * - * Default value: https://buy.itunes.apple.com/verifyReceipt - */ -define("APPLE_URL", "https://buy.itunes.apple.com/verifyReceipt"); - -/* - * The URL to use to validate an Apple in app purchase receipts while app is in development. - * - * Default value: https://buy.itunes.apple.com/verifyReceipt - */ -define("APPLE_SANDBOX_URL", "https://sandbox.itunes.apple.com/verifyReceipt"); - -/* - * The shared secret for your application. - * Used to validate in app purchase receipts. - * - * Default value: - */ -define("APPLE_SECRET", ""); - -/* ### Google/Android configuration ### */ - -/* - * The package name of your Android application. - * Used to validate in app purchase receipts. - * - * Default value: org.linphone - */ -define("ANDROID_PACKAGE", "org.linphone"); - -/* - * The path to the public key generated by the Android Play Store. - * See the documentation to know how to get it. - * - * Default value: google.pem - */ -define("ANDROID_PUB_KEY_PATH", "google.pem"); - -/* - * The URL to use to get the authentication token to make calls to Google API server. - * Used to validate in app purchase receipts. - * - * Default value: https://accounts.google.com/o/oauth2/token - */ -define("GOOGLE_API_OAUTH_URL", "https://accounts.google.com/o/oauth2/token"); - -/* - * The project ID with the access to the Android Developer Console API - * Used to validate in app purchase receipts. - * - * Default value: - */ -define("GOOGLE_PROJECT_ID", ""); - -/* - * The previous project ID's password - * Used to validate in app purchase receipts. - * - * Default value: - */ -define("GOOGLE_PROJECT_PASSWORD", ""); - -/* - * The refresh token generated by the Google Developer server. - * See documentation to know how to get it. - * Used to validate in app purchase receipts. - * - * Default value: - */ -define("GOOGLE_PROJECT_REFRESH_TOKEN", ""); - -/* ### Email configuration ### */ - -/* - * Whever or not enable the send email feature. - * Used to send link to generate random password if user forgot it, or the newly generated email once the link has been clicked. - * - * Default value: False - */ -define("EMAIL_ENABLED", False); - -/* - * The website address to display in the email header. - * - * Default value: https://linphone.org - */ -define("EMAIL_SITE", "https://linphone.org"); - -/* - * The link to open when click on activation - * - * Default value: www.linphone.org - */ -define("EMAIL_ACTIVATION_LINK", "www.linphone.org"); - -/* - * The FROM address to set in the email header. - * - * Default value: no.reply@linphone.org - */ -define("EMAIL_FROM_ADDR", "no.reply@linphone.org"); - -/* - * The FROM display name to set in the email header. - * - * Default value: No reply at Linphone.org - */ -define("EMAIL_FROM_NAME", "No reply at Linphone.org"); - -/* - * The subject of the activation account email. - */ -define("EMAIL_ACTIVATION_SUBJECT", "Start your sip.linphone.org service"); - -/* - * The body (as text) of the activation account email. - */ -define("EMAIL_ACTIVATION_BODY", "Hello,\nActivation pending for using your Linphone account.\nPlease use the link bellow to activate your account :\n\n%link%\n\nRegards,\nThe Linphone team.\n"); - -/* - * The body (as html) of the activation account email. - */ -define("EMAIL_ACTIVATION_BODY_HTML", 'Start your sip.linphone.org service

Hello,

Activation pending for using your Linphone account.
Please use the link bellow to activate your account :

%link%

 

Regards,
The Linphone team.

'); - - -/* ### SMS API configuration ### */ - -/* - * Whever or not enable the send SMS feature. - * Used to verify phone number when used as SIP username. - * - * Default value: False - */ -define("SMS_API_ENABLED", False); - -/* - * The application key for OVH SMS platform - * - * Default value: - */ -define("SMS_OVH_API_KEY", ""); - -/* - * The application secret for OVH SMS platform - * - * Default value: - */ -define("SMS_OVH_API_SECRET", ""); - -/* - * The consumer key for OVH SMS platform - * - * Default value: - */ -define("SMS_OVH_CONSUMER_KEY", ""); - -/* - * The sender alias for OVH SMS - * - * Default value: "Linphone" - */ -define("SMS_OVH_SENDER", "Linphone"); - -/* - * Whever or not to use a sender to send the SMS. - * When using sender you can customize the name of the sender, otherwise it will be a phone number. - * To disable for clients using our own OVH SMS account. - * - * Default value: True - */ -define("SMS_USE_SENDER", True); - -/* - * The sender reason for OVH SMS - * - * Default value: "created Linphone SMS sender" - */ -define("SMS_OVH_REASON", "created Linphone SMS sender"); - -/* - * The sender description for OVH SMS - * - * Default value: "Linphone SMS sender" - */ -define("SMS_OVH_DESC", "Linphone SMS sender"); - -/* - * The template to use to send SMS to the US - * - * Default value: "Your Linphone validation code is #CODE#" - */ -define("SMS_OVH_US_TEMPLATE", "Your Linphone validation code is #CODE#"); - -/* - * The OVH endpoint - * - * Default value: ovh-eu - */ -define("SMS_OVH_ENDPOINT", "ovh-eu"); - -/* - * The URL at which the SMS API is available. - * - * Default value: - */ -define("SMS_API_URL", ""); - -/* - * The username to authenticate to the SMS API if needed. - * - * Default value: - */ -define("SMS_API_USERNAME", ""); - -/* - * The username's password to authenticate to the SMS API if needed. - * - * Default value: - */ -define("SMS_API_PASSWORD", ""); - -/* - * The period of time (in milli seconds) over which we compute the number of sent sms - * - * Default value: 86400000 (24 hours) - */ -define("SMS_TIME_PERIOD", 86400000); - -/* - * The maximum number of allowed SMS to be sent over the period - * - * Default value: 3 - */ -define("SMS_COUNT_LIMIT_IN_PERIOD", 3); - -/* ### Tests configuration ### */ - -/* - * If true, more features are available for test purposes - * - * Default value: False - */ -define('ALLOW_TEST_ACCOUNTS', False); - -/* - * Prefix used only by tests account to enable/disable some features - * - * Default value: "+1000555" - */ -define("TESTS_PHONE_PREFIX", "+1000555"); - -/* - * Prefix used only by tests account to enable/disable some features - * - * Default value: "XXXTEST" - */ -define("TESTS_LOGIN_PREFIX", "xxxtest"); - -/* ### Authentication configuration ### */ - -/* - * The domain to use for digest auth. - * - * Default value: sip.example.org - */ -define("AUTH_REALM", "sip.example.org"); - -/* Authentication SQL query - * this SQL query must retrieve a field password and a field algorithm and will bind a string holding the username into the ? - * - * Default value : "SELECT password as password, algorithm as algorithm FROM " . ACCOUNTS_ALGO_DB_TABLE . " WHERE account_id=(SELECT id FROM " . ACCOUNTS_DB_TABLE . " WHERE login=?) LIMIT 1;" - */ -define("AUTH_QUERY", "SELECT password as password, algorithm as algorithm FROM " . ACCOUNTS_ALGO_DB_TABLE . " WHERE account_id=(SELECT id FROM " . ACCOUNTS_DB_TABLE . " WHERE login=?) LIMIT 1;"); - -/* Authentication Nonce Key - * This value must be a random string(12 characters minimum length) specific to each server and is PRIVATE - * - * Default value : The default is empty to force using a key different for each server - */ -define("AUTH_NONCE_KEY", ""); - -/* Authentication Nonce Validity - * The authentication is aimed to provide a one time usage nonce, it is not strictly inforced by storing valid once, instead - * we use a short living period, the maximum validity period will be twice the minimum one, value is in seconds - * - * Default value : 10 seconds - */ -define("MIN_NONCE_VALIDITY_PERIOD", 10); -?> diff --git a/src/xmlrpc.php b/src/xmlrpc.php deleted file mode 100644 index 365e15e..0000000 --- a/src/xmlrpc.php +++ /dev/null @@ -1,130 +0,0 @@ -= 2) { - $arg1 = $argv[1]; - if (strcmp($arg1, "create_tables") == 0) { - db_create_inapp_table(); - db_create_alias_table(); - db_create_accounts_table(); - db_create_accounts_algo_table(); - db_create_devices_table(); - db_create_sms_table(); - echo "Tables have been created!\r\n"; - } else if (strcmp($arg1, "delete_tables") == 0) { - db_drop_inapp_table(); - db_drop_alias_table(); - db_drop_accounts_table(); - db_drop_accounts_algo_table(); - db_drop_devices_table(); - db_drop_sms_table(); - echo "Tables have been deleted!\r\n"; - } else if (strcmp($arg1, "create_algo_table") == 0) { - db_create_accounts_algo_table(); - echo "Algo table has been created!\r\n"; - } else if (strcmp($arg1, "drop_algo_table") == 0) { - db_drop_accounts_algo_table(); - echo "Algo table has been deleted!\r\n"; - } - exit; - } - mylog("[DEBUG] No request found"); - exit; -} - -// XMLRPC requests that do not require authentication -$unauthenticated_requests = array( - // account - 0 => 'create_email_account', - 1 => 'create_phone_account', - 2 => 'get_confirmation_key', - 3 => 'activate_email_account', - 4 => 'activate_phone_account', - 5 => 'recover_phone_account', - 6 => 'get_phone_number_for_account', - 7 => 'is_account_activated', - - // aliases - 8 => 'is_alias_used', - - // inapp - 9 => 'check_payload_signature', - - // misc - 10 => 'add_ec_calibration_result', - - // compatibility - 11 => 'create_account', - 12 => 'create_account_with_useragent', -); - -$headers = getallheaders(); -$xml = simplexml_load_string($request); -$request_type = $xml->methodName; - -// Get authentication header if there is one -if (!empty($headers['Auth-Digest'])) { - mylog("Auth-Digest = " . $headers['Auth-Digest']); - $authorization = $headers['Auth-Digest']; -} elseif (!empty($headers['Authorization'])) { - mylog("Authorization = " . $headers['Authorization']); - $authorization = $headers['Authorization']; -} - -// Authentication -if (in_array($request_type, $unauthenticated_requests) == FALSE) { - if (!empty($authorization)) { - $authentication_status = authenticate(AUTH_REALM); - - if ($authentication_status == TRUE) { - mylog("[DEBUG] Authentication successful for " . $headers['From']); - } else { - mylog("[DEBUG] Authentication failed for " . $headers['From']); - request_authentication(AUTH_REALM); - } - } else { - mylog("[DEBUG] No authentication header for " . $headers['From']); - request_authentication(AUTH_REALM); - } -} - -xmlrpc_accounts_register_methods($server); -xmlrpc_aliases_register_methods($server); -xmlrpc_inapp_register_methods($server); -xmlrpc_misc_register_methods($server); -xmlrpc_compatibility_register_methods($server); - -if ($request) { - $options = array('output_type' => 'xml', 'version' => 'auto'); - echo xmlrpc_server_call_method($server, $request, null, $options); -} - -?> diff --git a/src/xmlrpc/accounts.php b/src/xmlrpc/accounts.php new file mode 100644 index 0000000..ff9917e --- /dev/null +++ b/src/xmlrpc/accounts.php @@ -0,0 +1,791 @@ +. +*/ + +include_once __DIR__ . '/../database/database.php'; + +include_once __DIR__ . '/../objects/account.php'; +include_once __DIR__ . '/../objects/password.php'; +include_once __DIR__ . '/../objects/alias.php'; + +include_once __DIR__ . '/../misc/utilities.php'; + +include_once __DIR__ . '/results_values.php'; + +// args = [user, pwd, [domain], [algo]] +// /!\ This method must be used for tests purposes only /!\ +function xmlrpc_get_confirmation_key($method, $args) { + $user = $args[0]; + $pwd = $args[1]; + $domain = get_domain($args[2]); + $algo = get_algo($args[3]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_get_confirmation_key(" . $user . ", " . $domain . ", " . $algo . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if (!ALLOW_TEST_ACCOUNTS) { + Logger::getInstance()->error ("Non test account unauthorized"); + return TEST_ACCOUNTS_DISABLED; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if (!$password->getOne()) { + return PASSWORD_NOT_FOUND; + } + + if ($algo == "clrtxt") { + $hashed_password = $pwd; + } else { + $hashed_password = hash_password($user, $pwd, $domain, $algo); + } + + if (!password_match($hashed_password, $password->password) + && !password_match($pwd, $password->password)) { // This condition is specific for liblinphone tester.... + return PASSWORD_DOESNT_MATCH; + } + + $key = $account->confirmation_key; + Logger::getInstance()->debug("[XMLRPC] returning key = " . $key); + return $key; +} + +// args = [user, pwd, [domain], [algo]] +// /!\ This method must be used for tests purposes only /!\ +function xmlrpc_delete_account($method, $args) { + $user = $args[0]; + $pwd = $args[1]; + $domain = get_domain($args[2]); + $algo = get_algo($args[3]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_delete_account(" . $user . ", " . $domain . ", " . $algo . ")"); + + if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } else if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if (!ALLOW_TEST_ACCOUNTS) { + return TEST_ACCOUNTS_DISABLED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if (!$password->getOne()) { + return PASSWORD_NOT_FOUND; + } + + if ($algo == "clrtxt") { + $hashed_password = $pwd; + } else { + $hashed_password = hash_password($user, $pwd, $domain, $algo); + } + if (!password_match($hashed_password, $password->password) + && !password_match($pwd, $password->password)) { // This condition is specific for liblinphone tester.... + return PASSWORD_DOESNT_MATCH; + } + + $alias = new Alias($db); + $alias->account_id = $account->id; + + $account->delete(); + $password->delete(); + $alias->delete(); + + return OK; +} + +// args = [username, [domain]] +function xmlrpc_is_account_used($method, $args) { + $user = $args[0]; + $domain = get_domain($args[1]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_is_account_used(" . $user . ", " . $domain . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if ($account->getOne()) { + return OK; + } + + return NOK; +} + +// args = [username, [domain]] +function xmlrpc_is_account_activated($method, $args) { + $user = $args[0]; + $domain = get_domain($args[1]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_is_account_activated(" . $user . ", " . $domain . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + Logger::getInstance()->message("Account activation status is " . $account->activated); + if (is_activated($account->activated)) { + return OK; + } + + return NOK; +} + +// args = [phone, [domain]] +function xmlrpc_is_phone_number_used($method, $args) { + $phone = $args[0]; + $domain = get_domain($args[1]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_is_phone_number_used(" . $phone . ", " . $domain . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!startswith($phone, "+")) { + return PHONE_NOT_E164; + } + + $database = new Database(); + $db = $database->getConnection(); + + $alias = new Alias($db); + $alias->alias = $phone; + $alias->domain = $domain; + + if ($alias->getOne()) { + return OK_ALIAS; + } + + $account = new Account($db); + $account->username = $phone; + $account->domain = $domain; + + if ($account->getOne()) { + return OK_ACCOUNT; + } + + return NOK; +} + +// args = [phone, username, key, [domain], [algo]] +function xmlrpc_activate_phone_account($method, $args) { + $phone = $args[0]; + $user = $args[1]; + $key = $args[2]; + $domain = get_domain($args[3]); + $algo = get_algo($args[4]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_activate_phone_account(" . $user . ", " . $domain . ", " . $phone . ", " . $key . ", " . $algo . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if (!startswith($phone, "+")) { + Logger::getInstance()->error("Phone doesn't start by +"); + return PHONE_NOT_E164; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + $key_db = $account->confirmation_key; + if ($key == "ERROR" || $key != $key_db) { + if ($key_db != "ERROR") { + $account->confirmation_key = "ERROR"; + $account->update(); + } + + Logger::getInstance()->error("Key doesn't match"); + return KEY_DOESNT_MATCH; + } + + // If this is a recovery, account is already activated, don't go through the following again + if (!is_activated($account->activated)) { + $expiration = NULL; + $account->activated = "1"; + $account->update(); + + $alias = new Alias($db); + $alias->account_id = $account->id; + $alias->alias = $phone; + $alias->domain = $account->domain; + $alias->create(); + + if (USE_IN_APP_PURCHASES) { + $expiration = get_trial_expiration_date(); + //db_inapp_add_account($user, $domain, $expiration); + //TODO + } + + if (CUSTOM_HOOKS) { + hook_on_account_activated($account); + } + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if ($password->getOne()) { + return $password->password; + } + + return PASSWORD_NOT_FOUND; +} + +// args = [phone, [username], [password], useragent, [domain], [lang], [algo]] +function xmlrpc_create_phone_account($method, $args) { + $phone = $args[0]; + $user = $args[1]; + $hashed_password = $args[2]; + $user_agent = $args[3]; + $domain = get_domain($args[4]); + $lang = get_lang($args[5]); + $algo = get_algo($args[6]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_create_phone_account(" . $user . ", " . $domain . ", " . $phone . ", " . $lang . ", " . $algo . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!startswith($phone, "+")) { + mylog("[ERROR] Phone doesn't start by +"); + return PHONE_NOT_E164; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + if (!check_parameter($user)) { + $user = $phone; + } + + $recover_params = array( + 0 => $phone, + 1 => $domain, + 2 => $lang, + ); + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + $alias = new Alias($db); + $alias->alias = $phone; + $alias->domain = $domain; + + if ($account->getOne()) { + if (RECOVER_ACCOUNT_IF_EXISTS) { + $recovered_user = xmlrpc_recover_phone_account($method, $recover_params); + if ($recovered_user == $user) { + return OK; + } + + return ACCOUNT_RECOVERY_IMPOSSIBLE; + } + + return USERNAME_TAKEN; + } else if ($alias->getOne()) { + if (RECOVER_ACCOUNT_IF_EXISTS) { + $recovered_user = xmlrpc_recover_phone_account($method, $recover_params); + if ($recovered_user == $user) { + return OK; + } + + return ACCOUNT_RECOVERY_IMPOSSIBLE; + } + + return PHONE_TAKEN; + } + + $pwd = $hashed_password; + if (!check_parameter($hashed_password, "hashed password")) { + $pwd = generate_password(); + $hashed_password = hash_password($user, $pwd, $domain, $algo); + } + + $account->confirmation_key = generate_4_digits_code(); + $account->user_agent = $user_agent; + $account->ip_address = getIp(); + $account->activated = AUTO_ACTIVATE_ACCOUNT ? "1" : "0"; + $account->create(); + + $password = new Password($db); + $password->account_id = $account->id; + $password->password = $hashed_password; + $password->algorithm = $algo; + $password->create(); + + if ($user != $phone) { + $alias->account_id = $account->id; + $alias->create(); + } + + if (CUSTOM_HOOKS) { + hook_on_account_created($account); + } + + if (SEND_ACTIVATION_SMS) { + if (!SMS_API_ENABLED) { + // This is a hack to allow testing without sending SMS + return OK; + } + $ok = send_sms($phone, $key, $lang); + return $ok; + } else if (AUTO_ACTIVATE_ACCOUNT) { + if (USE_IN_APP_PURCHASES) { + //TODO + /*$expiration = get_trial_expiration_date(); + db_inapp_add_account($user, $domain, $expiration);*/ + } + } + + return OK; +} + +// args = [username, key, [domain], [algo]] +function xmlrpc_activate_email_account($method, $args) { + $user = $args[0]; + $key = $args[1]; + $domain = get_domain($args[2]); + $algo = get_algo($args[3]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_activate_account(" . $user . ", " . $domain . ", " . $key . ", " . $algo . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } else if ($account->activated != "0") { + return ACCOUNT_ALREADY_ACTIVATED; + } + + $key_db = $account->confirmation_key; + if ($key == "ERROR" || $key != $key_db) { + if ($key_db != "ERROR") { + $account->confirmation_key = "ERROR"; + $account->update(); + } + Logger::getInstance()->error("Key doesn't match"); + return KEY_DOESNT_MATCH; + } + + $expiration = NULL; + $account->activated = "1"; + $account->update(); + + // TODO + /*if (USE_IN_APP_PURCHASES) { + $expiration = get_trial_expiration_date(); + db_inapp_add_account($user, $domain, $expiration); + }*/ + + if (CUSTOM_HOOKS) { + hook_on_account_activated($account); + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if ($password->getOne()) { + return $password->password; + } + + return PASSWORD_NOT_FOUND; +} + +// args = [username, email, [hash], useragent, [domain], [algo]] +function xmlrpc_create_email_account($method, $args) { + $user = $args[0]; + $email = $args[1]; + $hashed_password = $args[2]; + $user_agent = $args[3]; + $domain = get_domain($args[4]); + $algo = get_algo($args[5]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_create_email_account(" . $user . ", " . $domain . ", " . $email . ", " . $algo . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if (!check_parameter($email, "email")) { + return MISSING_EMAIL_PARAM; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if ($account->getOne()) { + return USERNAME_TAKEN; + } + + if (!ALLOW_SAME_EMAILS_ON_MULTILPLE_ACCOUNTS) { + $email_account = new Account($db); + $email_account->email = $email; + if ($email_account->getOne()) { + return EMAIL_TAKEN; + } + } + + if (GENERATE_PASSWORD_ENABLED) { + $hashed_password = hash_password($user, generate_password(), $domain, $algo); + } + + $account->confirmation_key = uniqid(); + $account->email = $email; + $account->user_agent = $user_agent; + $account->ip_address = getIp(); + $account->activated = AUTO_ACTIVATE_ACCOUNT ? "1" : "0"; + $account->create(); + + $password = new Password($db); + $password->account_id = $account->id; + $password->password = $hashed_password; + $password->algorithm = $algo; + $password->create(); + + if (CUSTOM_HOOKS) { + hook_on_account_created($account); + } + + if (SEND_ACTIVATION_EMAIL && EMAIL_ENABLED) { + send_email_with_activation_link($email, $account->confirmation_key); + } else if (AUTO_ACTIVATE_ACCOUNT) { + //TODO + /*if (USE_IN_APP_PURCHASES) { + $expiration = get_trial_expiration_date(); + db_inapp_add_account($user, $domain, $expiration); + }*/ + } + + return OK; +} + +// args = [username, [domain]] +function xmlrpc_get_phone_number_for_account($method, $args) { + $user = $args[0]; + $domain = get_domain($args[1]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_get_phone_number_for_account(" . $user . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + $alias = new Alias($db); + $alias->alias = $user; + $alias->domain = $domain; + + if ($alias->getOne()) { + return $user; + } + + return ACCOUNT_NOT_FOUND; + } + + $phone = $account->alias; + if ($phone == NULL) { + return ALIAS_NOT_FOUND; + } + + if (RECOVER_ACCOUNT_IF_EXISTS) { + return ACCOUNT_NOT_FOUND; + } + + return $phone; +} + +// args = [phone, [domain], [lang]] +function xmlrpc_recover_phone_account($method, $args) { + $phone = $args[0]; + $domain = get_domain($args[1]); + $lang = get_lang($args[2]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_recover_phone_account(" . $phone . ", " . $domain . ", " . $lang . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!startswith($phone, "+")) { + return PHONE_NOT_E164; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $phone; + $account->domain = $domain; + + $alias = new Alias($db); + $alias->alias = $phone; + $alias->domain = $domain; + + if (!$account->getOne()) { + if ($alias->getOne()) { + $account->id = $alias->account_id; + // This time the search will be done on the id instead of couple username / domain + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + } else { + return ACCOUNT_NOT_FOUND; + } + } + + if (SEND_ACTIVATION_SMS) { + $key = generate_4_digits_code(); + $account->confirmation_key = $key; + $account->update(); + + if (!SMS_API_ENABLED) { + // This is a hack to allow testing without sending SMS + return $account->username; + } + $ok = send_sms($phone, $key, $lang); + if ($ok != OK) { + return $ok; + } + } + + return $account->username; +} + +// args = [username, old password, new password, [domain], [algo]] +function xmlrpc_update_password($method, $args) { + $user = $args[0]; + $domain = get_domain($args[3]); + $algo = get_algo($algo[4]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_update_password(" . $user . ", " . $domain . ", " . $algo . ")"); + + if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $args[1] = hash_password($args[0], $args[1], $algo); + $args[2] = hash_password($args[0], $args[2], $algo); + + return xmlrpc_update_hash("xmlrpc_update_password", $args); +} + +// args = [username, old hash, new hash, [domain], [algo]] +function xmlrpc_update_hash($method, $args) { + $user = $args[0]; + $hashed_old_password = $args[1]; + $hashed_new_password = $args[2]; + $domain = get_domain($args[3]); + $algo = get_algo($args[4]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_update_hash(" . $user . ", " . $domain . ", " . $algo . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if (!$password->getOne()) { + return PASSWORD_NOT_FOUND; + } + + $db_hashed_password = $password->password; + if (!password_match($db_hashed_password, $hashed_old_password)) { + return PASSWORD_DOESNT_MATCH; + } + + $password->password = $hashed_new_password; + if ($password->update()) { + Logger::getInstance()->message("Password updated successfully"); + return OK; + } + + return NOK; +} + +// args = [username, password, new email, [domain], [algo]] +function xmlrpc_update_email($method, $args) { + $user = $args[0]; + $pwd = $args[1]; + $new_email = $args[2]; + $domain = get_domain($args[3]); + $algo = get_algo($args[4]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_update_email(" . $user . ", " . $domain . ", " . $new_email . ", " . $algo . ")"); + + if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if ($algo == NULL) { + return ALGO_NOT_SUPPORTED; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if (!$password->getOne()) { + return PASSWORD_NOT_FOUND; + } + + $hashed_old_password = hash_password($user, $pwd, $domain, $algo); + if (!password_match($password->password, $hashed_old_password)) { + return PASSWORD_DOESNT_MATCH; + } + + if ($account->email == $new_email) { + Logger::getInstance()->warning("New email same as previous one"); + return EMAIL_UNCHANGED; + } + + if (!ALLOW_SAME_EMAILS_ON_MULTILPLE_ACCOUNTS) { + $email_account = new Account($db); + $email_account->email = $email; + if ($email_account->getOne()) { + return EMAIL_TAKEN; + } + } + + $account->email = $new_email; + if ($account->update()) { + Logger::getInstance()->message("Email updated successfully"); + return OK; + } + + return NOK; +} + +function xmlrpc_accounts_register_methods($server) { + if (ALLOW_TEST_ACCOUNTS) { + // /!\ This methods must be used for tests purposes only /!\ + xmlrpc_server_register_method($server, 'get_confirmation_key', 'xmlrpc_get_confirmation_key');// args = [user, pwd, [domain]], return confirmation_key + xmlrpc_server_register_method($server, 'delete_account', 'xmlrpc_delete_account');// args = [user, pwd, [domain]] + } + + xmlrpc_server_register_method($server, 'is_account_used', 'xmlrpc_is_account_used');// args = [username, [domain]], return OK or NOK + xmlrpc_server_register_method($server, 'is_account_activated', 'xmlrpc_is_account_activated');// args = [username, [domain]], return OK or NOK + xmlrpc_server_register_method($server, 'is_phone_number_used', 'xmlrpc_is_phone_number_used');// args = [phone], return OK_ACCOUNT, OK_ALIAS or NOK + xmlrpc_server_register_method($server, 'activate_phone_account', 'xmlrpc_activate_phone_account');// args = [phone, username, key, [domain]], return ha1_password + xmlrpc_server_register_method($server, 'create_phone_account', 'xmlrpc_create_phone_account');// args = [phone, [username], [password], useragent, [domain], [lang]], return OK + xmlrpc_server_register_method($server, 'activate_email_account', 'xmlrpc_activate_email_account');// args = [username, key, [domain]], return ha1_password + xmlrpc_server_register_method($server, 'create_email_account', 'xmlrpc_create_email_account');// args = [username, email, [hash], useragent, [domain]], return OK + xmlrpc_server_register_method($server, 'get_phone_number_for_account', 'xmlrpc_get_phone_number_for_account');// args = [username, [domain]], return a phone number or an error + xmlrpc_server_register_method($server, 'recover_phone_account', 'xmlrpc_recover_phone_account');// args = [phone, [domain], [lang]], return username + + xmlrpc_server_register_method($server, 'update_password', 'xmlrpc_update_password');// args = [username, old password, new password, [domain]], return OK + xmlrpc_server_register_method($server, 'update_hash', 'xmlrpc_update_hash');// args = [username, old hash, new hash, [domain]], return OK + xmlrpc_server_register_method($server, 'update_email', 'xmlrpc_update_email');// args = [username, password, new email, [domain]], return OK +} + +?> \ No newline at end of file diff --git a/src/xmlrpc/aliases.php b/src/xmlrpc/aliases.php new file mode 100644 index 0000000..cd47856 --- /dev/null +++ b/src/xmlrpc/aliases.php @@ -0,0 +1,201 @@ +. +*/ + +include_once __DIR__ . '/../database/database.php'; + +include_once __DIR__ . '/../objects/account.php'; +include_once __DIR__ . '/../objects/password.php'; +include_once __DIR__ . '/../objects/alias.php'; + +include_once __DIR__ . '/../misc/utilities.php'; + +include_once __DIR__ . '/results_values.php'; + +// args = [phone, [domain]] +function xmlrpc_is_alias_used($method, $args) { + $phone = $args[0]; + $domain = get_domain($args[1]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_is_alias_used(" . $phone . ", " . $domain . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!startswith($phone, "+")) { + return PHONE_NOT_E164; + } + + $database = new Database(); + $db = $database->getConnection(); + $alias = new Alias($db); + $alias->alias = $phone; + $alias->domain = $domain; + + if (!$alias->getOne()) { + return ALIAS_NOT_FOUND; + } + + return OK; +} + +// args = [phone, account, [domain], [lang]] +function xmlrpc_link_phone_number_with_account($method, $args) { + $phone = $args[0]; + $user = $args[1]; + $domain = get_domain($args[2]); + $lang = get_lang($args[3]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_link_phone_number_with_account(" . $user . ", " . $domain . ", " . $phone . ", " . $lang . ")"); + + if (!check_parameter($phone)) { + return MISSING_PHONE_PARAM; + } else if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if (!startswith($phone, "+")) { + return PHONE_NOT_E164; + /*} else if (db_alias_is_in_use($phone, $domain)) { + return PHONE_TAKEN;*/ + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + + if (SEND_ACTIVATION_SMS) { + if (!SMS_API_ENABLED) { + // This is a hack to allow testing without sending SMS + return OK; + } + $key = generate_4_digits_code(); + $account->confirmation_key = $key; + $account->update(); + $ok = send_sms($phone, $key, $lang); + return $ok; + } + + return SMS_DISABLED; +} + +// args = [phone, user, key, ha1, [domain], [algo]] +function xmlrpc_activate_phone_number_link($method, $args) { + $phone = $args[0]; + $user = $args[1]; + $key = $args[2]; + $ha1 = $args[3]; + $domain = get_domain($args[4]); + $algo = get_algo($args[5]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_activate_phone_number_link(" . $user . ", " . $domain . ", " . $phone . ", " . $key . ", " . $algo . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!check_parameter($user)) { + return MISSING_USERNAME_PARAM; + } else if (!startswith($phone, "+")) { + return PHONE_NOT_E164; + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $user; + $account->domain = $domain; + + if (!$account->getOne()) { + return ACCOUNT_NOT_FOUND; + } + if (!is_activated($account->activated)) { + return ACCOUNT_NOT_YET_ACTIVATED; + } + if ($key != $account->confirmation_key) { + return KEY_DOESNT_MATCH; + } + + $password = new Password($db); + $password->account_id = $account->id; + $password->algorithm = $algo; + + if (!$password->getOne()) { + return PASSWORD_NOT_FOUND; + } + if (!password_match($password->password, $ha1)) { + return PASSWORD_DOESNT_MATCH; + } + + $alias = new Alias($db); + $alias->alias = $phone; + $alias->domain = $domain; + + if ($alias->getOne()) { + $alias->account_id = $account->id; + $alias->update(); + } else { + $alias->account_id = $account->id; + $alias->create(); + } + + return OK; +} + +// args = [phone, [domain]] +function xmlrpc_get_alias($method, $args) { + $phone = $args[0]; + $domain = get_domain($args[1]); + + Logger::getInstance()->message("[XMLRPC] xmlrpc_get_alias(" . $phone . ", " . $domain . ")"); + + if (!check_parameter($phone, "phone")) { + return MISSING_PHONE_PARAM; + } else if (!startswith($phone, "+")) { + return PHONE_NOT_E164; + } + + $database = new Database(); + $db = $database->getConnection(); + $alias = new Alias($db); + $alias->alias = $phone; + $alias->domain = $domain; + + if (!$alias->getOne()) { + return ALIAS_NOT_FOUND; + } + + $account = new Account($db); + $account->id = $alias->account_id; + if ($account->getOne()) { + return $account->username; + } + + return ACCOUNT_NOT_FOUND; +} + +function xmlrpc_aliases_register_methods($server) { + xmlrpc_server_register_method($server, 'is_alias_used', 'xmlrpc_is_alias_used');// args = [phone], return OK + xmlrpc_server_register_method($server, 'link_phone_number_with_account', 'xmlrpc_link_phone_number_with_account');// args = [phone, account, [domain], [lang]], return OK + xmlrpc_server_register_method($server, 'activate_phone_number_link', 'xmlrpc_activate_phone_number_link');// args = [phone, user, key, ha1, [domain]], return OK + xmlrpc_server_register_method($server, 'get_alias', 'xmlrpc_get_alias');// args = [phone], return username +} + +?> \ No newline at end of file diff --git a/src/xmlrpc/authentication.php b/src/xmlrpc/authentication.php new file mode 100644 index 0000000..81475b8 --- /dev/null +++ b/src/xmlrpc/authentication.php @@ -0,0 +1,109 @@ +. +*/ + +include_once __DIR__ . '/../database/database.php'; + +include_once __DIR__ . '/../objects/account.php'; +include_once __DIR__ . '/../objects/password.php'; + +include_once __DIR__ . '/../misc/utilities.php'; + +// Nonce are one-time usage, in order to avoid storing them in a table +// The nonce is built using: +// - timestamp : nonce is valid for MIN_NONCE_VALIDITY_PERIOD seconds at minimum and twice it at maximum (our goal is one time usage anyway, typical value shall be 10 ) +// - request content : the response uses only the URI, enforce the content to be the same so the nonce is actually a one time usage +// a replay is not devastating (it would just be an actual replay, not a different command to server) +// - secret key : avoid an attacker to be able to generate a valid nonce +function auth_get_valid_nonces() { + $request = file_get_contents('php://input'); + $time = time(); + $time -= $time%MIN_NONCE_VALIDITY_PERIOD; // our nonce will be valid at leat MIN_NONCE_VALIDITY_PERIOD seconds and max twice it, so floor the timestamp + return array( + hash_hmac("sha256", $time.':'.$request, AUTH_NONCE_KEY), + hash_hmac("sha256", $time-MIN_NONCE_VALIDITY_PERIOD.':'.$request, AUTH_NONCE_KEY)); +} + +function request_authentication($realm = "sip.example.org") { + header('HTTP/1.1 401 Unauthorized'); + header('WWW-Authenticate: Digest realm="' . $realm. + '",qop="auth",nonce="' . auth_get_valid_nonces()[0] . '",opaque="' . md5($realm) . '"'); + exit(); +} + +function authenticate($auth_digest, $realm = "sip.example.org") { + Logger::getInstance()->debug("Authenticate : Digest ".(print_r($auth_digest, true))." realm " . $realm); + // Parse the client authentication data + $default = array('nounce', 'nc', 'cnounce', 'qop', 'username', 'uri', 'response'); + preg_match_all('~(\w+)="?([^",]+)"?~', $auth_digest, $matches); # $_SERVER['PHP_AUTH_DIGEST'] + $data = array_combine($matches[1] + $default, $matches[2]); + + // Get the password/hash from database + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $data['username']; + $account->domain = empty($data['domain']) ? SIP_DOMAIN : $data['domain']; + + if (!$account->getOne()) { + Logger::getInstance()->error("Couldn't find account " . (string)$account); + return false; + } + $pwd = new Password($db); + $pwd->account_id = $account->id; + + $stmt = $pwd->getAll(); + $num = $stmt->rowCount(); + if ($num <= 0) { + Logger::getInstance()->error("Couldn't find password " . (string)$pwd); + return false; + } + + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + extract($row); + // Generate the valid response + switch ($algorithm) { + case 'CLRTXT': + $A1 = md5($data['username'].':'.$data['realm'].':'.$password); + $A2 = md5(getenv('REQUEST_METHOD').':'.$data['uri']); + $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); + break; + case 'MD5': + $A1 = $password; // username:realm:password + $A2 = md5(getenv('REQUEST_METHOD').':'.$data['uri']); + $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); + break; + case 'SHA256': + $A1 = $password; // username:realm:password + $A2 = hash('sha256', getenv('REQUEST_METHOD').':'.$data['uri']); + $valid_response = hash('sha256', $A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); + break; + } + + // Compare with the client response + if ($data['response'] === $valid_response) { + return true; + } + } + + Logger::getInstance()->error("Failed to authenticate request"); + return false; +} + +?> diff --git a/src/xmlrpc/compatibility.php b/src/xmlrpc/compatibility.php new file mode 100644 index 0000000..cc2aa28 --- /dev/null +++ b/src/xmlrpc/compatibility.php @@ -0,0 +1,129 @@ +. +*/ + +include_once __DIR__ . '/../database/database.php'; + +include_once __DIR__ . '/../objects/account.php'; +include_once __DIR__ . '/../objects/password.php'; +include_once __DIR__ . '/../objects/alias.php'; + +include_once __DIR__ . '/../misc/utilities.php'; + +// args = [identity] +function xmlrpc_compatibility_check_account_validated($method, $args) { + // Return 1 if account is validated, else return 0 + + list($login, $domain) = explode("@", $args[0]); + if (startswith($login, "sip:")) { + list($sip, $login) = explode(":", $login); + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $login; + $account->domain = $domain; + + if ($account->getOne()) { + return is_activated($account->activated) ? '1' : '0'; + } + + return 0; +} + +// args = [identity] +function xmlrpc_compatibility_check_account($method, $args) { + // Return 1 if login is already used, else return 0 + + list($login, $domain) = explode("@", $args[0]); + if (startswith($login, "sip:")) { + list($sip, $login) = explode(":", $login); + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $login; + $account->domain = $domain; + + if ($account->getOne()) { + return 1; + } + + return 0; +} + +// args = [identity, password, email, useragent] +function xmlrpc_compatibility_create_account_with_useragent($method, $args) { + $newargs = array($args[0], $args[1], $args[2], 0, $args[3]); + return xmlrpc_compatibility_create_account($method, $newargs); +} + +// args = [identity, password, email, newsletter, useragent?] +function xmlrpc_compatibility_create_account($method, $args) { + // Return 0 if account successfully created, else return -1 + + list($login, $domain) = explode("@", $args[0]); + if (startswith($login, "sip:")) { + list($sip, $login) = explode(":", $login); + } + + $database = new Database(); + $db = $database->getConnection(); + $account = new Account($db); + $account->username = $login; + $account->domain = $domain; + + if ($account->getOne()) { + return -1; + } + + $account->email = $args[2]; + $account->confirmation_key = uniqid(); + $account->ip_address = getIp(); + $account->$user_agent = 'linphone-wizard'; + $account->activated = AUTO_ACTIVATE_ACCOUNT ? "1" : "0"; + if (count($args) == 5) { + $account->$user_agent = $args[4]; + } + $account->create(); + + $crypted_password = hash_password($login, $args[1], $domain, "MD5"); + $password = new Password($db); + $password->account_id = $account->id; + $password->password = $crypted_password; + $password->algorithm = "MD5"; + $password->create(); + + if (SEND_ACTIVATION_EMAIL && EMAIL_ENABLED) { + send_email_with_activation_link($account->email, $account->confirmation_key); + } + + return 0; +} + +function xmlrpc_compatibility_register_methods($server) { + xmlrpc_server_register_method($server, 'check_account', 'xmlrpc_compatibility_check_account'); + xmlrpc_server_register_method($server, 'create_account', 'xmlrpc_compatibility_create_account'); + xmlrpc_server_register_method($server, 'check_account_validated', 'xmlrpc_compatibility_check_account_validated'); + xmlrpc_server_register_method($server, 'create_account_with_useragent', 'xmlrpc_compatibility_create_account_with_useragent'); +} + +?> \ No newline at end of file diff --git a/src/xmlrpc/devices.php b/src/xmlrpc/devices.php new file mode 100644 index 0000000..8bcc848 --- /dev/null +++ b/src/xmlrpc/devices.php @@ -0,0 +1,55 @@ +. +*/ + +include_once __DIR__ . '/../database/database.php'; +include_once __DIR__ . '/../objects/device.php'; +include_once __DIR__ . '/results_values.php'; + +// args = [manufacturer, model, status, delay, hasHEC] +function xmlrpc_add_ec_calibration_result($method, $args) { + $manufacturer = $args[0]; + $model = $args[1]; + $status = $args[2]; + $delay = $args[3]; + + $hasHEC = 0; + if (count($args) == 5) { + $hasHEC = (int)$args[4]; + } + + $database = new Database(); + $db = $database->getConnection(); + + $device = new Device($db); + $device->manufacturer = $manufacturer; + $device->model = $model; + $device->status = $status; + $device->delay = $delay; + $device->hardware_echo_canceller = $hasHEC; + $device->create(); + + return OK; +} + +function xmlrpc_devices_register_methods($server) { + xmlrpc_server_register_method($server, 'add_ec_calibration_result', 'xmlrpc_add_ec_calibration_result');// args = [manufacturer, model, status, delay, hasHEC] +} + +?> \ No newline at end of file diff --git a/src/xmlrpc-inapp.php b/src/xmlrpc/inapp.php similarity index 74% rename from src/xmlrpc-inapp.php rename to src/xmlrpc/inapp.php index cac9452..2519fe3 100644 --- a/src/xmlrpc-inapp.php +++ b/src/xmlrpc/inapp.php @@ -1,94 +1,22 @@ = 1; - linphonedb_clean($result); - linphonedb_close($conn); - return $is_account; -} - -function db_inapp_is_account_trial($user, $domain) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT trial FROM " . INAPP_DB_TABLE . " WHERE account_id=(SELECT id FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user) . "' AND domain='" . linphonedb_escape($conn, $domain) . "')", $conn); - $row = linphonedb_fetch($result); - $is_account_trial = $row[0] == 1; - linphonedb_clean($result); - linphonedb_close($conn); - return $is_account_trial; -} - -function db_inapp_get_last_used_field($user, $domain) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT last_used FROM " . INAPP_DB_TABLE . " WHERE account_id=(SELECT id FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user) . "' AND domain='" . linphonedb_escape($conn, $domain) . "')", $conn); - $row = linphonedb_fetch($result); - $last_used_field = $row[0]; - linphonedb_clean($result); - linphonedb_close($conn); - return $last_used_field; -} - -function db_inapp_get_expiration_date($user, $domain) { - $conn = linphonedb_connect(); - $result = linphonedb_query("SELECT expire FROM " . INAPP_DB_TABLE . " WHERE account_id=(SELECT id FROM " . ACCOUNTS_DB_TABLE . " WHERE login='" . linphonedb_escape($conn, $user) . "' AND domain='" . linphonedb_escape($conn, $domain) . "')", $conn); - $row = linphonedb_fetch($result); - $expiration_date = $row[0]; - linphonedb_clean($result); - linphonedb_close($conn); - return $expiration_date; -} + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ // Google/Android specifics @@ -415,9 +343,9 @@ function xmlrpc_update_expiration_date($method, $args) { db_inapp_update_trial($user, $domain, 0); db_inapp_update_expiration_date($user, $domain, $expiration_date); - if (CUSTOM_HOOKS) { + /*if (CUSTOM_HOOKS) { hook_on_expiration_date_updated($user, $domain, $expiration_date, $payloadJson, $os); - } + }*/ return $expiration_date . ""; } else { return db_inapp_get_expiration_date($user, $domain) . ""; diff --git a/src/xmlrpc/results_values.php b/src/xmlrpc/results_values.php new file mode 100644 index 0000000..17cddd2 --- /dev/null +++ b/src/xmlrpc/results_values.php @@ -0,0 +1,71 @@ +. +*/ + +define ("OK", "OK"); +define ("NOK", "NOK"); +define ("OK_ALIAS", "OK_ALIAS"); +define ("OK_ACCOUNT", "OK_ACCOUNT"); + +/* Parameter related */ + +define ("MISSING_PHONE_PARAM", "ERROR_PHONE_PARAMETER_NOT_FOUND"); +define ("MISSING_USERNAME_PARAM", "ERROR_USERNAME_PARAMETER_NOT_FOUND"); +define ("MISSING_EMAIL_PARAM", "ERROR_EMAIL_PARAMETER_NOT_FOUND"); +define ("EMAIL_UNCHANGED", "ERROR_EMAIL_NEW_SAME_AS_OLD"); + +/* Parameter not available because already in use */ + +define ("PHONE_TAKEN", "ERROR_ALIAS_ALREADY_IN_USE"); +define ("USERNAME_TAKEN", "ERROR_ACCOUNT_ALREADY_IN_USE"); +define ("EMAIL_TAKEN", "ERROR_EMAIL_ALREADY_IN_USE"); + +/* Object not found */ + +define ("ALIAS_NOT_FOUND", "ERROR_ALIAS_DOESNT_EXIST"); +define ("ACCOUNT_NOT_FOUND", "ERROR_ACCOUNT_DOESNT_EXIST"); +define ("PASSWORD_NOT_FOUND", "ERROR_PASSWORD_NOT_FOUND"); + +/* Equality check failure */ + +define ("KEY_DOESNT_MATCH", "ERROR_KEY_DOESNT_MATCH"); +define ("PASSWORD_DOESNT_MATCH", "ERROR_PASSWORD_DOESNT_MATCH"); + +/* Disabled features */ + +define ("TEST_ACCOUNTS_DISABLED", "ERROR_NON_TEST_ACCOUNTS_UNAUTHORIZED"); +define ("SMS_DISABLED", "ERROR_SMS_API_DISABLED"); +define ("ALGO_NOT_SUPPORTED", "ERROR_ALGO_NOT_SUPPORTED"); + +/* Unexpected state */ + +define ("ACCOUNT_ALREADY_ACTIVATED", "ERROR_ACCOUNT_ALREADY_ACTIVATED"); +define ("ACCOUNT_NOT_YET_ACTIVATED", "ERROR_ACCOUNT_NOT_ACTIVATED"); + +/* Format error */ + +define ("PHONE_NOT_E164", "ERROR_PHONE_ISNT_E164"); + +/* SMS error */ + +define ("MAX_SMS_ALLOWED_EXCEEDED", "ERROR_MAX_SMS_EXCEEDED"); +define ("SMS_API_FAILURE", "ERROR_CANT_SEND_SMS"); + + +?> \ No newline at end of file diff --git a/src/xmlrpc/xmlrpc.php b/src/xmlrpc/xmlrpc.php new file mode 100644 index 0000000..3639672 --- /dev/null +++ b/src/xmlrpc/xmlrpc.php @@ -0,0 +1,105 @@ +. +*/ + +include_once __DIR__ . '/../database/database.php'; +include_once __DIR__ . '/../misc/utilities.php'; +include_once __DIR__ . '/authentication.php'; +include_once __DIR__ . '/accounts.php'; +include_once __DIR__ . '/aliases.php'; +include_once __DIR__ . '/devices.php'; +include_once __DIR__ . '/compatibility.php'; + +$request = file_get_contents("php://input"); +if (empty($request)) Logger::getInstance()->error("Request is empty"); + +$server = xmlrpc_server_create(); +if (!$server) die("Couldn't create server"); + +if (USE_DIGEST_AUTH) { + $headers = getallheaders(); + $xml = simplexml_load_string($request); + $request_type = $xml->methodName; + + $unauthenticated_requests = array( + // account + 0 => 'create_email_account', + 1 => 'create_phone_account', + 2 => 'get_confirmation_key', + 3 => 'activate_email_account', + 4 => 'activate_phone_account', + 5 => 'recover_phone_account', + 6 => 'get_phone_number_for_account', + 7 => 'is_account_activated', + + // aliases + 8 => 'is_alias_used', + + // inapp + 9 => 'check_payload_signature', + + // misc + 10 => 'add_ec_calibration_result', + + // compatibility + 11 => 'create_account', + 12 => 'create_account_with_useragent', + ); + + // Get authentication header if there is one + if (!empty($headers['Auth-Digest'])) { + Logger::getInstance()->debug("Auth-Digest = " . $headers['Auth-Digest']); + $authorization = $headers['Auth-Digest']; + } elseif (!empty($headers['Authorization'])) { + Logger::getInstance()->debug("Authorization = " . $headers['Authorization']); + $authorization = $headers['Authorization']; + } + + // Authentication + if (in_array($request_type, $unauthenticated_requests) == FALSE) { + if (!empty($authorization)) { + $authentication_status = authenticate(AUTH_REALM); + + if ($authentication_status == TRUE) { + Logger::getInstance()->debug("Authentication successful for " . $headers['From']); + } else { + Logger::getInstance()->debug("Authentication failed for " . $headers['From']); + request_authentication(AUTH_REALM); + } + } else { + Logger::getInstance()->debug("No authentication header for " . $headers['From']); + request_authentication(AUTH_REALM); + } + } +} + +xmlrpc_accounts_register_methods($server); +xmlrpc_aliases_register_methods($server); +xmlrpc_devices_register_methods($server); +if (USE_IN_APP_PURCHASES) { + xmlrpc_inapp_register_methods($server); +} +xmlrpc_compatibility_register_methods($server); + +if ($request) { + $options = array('output_type' => 'xml', 'version' => 'auto'); + echo xmlrpc_server_call_method($server, $request, null, $options); +} + +?> \ No newline at end of file