diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 00000000..6de83601
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,21 @@
+Make sure these boxes are checked before submitting your issue -- thank you!
+
+
+- [ ] You are using PHP > 5.6
+- [ ] You have installed all extensions and modules listed in [here](https://github.com/mgp25/Chat-API/wiki/Dependencies). PHP Protobuf and Curve25519 are required!
+- [ ] You have checked if someone has already asked the same issue you have.
+- [ ] You have read the [wiki](https://github.com/mgp25/Chat-API/wiki).
+- [ ] Is not a programming question.
+- [ ] You are using latest Chat API code.
+
+
+### Error
+Post your error below:
+
+
+### Debug log
+Post your debug log below:
+
+```xml
+YOUR DEBUG LOG HERE
+```
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..9e88f8c9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,14 @@
+/bootstrap/compiled.php
+/vendor
+/.idea
+/nbproject
+composer.phar
+.env.*.php
+.env.php
+.DS_Store
+Thumbs.db
+*.dat
+
+*.db
+
+*.log
diff --git a/EVENTS.md b/EVENTS.md
deleted file mode 100755
index 5c02ecc0..00000000
--- a/EVENTS.md
+++ /dev/null
@@ -1,47 +0,0 @@
-Available events and arguments
-==============================
-See events/WhatsAppEventListener.php.
-
-How to bind a callback to an event
-==================================
-
-# Create a WhatsAppEventListener class and implement the method you
-# would like to handle:
-```php
-require 'events/WhatsAppEventListenerBase.php';
-
-class MyEventListener extends WhatsAppEventListenerBase {
- function onGetMessage(
- $phone, // The user phone number including the country code.
- $from, // The sender JID.
- $msgid, // The message id.
- $type, // The message type.
- $time, // The unix time when send message notification.
- $name, // The sender name.
- $message // The message.
- ) {
- print( "onGetMessage(" . $phone . ", " . $from . ", " . $msgid . ", " . $type . ", " . $time . ", " . $name . ", " . $message . ")\n" );
- }
-}
-```
-# Require your new class;
-```php
-require 'MyEventListener.php';
-```
-# Create an instance of WhastProt.
-```php
-$w = new WhatsProt($userPhone, $userIdentity, $userName, $debug);
-```
-# Add your event listener.
-```php
-w->eventManager()->addEventListener(new MyEventListener());
-```
-# Connect to WhatsApp servers.
-```php
-$w->connect();
-```
-# Login to WhatsApp
-```php
-$w->loginWithPassword($password);
-```
-[...]
diff --git a/LICENSE b/LICENSE
index bcfbe6d6..6b156fe1 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,22 +1,675 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 mgp25
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 59a6eec3..f52d41c2 100644
--- a/README.md
+++ b/README.md
@@ -1,60 +1,36 @@
-# WhatsAPI
+# Chat API [](https://packagist.org/packages/whatsapp/chat-api) [](https://packagist.org/packages/whatsapp/chat-api) [](https://packagist.org/packages/whatsapp/chat-api)
Interface to WhatsApp Messenger
-----------
-
-### Update March 15th, 2014
-
-Sources are back after brief downtime due to [DCMA takedown](https://github.com/github/dmca/blob/master/2014-02-12-WhatsApp.md).
-
-### Note July 30th, 2013
-*New policy:*
-
-*I no longer provide support to users who are trying to send bulk messages using this API (i.e. a large amount of messages and not the built-in bulk message functionality).*
-*Sending advertisments on WhatsApp goes directly against their EULA and I have no way of determining whether the user is trying to send spam, advertising or sending mass messages to "opt-in users".*
-*And I also don't want to waste the little spare time that I have on trying to figure out ways to fuck up this beautiful ad-free platform called WhatsApp by enabling people to send spam.*
-*Everyone is free to use this API but there will be no more issue reports about being blocked after sending messages to semi-random users.*
-
-*In the famous words of Heath Ledger as the Joker (taken completely out of context by me):*
-
-**It's not about the money, it's about sending a message.**
-
-*\- [shirioko](https://github.com/shirioko)*
-
-----------
+**Read the [wiki](https://github.com/mgp25/Chat-API/wiki)** and previous issues before opening a new one! Maybe your issue is already answered.
-### Note July 14th, 2013
-*Events renamed:*
-- *A large number of events have been renamed in the event handling system to better match the recent method names.*
-- *All event names and parameters have been listed in the EVENTS.md file*
+For new WhatsApp updates check **[WhatsApp incoming updates log](https://github.com/mgp25/Chat-API/wiki/WhatsApp-incoming-updates)**
+**Do you like this project? Support it by donating**
+-  Paypal: [Donate](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=YNVNPLE45DNG6)
+-  Bitcoin: 1DCEpC9wYXeUGXS58qSsqKzyy7HLTTXNYe
----------
+### Installation
-### Note July 10th, 2013
-*Another massive overhaul in the code:*
-- *MAJOR RENAMING OF MOST METHODS!! Old legacy code will break, we are sorry but it is necessary to provide a cleaner interface. Please check the new code.*
-- *Methods renamed to give a more consistent feel to the API - all methods are now camelCase watch out for typo's!*
-- *Initial movement towards bringing the code into alignment with PSR-2 (http://www.php-fig.org/psr/2/)*
-- *There is absolutely NO, NONE, NADA, ZIP, 100% FREE of any need to use/enter a MAC address or IMEI in this code. DO NOT TRY!*
-- *[New Android token used](https://github.com/karolsarnacki/whatsapp/commit/55d8233b852ecd9f6a6f845586e91e6fadbd0c44#L1L20) as WP7 one appears to no longer work. Long live the WP7 token?*
-
-----------
+```sh
+composer require whatsapp/chat-api
+```
+- **Requires:** [PHP Protobuf](https://github.com/allegro/php-protobuf) and [Curve25519](https://github.com/mgp25/curve25519-php) to enable end to end encryption
-### Note June 18th, 2013
+### Special thanks
-*Big overhaul in the code. Big thanks to:*
-- *[Ali Hubail](https://github.com/hubail) and*
-- *[Ahmed Moh'd](http://fb.com/ahmed.mhd) for making this project happen (and adding me as a member)*
-- *[Jannik Vogel](https://github.com/JayFoxRox) for helping me retrieve the latest WhatsApp token, someone should write a book about it some day..*
-- *[Tarek Galal](https://github.com/tgalal) for providing the latest WhatsApp functionality in yowsup*
-- *[Atans](https://github.com/atans) and*
-- *[Jonathan Williamson](https://github.com/jonnywilliamson) for additional fixes*
+- [CODeRUS](https://github.com/CODeRUS)
+- [tgalal](https://github.com/tgalal)
+- [SikiFn](https://github.com/SikiFn)
+- [0xTryCatch](https://github.com/0xTryCatch)
+- [Shirioko](https://github.com/shirioko)
+- [sinjuice](https://github.com/sinjuice)
-*\- [shirioko](https://github.com/shirioko)*
+Also Ahmed Moh'd ([fb.com/ahmed.mhd](fb.com/ahmed.mhd)) and Ali Hubail ([@hubail](https://twitter.com/hubail)) for making this project possible.
+And everyone that contributes to it.
----------
@@ -63,72 +39,25 @@ According to [the company](http://www.whatsapp.com/):
> “WhatsApp Messenger is a cross-platform mobile messenger that replaces SMS and works through the existing internet data plan of your device. WhatsApp is available for iPhone, BlackBerry, Android, Windows Phone, Nokia Symbian60 & S40 phones. Because WhatsApp Messenger uses the same internet data plan that you use for email and web browsing, there is no cost to message and stay in touch with your friends.”
-Late 2011 numbers: 1 billion messages per day, ~20 million users.
-
-### Modified XMPP
-WhatsApp uses some sort of customized XMPP server, named internally as FunXMPP, which is basically some extended proprietary version.
-
-### Login procedure
-Much like XMPP, WhatsApp uses JID (jabber id) and password to successfully login to the service. The password is generated by the server and received upon registration.
-
-
-The JID is a concatenation between your country’s code and mobile number.
-
-Initial login uses Digest Access Authentication.
-
-### Message sending
-Messages are basically sent as TCP packets, following WhatsApp’s own format (unlike what’s defined in XMPP RFCs).
+Jan. 2015: 30 billion messages per day, ~700 million users.
-Messages are application level encrypted using RC4 keystreams
-
-### Multimedia Message sending
-Photos, Videos and Audio files shared with WhatsApp contacts are HTTP-uploaded to a server before being sent to the recipient(s) along with Base64 thumbnail of media file (if applicable) along with the generated HTTP link as the message body.
-
-### Event system
-WhatsApi uses an event manager (created by [facine](https://github.com/facine)) which allows you to respond to certain events.
-
-List of events and example code on how to bind an event handler:
-https://github.com/shirioko/WhatsAPI/wiki/WhatsApi-events
-
-# FAQ
-
-
-- **What’s with the hex chars floating all over the code?**
-
- Mostly WhatsApp’s proprietary control chars/commands, or formatted data according to their server’s specifications, stored in predefined dictionaries within the clients.
-
-- **What’s your future development plans?**
-
- We don’t have any.
-
-- **Would it run over the web?**
-
- We’ve tested a slightly-modified version on top of Tornado Web Server and worked like a charm, however, building a chat client is a bit tricky, do your research.
-
-- **Can I receive chats?**
-
- Indeed, using the same socket-receiving mechanism. But you have to parse the incoming data. Parsing functions aren’t included in this release, maybe in the next one?
-
-- **I think the code is messy.**
-
- It’s working.
-
-- **How can I obtain my password?**
+# License
- Register a number using WhatsAPI or intercept your phone's password using MissVenom
+As of November 1, 2015 Chat API is licensed under the GPLv3+: http://www.gnu.org/licenses/gpl-3.0.html.
-# NOTES
+# Terms and conditions
-- This proof of concept is extensible to contain every feature that make a fully-fledged client, similar to the official ones, actually could be even better.
+- You will NOT use this API for marketing purposes (spam, massive sending...).
+- We do NOT give support to anyone that wants this API to send massive messages or similar.
+- We reserve the right to block any user of this repository that does not meet these conditions.
-- During the two weeks of analysis of service mechanisms, we stumbled upon serious design and security flaws (they fixed some of them since 2011). For a company with such massive user base, we expected better practises and engineering.
+## Legal
-# License
+This code is in no way affiliated with, authorized, maintained, sponsored or endorsed by WhatsApp or any of its affiliates or subsidiaries. This is an independent and unofficial API. Use at your own risk.
-MIT - refer to the source code for the extra line.
-# Venomous
+##Cryptography Notice
-Team of Bahraini Developers.
+This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See http://www.wassenaar.org/ for more information.
-Ahmed Moh'd ([fb.com/ahmed.mhd](https://www.facebook.com/ahmed.mhd)) and Ali Hubail ([@hubail](https://twitter.com/hubail)) contributed to this release.
+The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms. The form and manner of this distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.
diff --git a/classesMD5.txt b/classesMD5.txt
deleted file mode 100644
index f8d11075..00000000
--- a/classesMD5.txt
+++ /dev/null
@@ -1,110 +0,0 @@
-===============================
-= CLASSES MD5 =
-= B64 ENCODED =
-===============================
-
-
-WhatsApp/2.11.407 Android/4.3 Device/GalaxyS3
-xOyKd7AoN0uoos7Fkeup5w==
-
-WhatsApp/2.11.404 Android/4.3 Device/GalaxyS3
-UwR/p2qFH6trUCtAwVFvlw==
-
-WhatsApp/2.11.395 Android/4.3 Device/GalaxyS3 [*] Safe version
-P3b9TfNFCkkzPoVzZnm+BA==
-
-WhatsApp/2.11.394 Android/4.3 Device/GalaxyS3
-EkA+wIj+E8R7ncRihvTbJQ==
-
-WhatsApp/2.11.393 Android/4.3 Device/GalaxyS3
-39ykQ+QRBQ3V4y5u7qnqDA==
-
-WhatsApp/2.11.391 Android/4.3 Device/GalaxyS3
-08io6i/9AExMEsEar18G5w==
-
-WhatsApp/2.11.390 Android/4.3 Device/GalaxyS3
-ueXcdj5E56OZ0ABxU/YasQ==
-
-WhatsApp/2.11.388 Android/4.3 Device/GalaxyS3
-KSb52iVfhyJMXxuGse8avw==
-
-WhatsApp/2.11.383 Android/4.3 Device/GalaxyS3
-2IVWfReKm2m+1ORLg3gQtg==
-
-WhatsApp/2.11.382 Android/4.3 Device/GalaxyS3
-IJWjujh8Eds1Ew1pjWZWvg==
-
-WhatsApp/2.11.380 Android/4.3 Device/GalaxyS3
-b9ztDlCAK+k27UGaZkM7nw==
-
-WhatsApp/2.11.378 Android/4.3 Device/GalaxyS3 [*] 5 Sept 2014. PS.
-oCtjlSonS+4H16h9HW6nNA==
-
-WhatsApp/2.11.375 Android/4.3 Device/GalaxyS3
-ZLvs/rzS8qU90wZLE/1MgQ==
-
-WhatsApp/2.11.372 Android/4.3 Device/GalaxyS3
-eAaY/5A1G1nadV0TLtmdFQ==
-
-WhatsApp/2.11.371 Android/4.3 Device/GalaxyS3
-ScUKonjwWeLYhKqH8uV4HA==
-
-WhatsApp/2.11.365 Android/4.3 Device/GalaxyS3
-GUfilO0O5J4ZEMWcQKN7mg==
-
-WhatsApp/2.11.355 Android/4.3 Device/GalaxyS3
-w5mQTrb0Tky4s6Ln6RFMVQ==
-
-WhatsApp/2.11.354 Android/4.3 Device/GalaxyS3
-MPLa6ffv7Z/WNGS60PpxJQ==
-
-WhatsApp/2.11.348 Android/4.3 Device/GalaxyS3
-vszYr764HF2FQpdbqTdr/w==
-
-WhatsApp/2.11.339 Android/4.0.4 Device/GalaxyS3
-iV15qOB/jPIidogqfJ/oJA==
-
-WhatsApp/2.11.301 Android/4.3 Device/GalaxyS3
-pZ3J/O+F3HXOyx8YixzvPQ==
-
-WhatsApp/2.11.272 Android/4.0.4 Device/GalaxyS2
-kI6dipxOAk055AWZxknGqg==
-
-WhatsApp/2.11.264 Android/4.0.4 Device/GalaxyS2
-opf5/xMP2qdqHJ+7d4/LwA==
-
-WhatsApp/2.11.254 Android/4.0.4 Device/GalaxyS2
-ueKiLIlXuHtGzw2oxoZvfg==
-
-WhatsApp/2.11.224 Android/4.4.2 Device/GalaxyS4
-ZGdhtLiFqomD5ovSpQ+Odw==
-
-WhatsApp/2.11.209 Android/4.4.2 Device/GalaxyS4
-+XW/7rCZDX9T7YrGQqTmcg==
-
-WhatsApp/2.11.200 Android/4.4.2 Device/GalaxyS4
-8PZch1s/VRHIKujxCxOXig==
-
-WhatsApp/2.11.151 Android/4.2.1 Device/GalaxyS3
-94bjoO7brhy/QJZRceJHYw==
-
-WhatsApp/2.11.144 Android/4.2.1 Device/GalaxyS3
-QtHrjQzwQjujOOOd1oObgQ==
-
-WhatsApp/2.11.139 Android/4.2.1 Device/GalaxyS3
-rzoCoMEYKQ6zoUWINKC9oQ==
-
-WhatsApp/2.11.134 Android/4.2.1 Device/GalaxyS3
-r4WQV17nVTl3+uFlF9mvEg==
-
-WhatsApp/2.11.125 Android/4.2.1 Device/GalaxyS3
-JqOGtSEKUWEu/jxzCB6Bdw==
-
-WhatsApp/2.11.113 Android/4.2.1 Device/GalaxyS3
-MOpsiNsR+nHEv0dFc3dqmA==
-
-WhatsApp/2.11.102 Android/4.2.1 Device/GalaxyS3
-zo7YXXvrrRqpikOi/CveTw==
-
-WhatsApp/2.11.69 Android/4.2.1 Device/GalaxyS3
-30CnAF22oY+2PUD5pcJGqw==
diff --git a/composer.json b/composer.json
new file mode 100644
index 00000000..af926a6c
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,37 @@
+{
+ "name": "whatsapp/chat-api",
+ "description": "The PHP WhatsApp library",
+ "license": "GPL-3.0+",
+ "keywords": [
+ "WhatsApp",
+ "WhatsAPI",
+ "Chat-API"
+ ],
+ "authors": [
+ {
+ "role": "Contributors",
+ "name": "Chat API Contributing Team",
+ "homepage": "https://github.com/mgp25/Chat-API/graphs/contributors"
+ }
+ ],
+ "support": {
+ "issues": "https://github.com/mgp25/Chat-API/issues",
+ "wiki": "https://github.com/mgp25/Chat-API/wiki",
+ "source": "https://github.com/mgp25/Chat-API"
+ },
+ "autoload": {
+ "classmap": [
+ "src/"
+ ]
+ },
+ "require": {
+ "php": ">=5.6",
+ "ext-curl": "*",
+ "ext-gd" : "*",
+ "ext-mcrypt": "*",
+ "ext-openssl" : "*",
+ "ext-pdo" : "*",
+ "ext-sockets" : "*",
+ "ext-sqlite3" : "*"
+ }
+}
diff --git a/examples/Simple CLI client.php b/examples/Simple CLI client.php
index e3b18df0..d43e4e7c 100755
--- a/examples/Simple CLI client.php
+++ b/examples/Simple CLI client.php
@@ -16,51 +16,53 @@
////////////////CONFIGURATION///////////////////////
////////////////////////////////////////////////////
-$username = "";
-$password = "";
-$identity = "";
-$nickname = "";
-$debug = false;
+$username = '';
+$password = '';
+$nickname = '';
+$debug = false;
/////////////////////////////////////////////////////
if ($_SERVER['argv'][1] == null) {
- echo "USO: php ".$_SERVER['argv'][0]." \n\nEj: php cliente.php 34123456789\n\n";
+ echo 'USAGE: php '.$_SERVER['argv'][0]." \n\nEj: php client.php 34123456789\n\n";
exit(1);
}
$target = $_SERVER['argv'][1];
function fgets_u($pStdn)
{
- $pArr = array($pStdn);
+ $pArr = [$pStdn];
- if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
- print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
+ if (false === ($num_changed_streams = stream_select($pArr, $write = null, $except = null, 0))) {
+ echo "\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n";
- return FALSE;
+ return false;
} elseif ($num_changed_streams > 0) {
return trim(fgets($pStdn, 1024));
}
- return null;
}
-function onPresenceReceived($username, $from, $type)
+function onPresenceAvailable($username, $from)
{
- $dFrom = str_replace(array("@s.whatsapp.net","@g.us"), "", $from);
- if($type == "available")
- echo "<$dFrom is online>\n\n";
- else
- echo "<$dFrom is offline>\n\n";
+ $dFrom = str_replace(['@s.whatsapp.net', '@g.us'], '', $from);
+ echo "<$dFrom is online>\n\n";
+}
+
+function onPresenceUnavailable($username, $from, $last)
+{
+ $dFrom = str_replace(['@s.whatsapp.net', '@g.us'], '', $from);
+ echo "<$dFrom is offline>\n\n";
}
echo "[] logging in as '$nickname' ($username)\n";
-$w = new WhatsProt($username, $identity, $nickname, false);
+$w = new WhatsProt($username, $nickname, $debug);
-$w->eventManager()->bind("onPresence", "onPresenceReceived");
+$w->eventManager()->bind('onPresenceAvailable', 'onPresenceAvailable');
+$w->eventManager()->bind('onPresenceUnavailable', 'onPresenceUnavailable');
$w->connect(); // Nos conectamos a la red de WhatsApp
$w->loginWithPassword($password); // Iniciamos sesion con nuestra contraseña
echo "[*]Conectado a WhatsApp\n\n";
$w->sendGetServerProperties(); // Obtenemos las propiedades del servidor
$w->sendClientConfig(); // Enviamos nuestra configuración al servidor
-$sync = array($target);
+$sync = [$target];
$w->sendSync($sync); // Sincronizamos el contacto
$w->pollMessage(); // Volvemos a poner en cola mensajes
$w->sendPresenceSubscription($target); // Nos suscribimos a la presencia del usuario
@@ -68,37 +70,37 @@ function onPresenceReceived($username, $from, $type)
$pn = new ProcessNode($w, $target);
$w->setNewMessageBind($pn);
- while (1) {
+while (1) {
$w->pollMessage();
$msgs = $w->getMessages();
foreach ($msgs as $m) {
- # process inbound messages
+ // process inbound messages
//print($m->NodeString("") . "\n");
}
- $line = fgets_u(STDIN);
- if ($line != "") {
- if (strrchr($line, " ")) {
- $command = trim(strstr($line, ' ', TRUE));
- } else {
- $command = $line;
- }
- switch ($command) {
- case "/query":
- $dst = trim(strstr($line, ' ', FALSE));
- echo "[] Interactive conversation with $contact:\n";
- break;
- case "/lastseen":
- echo "[] Last seen $target: ";
- $w->sendGetRequestLastSeen($target);
- break;
- default:
- $w->sendMessage($target , $line);
- break;
- }
+ $line = fgets_u(STDIN);
+ if ($line != '') {
+ if (strrchr($line, ' ')) {
+ $command = trim(strstr($line, ' ', true));
+ } else {
+ $command = $line;
+ }
+ switch ($command) {
+ case '/query':
+ $dst = trim(strstr($line, ' ', false));
+ echo "[] Interactive conversation with $contact:\n";
+ break;
+ case '/lastseen':
+ echo "[] Last seen $target: ";
+ $w->sendGetRequestLastSeen($target);
+ break;
+ default:
+ $w->sendMessage($target, $line);
+ break;
}
+ }
}
-class ProcessNode
+class ProcessNode implements NewMsgBindInterface
{
protected $wp = false;
protected $target = false;
@@ -109,13 +111,12 @@ public function __construct($wp, $target)
$this->target = $target;
}
- public function process($node)
+ public function process(\ProtocolNode $node)
{
$text = $node->getChild('body');
$text = $text->getData();
- $notify = $node->getAttribute("notify");
-
- echo "\n- ".$notify.": ".$text." ".date('H:i')."\n";
+ $notify = $node->getAttribute('notify');
- }
-}
+ echo "\n- ".$notify.': '.$text.' '.date('H:i')."\n";
+ }
+}
diff --git a/examples/WA CLI Client/client.php b/examples/WA CLI Client/client.php
new file mode 100755
index 00000000..eaaf2e51
--- /dev/null
+++ b/examples/WA CLI Client/client.php
@@ -0,0 +1,687 @@
+ PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $db->exec('CREATE TABLE data (`username` TEXT, `password` TEXT, `nickname` TEXT, `login` TEXT)');
+ $sql = 'INSERT INTO data (`username`, `password`, `nickname`, `login`) VALUES (:username, :password, :nickname, :login)';
+ $query = $db->prepare($sql);
+
+ $query->execute(
+ [
+ ':username' => $argv[1],
+ ':password' => $argv[2],
+ ':nickname' => $argv[3],
+ ':login' => '1',
+ ]
+ );
+ }
+}
+
+if ((!file_exists($fileName))) {
+ echo "Welcome to CLI WA Client\n";
+ echo "========================\n\n\n";
+ echo 'Your number > ';
+ $number = trim(fgets(STDIN));
+ $w = new WhatsProt($number, $nickname, $debug);
+
+ try {
+ $result = $w->codeRequest('sms');
+ } catch (Exception $e) {
+ echo 'there is an error'.$e;
+ }
+ echo "\nEnter sms code you have received > ";
+ $code = trim(str_replace('-', '', fgets(STDIN)));
+ try {
+ $result = $w->codeRegister($code);
+ } catch (Exception $e) {
+ echo 'there is an error';
+ }
+
+ echo "\nYour nickname > ";
+ $nickname = trim(fgets(STDIN));
+ do {
+ echo "Is '$nickname' right?\n";
+ echo 'yes/no > ';
+ $right = trim(fgets(STDIN));
+ if ($right != 'yes') {
+ echo "\nYour nickname > ";
+ $nickname = trim(fgets(STDIN));
+ }
+ } while ($right != 'yes');
+
+ $db = new \PDO('sqlite:'.$fileName, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $db->exec('CREATE TABLE data (`username` TEXT, `password` TEXT, `nickname` TEXT, `login` TEXT)');
+
+ $sql = 'INSERT INTO data (`username`, `password`, `nickname`, `login`) VALUES (:username, :password, :nickname, :login)';
+ $query = $db->prepare($sql);
+
+ $query->execute(
+ [
+ ':username' => $number,
+ ':password' => $result->pw,
+ ':nickname' => $nickname,
+ ':login' => '1',
+ ]
+ );
+}
+
+$db = new \PDO('sqlite:'.$fileName, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+$sql = 'SELECT username, password, nickname, login FROM data';
+$row = $db->query($sql);
+$result = $row->fetchAll();
+$username = $result[0]['username'];
+$password = $result[0]['password'];
+$nickname = $result[0]['nickname'];
+$login = $result[0]['login'];
+
+$w = new WhatsProt($username, $nickname, $debug);
+$GLOBALS['wa'] = $w;
+$w->setMessageStore(new SqliteMessageStore($username));
+$events = new MyEvents($w);
+$w->eventManager()->bind('onGetSyncResult', 'onSyncResult');
+$w->eventManager()->bind('onGetRequestLastSeen', 'onGetRequestLastSeen');
+$w->eventManager()->bind('onPresenceAvailable', 'onPresenceAvailable');
+$w->eventManager()->bind('onPresenceUnavailable', 'onPresenceUnavailable');
+$w->eventManager()->bind('onGetImage', 'onGetImage');
+$w->eventManager()->bind('onGetVideo', 'onGetVideo');
+$w->eventManager()->bind('onGetAudio', 'onGetAudio');
+
+$w->connect();
+try {
+ $w->loginWithPassword($password);
+} catch (Exception $e) {
+ echo "Error: $e";
+ exit();
+}
+echo "\nConnected to WA\n\n";
+if ($login == '1') {
+ $w->sendGetClientConfig();
+ $w->sendGetServerProperties();
+ $w->sendGetGroups();
+ $w->sendGetBroadcastLists();
+
+ $sql = 'UPDATE data SET login=?';
+ $query = $db->prepare($sql);
+ $query->execute(['0']);
+}
+$w->sendGetPrivacyBlockedList();
+$w->sendAvailableForChat($nickname);
+$show = true;
+global $onlineContacts;
+$GLOBALS['online_contacts'] = [];
+$GLOBALS['current_contact'];
+$poll = 0;
+do {
+ if ($show) {
+ showContacts();
+ $show = false;
+ }
+ $poll++;
+ if ($poll == 10) {
+ $w->pollMessage();
+ $poll = 0;
+ }
+ $mainCmd = fgets_u(STDIN);
+ switch ($mainCmd) {
+ case '/add':
+ echo "\nEnter the number you want to add > ";
+ $numberToAdd = trim(fgets(STDIN));
+ do {
+ echo "\nIs it right yes/no > ";
+ $check = trim(fgets(STDIN));
+ if ($check != 'yes') {
+ echo "\nEnter the number you want to add > ";
+ $numberToAdd = trim(fgets(STDIN));
+ }
+ } while ($check != 'yes');
+ echo "\nEnter the nickname/name > ";
+ $nickname = trim(fgets(STDIN));
+ $w->sendSync([$numberToAdd], null, 3);
+ if ($existUser) {
+ $w->sendPresenceSubscription($numberToAdd);
+ addContact($numberToAdd, $nickname);
+ }
+ break;
+ case '/delete':
+ echo "\nEnter the nickname you want to remove > ";
+ $nickname = trim(fgets(STDIN));
+ do {
+ echo "\nIs it right yes/no > ";
+ $check = trim(fgets(STDIN));
+ if ($check != 'yes') {
+ echo "\nEnter the nickname you want to remove > ";
+ $nickname = trim(fgets(STDIN));
+ }
+ } while ($check != 'yes');
+ $numberToRemove = findPhoneByNickname($nickname);
+ $w->sendSync([], [$numberToRemove], 3);
+ $w->sendPresenceUnsubscription($numberToRemove);
+ $contactsDB = __DIR__.DIRECTORY_SEPARATOR.'contacts.db';
+ $cDB = new \PDO('sqlite:'.$contactsDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $sql = 'DELETE FROM contacts WHERE nickname = :nickname';
+ $query = $cDB->prepare($sql);
+ $query->execute([':nickname' => $nickname]);
+ break;
+ case '/contacts':
+ $show = true;
+ break;
+ case '/status':
+ echo "\nEnter your status > ";
+ $status = trim(fgets(STDIN));
+ do {
+ echo "\nIs it right yes/no > ";
+ $check = trim(fgets(STDIN));
+ if ($check != 'yes') {
+ echo "\nEnter your status > ";
+ $status = trim(fgets(STDIN));
+ }
+ } while ($check != 'yes');
+ $w->sendStatusUpdate($status);
+ break;
+ case '/profile':
+ echo "\nEnter your profile picture URL > ";
+ $profile = trim(fgets(STDIN));
+ do {
+ echo "\nIs it right yes/no > ";
+ $check = trim(fgets(STDIN));
+ if ($check != 'yes') {
+ echo "\nEnter your profile picture URL > ";
+ $profile = trim(fgets(STDIN));
+ }
+ } while ($check != 'yes');
+ if (!filter_var($profile, FILTER_VALIDATE_URL) === false) {
+ if (@getimagesize($profile) !== false) {
+ $w->sendSetProfilePicture($profile);
+ }
+ } else {
+ echo "$profile is NOT a valid URL\n\n";
+ }
+ break;
+ case '/credits':
+ echo "\nSpecials thanks to 0xtryCatch :D\n";
+ break;
+ case '/secret':
+ echo "If you are a spammer or bulk sender, this is your lucky day! Follow the link:\n";
+ echo "http://bit.ly/1dOj8e0\n\n";
+ echo ":)\n\n";
+ exit();
+ break;
+ case '/chat':
+ echo "\nEnter the name of the contact > ";
+ $nickname = trim(fgets(STDIN));
+ do {
+ echo "\nIs it right yes/no > ";
+ $check = trim(fgets(STDIN));
+ if ($check != 'yes') {
+ echo "\nEnter the number you want to add > ";
+ $nickname = trim(fgets(STDIN));
+ }
+ } while ($check != 'yes');
+
+ echo "\n\n";
+ echo "You are chatting with $nickname\n";
+ echo "=================================\n\n";
+ $contact = findPhoneByNickname($nickname);
+ $latestMsgs = getLatestMessages($contact);
+ $GLOBALS['current_contact'] = $contact;
+ foreach ($latestMsgs as $msg) {
+ echo "\n- ".$nickname.': '.$msg['message'].' '.date('t/m/Y h:i:s A', $msg['t'])."\n";
+ }
+ $pn = new ProcessNode($w, $contact);
+ $w->setNewMessageBind($pn);
+ $chatting = true;
+ $compose = true;
+ $lastSeen = true;
+ while ($chatting) {
+ $w->pollMessage();
+ $msgs = $w->getMessages();
+ foreach ($msgs as $m) {
+ // process inbound messages
+ //print($m->NodeString("") . "\n");
+ }
+ if ($compose) {
+ $w->sendMessageComposing($contact);
+ $compose = false;
+ }
+ if ($lastSeen) {
+ if (!in_array($contact, $GLOBALS['online_contacts'])) {
+ $w->sendGetRequestLastSeen($contact);
+ }
+ $lastSeen = false;
+ }
+ $line = fgets_u(STDIN);
+ /*
+ $typing = true;
+ while (($c = fread(STDIN, 1)) && ($w->pollMessage()))
+ {
+ if ($typing)
+ $w->sendMessageComposing($contact);
+ switch (ord($c)) {
+ case 8:
+ // Backspace
+ $text = substr($line, 0, -1);
+ break;
+ case 10:
+ // Newline
+ $line = $text;
+ $text = "";
+ $w->sendMessagePaused($contact);
+ break 2;
+ default:
+ $text .= $c;
+ break;
+ }
+ $typing = false;
+ }
+ */
+ if ($line != '') {
+ if (strrchr($line, ' ')) {
+ $command = trim(strstr($line, ' ', true));
+ } else {
+ $command = $line;
+ }
+ switch ($command) {
+ case '/current':
+ $nickname = findNicknameByPhone($contact);
+ echo "[] Interactive conversation with $nickname:\n";
+ break;
+ case '/lastseen':
+ echo "[] Last seen $contact: ";
+ $w->sendMessagePaused($contact);
+ $compose = true;
+ $w->sendGetRequestLastSeen($contact);
+ break;
+ case '/block':
+ echo "< User is now blocked >\n";
+ $w->sendMessagePaused($contact);
+ $compose = true;
+ $blocked = privacySettings($contact, 'block');
+ $w->sendSetPrivacyBlockedList($blocked);
+ break;
+ case '/unblock':
+ echo "< User is now unblocked >\n";
+ $w->sendMessagePaused($contact);
+ $compose = true;
+ $blocked = privacySettings($contact, 'unblock');
+ $w->sendSetPrivacyBlockedList($blocked);
+ break;
+ case '/back':
+ echo "\nYou are now in the main menu\n";
+ echo "================================\n\n";
+ $chatting = false;
+ break;
+ case '/time':
+ echo date("l jS \of F Y h:i:s A")."\n\n";
+ break;
+ case '/help':
+ echo "Available commands\n";
+ echo "==================\n\n";
+ echo "/query - Shows the number you are chatting with\n";
+ echo "/lastseen - Last seen of the user\n";
+ echo "/block - Blocks the user\n";
+ echo "/unblock - Unblocks user\n";
+ echo "/time - Current time\n";
+ echo "/back - Return to main menu\n\n";
+ break;
+ default:
+ $w->sendMessagePaused($contact);
+ if (!filter_var($line, FILTER_VALIDATE_URL) === false) {
+ if (@getimagesize($line) !== false) {
+ $w->sendMessageImage($contact, $line);
+ }
+ } else {
+ $w->sendMessage($contact, $line);
+ }
+ $compose = true;
+ break;
+ }
+ }
+ }
+ break;
+ case '/time':
+ echo date("l jS \of F Y h:i:s A")."\n\n";
+ break;
+ case '/help':
+ echo "Available commands\n";
+ echo "==================\n\n";
+ echo "/add - Adds a contact\n";
+ echo "/delete - Removes a contact\n";
+ echo "/chat - Starts a conversation\n";
+ echo "/contacts - Shows all contacts\n";
+ echo "/status - Change status\n";
+ echo "/profile - Change profile image\n";
+ echo "/time - Current time\n";
+ echo "/credits - Credits & special thanks\n";
+ echo "/exit - Close WA CLI Client\n\n";
+ break;
+ default:
+ //code
+ break;
+ }
+} while (($mainCmd != '/exit'));
+
+$w->disconnect();
+echo "Disconnected. Bye! :D\n";
+
+function showContacts()
+{
+ $contactsDB = __DIR__.DIRECTORY_SEPARATOR.'contacts.db';
+ if (file_exists($contactsDB)) {
+ $cDB = new \PDO('sqlite:'.$contactsDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $sql = 'SELECT nickname FROM contacts';
+ $row = $cDB->query($sql);
+ $contacts = $row->fetchAll();
+ echo "\n Contacts\n";
+ echo "==================\n\n";
+ foreach ($contacts as $contact) {
+ echo '- '.$contact['nickname']."\n";
+ }
+ echo "\n\n";
+ }
+}
+
+function fgets_u($pStdn)
+{
+ $pArr = [$pStdn];
+
+ if (false === ($num_changed_streams = stream_select($pArr, $write = null, $except = null, 0))) {
+ echo "\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n";
+
+ return false;
+ } elseif ($num_changed_streams > 0) {
+ return trim(fgets($pStdn, 1024));
+ }
+}
+
+function addContact($number, $name)
+{
+ $contactsDB = __DIR__.DIRECTORY_SEPARATOR.'contacts.db';
+ if (!file_exists($contactsDB)) {
+ $db = new \PDO('sqlite:'.$contactsDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $db->exec('CREATE TABLE contacts (`phone` TEXT, `nickname` TEXT)');
+ } else {
+ $db = new \PDO('sqlite:'.$contactsDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ }
+ $sql = 'INSERT INTO contacts (`phone`, `nickname`) VALUES (:phone, :nickname)';
+ $query = $db->prepare($sql);
+
+ $query->execute(
+ [
+ ':phone' => $number,
+ ':nickname' => $name,
+ ]
+ );
+}
+
+function findPhoneByNickname($contact)
+{
+ $contactsDB = __DIR__.DIRECTORY_SEPARATOR.'contacts.db';
+ if (file_exists($contactsDB)) {
+ $cDB = new \PDO('sqlite:'.$contactsDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $sql = 'SELECT phone FROM contacts WHERE nickname = :nickname';
+ $query = $cDB->prepare($sql);
+ $query->execute([':nickname' => $contact]);
+ $contact = $query->fetchAll();
+ $contact = $contact[0]['phone'];
+
+ return $contact;
+ }
+}
+
+function findNicknameByPhone($phone)
+{
+ $contactsDB = __DIR__.DIRECTORY_SEPARATOR.'contacts.db';
+ if (file_exists($contactsDB)) {
+ $cDB = new \PDO('sqlite:'.$contactsDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $sql = 'SELECT nickname FROM contacts WHERE phone = :phone';
+ $query = $cDB->prepare($sql);
+ $query->execute([':phone' => $phone]);
+ $contact = $query->fetchAll();
+ $contact = $contact[0]['nickname'];
+
+ return $contact;
+ }
+}
+
+function getLatestMessages($phone)
+{
+ $msgDB = $GLOBALS['msg_db'];
+ if (file_exists($msgDB)) {
+ $cDB = new \PDO('sqlite:'.$msgDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $sql = 'SELECT message, t FROM messages WHERE `from` = :phone LIMIT 20';
+ $query = $cDB->prepare($sql);
+ $query->execute([':phone' => $phone]);
+ $messages = $query->fetchAll();
+
+ return $messages;
+ }
+}
+
+function privacySettings($number, $option)
+{
+ if ($option == 'block') {
+ $privacyDB = __DIR__.DIRECTORY_SEPARATOR.'privacy.db';
+ if (!file_exists($privacyDB)) {
+ $pDB = new \PDO('sqlite:'.$privacyDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $pDB->exec('CREATE TABLE blocked (`phone` TEXT)');
+ } else {
+ $pDB = new \PDO('sqlite:'.$privacyDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ }
+ $sql = 'INSERT INTO blocked (`phone`) VALUES (:phone)';
+ $query = $pDB->prepare($sql);
+
+ $query->execute(
+ [
+ ':phone' => $number,
+ ]
+ );
+
+ $sql = 'SELECT phone FROM blocked';
+ $query = $pDB->prepare($sql);
+ $query->execute();
+ $blocked = $query->fetchAll();
+ $i = 0;
+ for ($i; $i < count($blocked); $i++) {
+ $blockedList[] = $blocked[$i]['phone'];
+ }
+
+ return $blockedList;
+ } else {
+ $privacyDB = __DIR__.DIRECTORY_SEPARATOR.'privacy.db';
+ if (file_exists($privacyDB)) {
+ $pDB = new \PDO('sqlite:'.$privacyDB, null, null, [PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $sql = 'DELETE FROM blocked WHERE phone = :phone';
+ $query = $pDB->prepare($sql);
+ $query->execute([':phone' => $number]);
+
+ $sql = 'SELECT phone FROM blocked';
+ $query = $pDB->prepare($sql);
+ $query->execute();
+ $blocked = $query->fetchAll();
+ $i = 0;
+ for ($i; $i < count($blocked); $i++) {
+ $blockedList[] = $blocked[$i]['phone'];
+ }
+
+ return $blockedList;
+ }
+ }
+}
+
+function onSyncResult($result)
+{
+ foreach ($result->existing as $number) {
+ global $existUser;
+ $existUser = true;
+ }
+}
+
+function onGetRequestLastSeen($mynumber, $from, $id, $seconds)
+{
+ $nickname = findNicknameByPhone(ExtractNumber($from));
+ if (($seconds != '') || ($seconds != null)) {
+ echo "$nickname last seen: ".gmdate('l jS \of F Y h:i:s A', intval($seconds))."\n";
+ }
+}
+
+function onPresenceAvailable($mynumber, $from)
+{
+ $number = ExtractNumber($from);
+ if (!in_array($number, $GLOBALS['online_contacts'])) {
+ array_push($GLOBALS['online_contacts'], $number);
+ }
+ $nickname = findNicknameByPhone($number);
+ echo " < $nickname is now online >\n";
+}
+
+function onPresenceUnavailable($mynumber, $from, $last)
+{
+ $number = ExtractNumber($from);
+ if (($key = array_search($number, $GLOBALS['online_contacts'])) !== false) {
+ unset($GLOBALS['online_contacts'][$key]);
+ }
+ $nickname = findNicknameByPhone($number);
+ echo " < $nickname is now offline >\n";
+}
+
+function onGetMessage($mynumber, $from, $id, $type, $time, $name, $body)
+{
+ $number = ExtractNumber($from);
+ if ($number != $GLOBALS['current_contact']) {
+ $nickname = findNicknameByPhone($number);
+ if (($nickname != '') || ($nickname != null)) {
+ echo " < New message from $nickname >";
+ } else {
+ echo " < New message from $name ($number) >";
+ do {
+ echo "\nDo you want to add $name ($number)? add/block/nothing\n";
+ echo '> ';
+ $option = trim(fgets(STDIN));
+ } while (($option != 'add') || ($option != 'block') || ($option != 'nothing'));
+
+ switch ($option) {
+ case 'add':
+ echo "\nEnter the nickname/name > ";
+ $nickname = trim(fgets(STDIN));
+ addContact($number, $nickname);
+ $GLOBALS['wa']->sendSync([$number], null, 3);
+ $GLOBALS['wa']->sendPresenceSubscription($number);
+ break;
+ case 'block':
+ $blockedContacts = privacySettings($number, 'block');
+ $GLOBALS['wa']->sendSetPrivacyBlockedList($blockedContacts);
+ echo "$name ($number) is now blocked\n";
+ break;
+ }
+ }
+ }
+}
+
+function onGetImage($mynumber, $from, $id, $type, $time, $name, $size, $url, $file, $mimeType, $fileHash, $width, $height, $preview, $caption)
+{
+ $number = ExtractNumber($from);
+ $nickname = findNicknameByPhone($number);
+ $path = __DIR__.DIRECTORY_SEPARATOR."data/media/$nickname/";
+ if (!file_exists($path)) {
+ mkdir($path);
+ }
+ $filename = $path.time().'.jpg';
+ $data = file_get_contents($url);
+ $fp = @fopen($filename, 'w');
+ if ($fp) {
+ fwrite($fp, $data);
+ fclose($fp);
+ }
+ echo " < Received image from $nickname >\n";
+}
+
+function onGetVideo($mynumber, $from, $id, $type, $time, $name, $url, $file, $size, $mimeType, $fileHash, $duration, $vcodec, $acodec, $preview, $caption)
+{
+ $number = ExtractNumber($from);
+ $nickname = findNicknameByPhone($number);
+ $path = "data/media/$nickname/";
+ if (!file_exists($path)) {
+ mkdir($path);
+ }
+ $filename = __DIR__.DIRECTORY_SEPARATOR.$path.time().'.jpg';
+ $data = file_get_contents($url);
+ $fp = @fopen($filename, 'w');
+ if ($fp) {
+ fwrite($fp, $data);
+ fclose($fp);
+ }
+ echo " < Received video from $nickname >\n";
+}
+
+function onGetAudio($mynumber, $from, $id, $type, $time, $name, $size, $url, $file, $mimeType, $fileHash, $duration, $acodec, $fromJID_ifGroup = null)
+{
+ $number = ExtractNumber($from);
+ $nickname = findNicknameByPhone($number);
+ $path = "data/media/$nickname/";
+ if (!file_exists($path)) {
+ mkdir($path);
+ }
+ $filename = __DIR__.DIRECTORY_SEPARATOR.$path.time().'.jpg';
+ $data = file_get_contents($url);
+ $fp = @fopen($filename, 'w');
+ if ($fp) {
+ fwrite($fp, $data);
+ fclose($fp);
+ }
+ echo " < Received audio from $nickname >\n";
+}
+
+class ProcessNode implements NewMsgBindInterface
+{
+ protected $wp = false;
+ protected $target = false;
+
+ public function __construct($wp, $target)
+ {
+ $this->wp = $wp;
+ $this->target = $target;
+ }
+
+ public function process(\ProtocolNode $node)
+ {
+ if ($node->getAttribute('type') == 'text') {
+ $text = $node->getChild('body');
+ $text = $text->getData();
+ $number = ExtractNumber($node->getAttribute('from'));
+ $nickname = findNicknameByPhone($number);
+
+ echo "\n- ".$nickname.': '.$text.' '.date('H:i')."\n";
+ }
+ }
+}
diff --git a/examples/WA CLI Client/data/media/.gitkeep b/examples/WA CLI Client/data/media/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/examples/ajaxDemo/ajax.php b/examples/ajaxDemo/ajax.php
index d1c3319b..e7990d39 100755
--- a/examples/ajaxDemo/ajax.php
+++ b/examples/ajaxDemo/ajax.php
@@ -1,31 +1,31 @@
$target, "body" => $message);
- $_SESSION["outbound"] = $outbound;
+ case 'sendMessage':
+ $target = $_POST['target'];
+ $message = $_POST['message'];
+ $outbound = $_SESSION['outbound'];
+ $outbound[] = ['target' => $target, 'body' => $message];
+ $_SESSION['outbound'] = $outbound;
break;
- case "pollMessages":
- $inbound = @$_SESSION["inbound"];
- $_SESSION["inbound"] = array();
- $profilepic = @$_SESSION["profilepic"];
+ case 'pollMessages':
+ $inbound = @$_SESSION['inbound'];
+ $_SESSION['inbound'] = [];
+ $profilepic = @$_SESSION['profilepic'];
$ret = new JSONResponse();
- if ($profilepic != null && $profilepic != "") {
+ if ($profilepic != null && $profilepic != '') {
$ret->profilepic = $profilepic;
}
- $_SESSION["profilepic"] = "";
+ $_SESSION['profilepic'] = '';
if (count($inbound) > 0) {
foreach ($inbound as $message) {
$ret->messages[] = $message;
@@ -33,4 +33,4 @@ class JSONResponse
}
echo json_encode($ret);
break;
-}
\ No newline at end of file
+}
diff --git a/examples/ajaxDemo/index.php b/examples/ajaxDemo/index.php
index 5f146c07..da7c8950 100755
--- a/examples/ajaxDemo/index.php
+++ b/examples/ajaxDemo/index.php
@@ -1,10 +1,10 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-