pax_global_header 0000666 0000000 0000000 00000000064 12130076041 0014504 g ustar 00root root 0000000 0000000 52 comment=f3dbeeadedb2565f588bd7ddc1d42cb9e15b9928
php-horde-syncml-2.0.3/ 0000775 0000000 0000000 00000000000 12130076041 0014677 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/ 0000775 0000000 0000000 00000000000 12130076041 0017663 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/ 0000775 0000000 0000000 00000000000 12130076041 0020430 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/ 0000775 0000000 0000000 00000000000 12130076041 0021471 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/SyncMl/ 0000775 0000000 0000000 00000000000 12130076041 0022676 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/SyncMl/COPYING 0000664 0000000 0000000 00000057646 12130076041 0023753 0 ustar 00root root 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/SyncMl/INSTALL.p900.txt 0000664 0000000 0000000 00000002711 12130076041 0025235 0 ustar 00root root 0000000 0000000
How to get SyncML working with your P800/P900:
[[somebody with access to other phones might add instructions
for these as well. Thanks]]
Start "Remote Synchronisation" from you phones app launcher:
1)Select edit/settings and put in the following:
"Server" tab:
server address: http://yourserver.com/horde/rpc.php
user name: your horde user name
password: your horde user password
"Protocol" tab:
Needs not to be filled in. Unless you have your web-server
configured to require HTTP Authentification.
2) Configure sync types:
Start with Calendar/Tasks:
check "activate"
name can be anything
server database: must be "calendar"
For Jotter the server database name is "notes".
However you should start with activating one type only.
3) Hit Sync, wait and hope.
Now Synchronoisation should take place. During the first sync
a set union of the client's and server's data sets are created.
Further Sync runs should only transfer the changes since last
time.
If it's not working:
make sure the /tmp/sync directory exists and is writeable by your
webserver (user might be wwwrun). Try to Sync once more and check
the input/output in this directory.
Maybe change your php.ini settings so php logs ERROR messages and
NOTICEs in a file as well. Check this file. Your phone gets
confused when the XML is cluttered with stuff like
"PHP Notice: Undefined index: body in /blah/blub.php on line 256"
Consult sync@lists.horde.org and the syncml.org protocol specification.
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/SyncMl/README.program_flow.txt 0000664 0000000 0000000 00000007651 12130076041 0027102 0 ustar 00root root 0000000 0000000 rpc.php in horde's main directory is the starting point for our (and any)
RPC call.
It determines the $serverType ("syncml" for us) and then does something
like this:
$server = Horde_RPC::factory($serverType); // [will include RPC/syncml.php and create the class therein]
$server->authorize();
$input = $server->getInput(); // [basically the HTTP POST data]
$out = $server->getResponse($input, $params);
echo $out
So the main part takes place in getResponse of
framework/RPC/RPC/syncml.php's Horde_RPC_syncml class and there in
getResponse:
First, XML_WBXML_ContentHandler is installed as an output content handler:
$this->output = new XML_WBXML_ContentHandler();
Despite the name, this class has (almost) nothing to do with WBXML.
It's a helper to produce xml. To do this, it has 4 main methods:
1) startElement($uri, $element, $attrs) produces an <$element xlmns=$uri
attr1=v1 ...> opening tag
2) characters($str) addes $str to the content
3) endElement($uri, $element) produces a closing tag $element>
4) getOutput() returns the output produced so far
All subsequent code produces output by calling functions 1)-3)
After installing the output content handler, Horde_RPC_syncml::getResponse
continues with
$this->_parse($request);
do do the actual parsing and output creation and then finally
$xmlinput = $this->output->getOutput();
to retrieve the created output from the content handler.
The name $xmlinput is misleading, it should be called xmloutput instead.
So our quest for the code continues withing the Horde_RPC_syncml's _parse
function:
It creates an XML Parser and registers the class (well, the object) itself
as element handlers:
_startElement,_endElement, and _characters, which only format the data a
bit and call startElement,endElement, and characters respectively.
Please note, that start/endElment sounding functions are used for processing
the input as well as for creation of the output.
This can be somewhat confusing. As a rule of thumb, code that produces xml
output contains reference to an output var and looks like this:
$this->output->startElement(...);
After the XML parser is istalled, it is fired and the execution takes place
in the element handler functions.
A syncml message (input as well as output) has this structure::
...stuff...
...stuff...
the content handler in Horde_RPC_syncml delegate the work for header and
body to the two sub-content handlers SyncML_SyncMLHdr and
SyncML_SyncMLBody which reside in framework/SyncML/SyncML.php.
So at least we made it to the to the SyncML package by now...
The job of SyncML_SyncMLHdr is to read all the values in the header
and store them in a php session (custom session, not normal horde session
system) of type SyncML_State. After all header data is collected,
outputSyncHdr write a SyncHdr as output.
SyncML_SyncMLBody is another delegator. First it creates a
SyncML_Command_Status to output the status-code of the session
(authorized or not).
The content of the element are command(-tags): for each element
in there, an appropriate handler is created with
SyncML_Command::factory($element);
and assigned the tasks of handling this command.
So execution continues with classes in SyncML/Command/ which are
all children of SyncML_Command.
>From here, you're on your own. Just two more facts:
1)
processing of changes received from the client are handled in
SyncML/Sync.php (not to be confused with SyncML/Command/Sync.php) and
there in runSyncCommand($command) command is one of
SyncML_Command_Sync_(Add|Delete|Replace)
2)
The other way around:
creating changes on the server for the client is done after the changes
from the client have been processed. This is done in TwoWaySync.php.
Some care has to be taken to avoid that the changes that are received
from the client are considered "new changes" and echoed back to the
client. That would result in severe data duplication meltdown.
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/SyncMl/README.syncml_primer.txt 0000664 0000000 0000000 00000011013 12130076041 0027252 0 ustar 00root root 0000000 0000000
SyncML Primer:
--------------
A SyncML Protocol Primer
The specification can be downloaded from www.syncml.org.
This Primer deals with SyncML 1.0.1 only.
Basically a SynML Synchronisations consists of 6 steps: Three packages sent
from the Client to the Server and three packages the other way round.
Here's a brief description of these 2*3 steps. The Chapter references refer
to XML examples for these steps in SyncML Sync Protocol, version 1.0.1(pdf)
from syncml.org. I found these examples most helpful.
Here we go:
1a) Sync Initialization Package from Client (Chapter 4.1.1)
Client starts communication, sends authentification and device info and maybe
info about previous sync if any.
1b) Sync Initialization Package from Server (chapter 4.2.1)
Server responds with session info if authorisation was successfull, provides
device info if requested and the synchronisation type (like TwoWaySync or
SlowSync) that is suitable for this run. Basically, if both sides "remember"
the same timestamp for the previous sync run, a TwoWaySync can be used to
transfer only the differences since then. Otherwise or for initial sync,
a SlowSync is used. In that the client sends all its data to the server
which then handles them.
2a) Client Sending Modifications to Server (Chapter 5.1.1)
The client sends all its modifications since the last sync run
(or all data for SlowSync) to the server
2b) Server Sending Modifications to Client
The server incoporates the changes from the client and now sends its
modifications to the client.
3a) Data Update Status to Server (Chapter 5.3.1)
A key concept of SyncML is that client and server have their own internal
representation of the data and use different primary keys. To identify
items there has to be a mapping between the client's keys and the server's
keys. (primary keys are relative URIs in SyncML language). This map is
maintained by the server. After the client has incoporated the servers data
in its own database it sends its new primary keys () for the
changed data back to the server. The server can then update its map.
3b) Map Acknowledgement from Server (Chapter 5.4.1)
Basically says: "Whoopie, we're through. See you next time".
XML Specification:
Each SyncML Packet consists of one SyncMLHdr Element an one SyncMLBody Element.
The header contains authorisation and session information.
A typical header sent from the server might look like this::
1.0SyncML/1.04242424242422111111-00-222222-4http://mysyncmlserver.com/horde/rpc.phphttp://mysyncmlserver.com/horde/rpc.php
The SyncBody contains the following elements (called "commands") as specified
in the DTD:
(Alert | Atomic | Copy | Exec | Get | Map | Put | Results | Search | Sequence
| Status | Sync)+, Final?
CmdID: each command in a packet has a unique command id like 1
We discuss only Alert,Get,Put,Results,Map,Status Sync and Final here.
Get
The Get request command works similar to HTTP GET: it is intended to request
data from the communication partner. Currently it's only use is to retrieve
"./devinf10" (or 11 for syncml 1.1) which contains information about the sync
capabilitys of the partner.
Put
Put is similar to HTTP POST: it's designed to transfer data to the
communication partner. As with get, the only use at the moment is to publish
the "./devinf10" device information to the communication partner. A typcial
first packet from the client would include a GET for the servers devinf and a
put with the client's own devinf data.
Result
The Result Element is used to respond to a GET Command and contains the
requested data, i.e. the devinf data.
Status
In General, for each command there must be a status response from the other
side. (For exception see the spec.)
The Status includes a CmdID (like any command). It has a MsgRef and CmdRef to
identify the command it responds to: MsgRef identifies the packet (given in
the Header) and CmdRef the CmdId of the original command. There's also a
Element to specify the type::
312Put./devinf10
200
Sync
Alert
Sync and Alert is where the action takes place. Unfortunately the primer is
not yet finished.
Stay tuned or check the Spec yourself...
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/doc/Horde/SyncMl/TODO 0000664 0000000 0000000 00000001511 12130076041 0023364 0 ustar 00root root 0000000 0000000 TODOs
-----
- handle recurring events
- handle alarms in sync4j
- review session handling.
- Deal with "unfinished" sessions after incomplete sync.
- use cookies where possible. Otherwise concurrent sessions with
device ID "sc-pim-outlook" will cause trouble big time.
- implement BUSY feature
- try to speedup data retrival inside horde
- create configuration in horde preferences: allow fancy stuff like
"delete calendar entries from clients for events n days in the past"
- create page to view summary of previous sync and ultimately handle
collisions as well...
- get vcard/icalendar handling right: support ical 1.0/2.0 and vcard
2.1/3.0 creation.
Redesign / Refactoring
----------------------
-concentrate business logic where possible (controller class),
seperate xml parsing/creation from business logic
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/ 0000775 0000000 0000000 00000000000 12130076041 0020431 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/ 0000775 0000000 0000000 00000000000 12130076041 0021472 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl.php 0000664 0000000 0000000 00000015430 12130076041 0023413 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
class Horde_SyncMl
{
const ALERT_DISPLAY = 100;
const ALERT_TWO_WAY = 200;
const ALERT_SLOW_SYNC = 201;
const ALERT_ONE_WAY_FROM_CLIENT = 202;
const ALERT_REFRESH_FROM_CLIENT = 203;
const ALERT_ONE_WAY_FROM_SERVER = 204;
const ALERT_REFRESH_FROM_SERVER = 205;
// Not implemented.
const ALERT_TWO_WAY_BY_SERVER = 206;
const ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER = 207;
const ALERT_REFRESH_FROM_CLIENT_BY_SERVER = 208;
const ALERT_ONE_WAY_FROM_SERVER_BY_SERVER = 209;
const ALERT_REFRESH_FROM_SERVER_BY_SERVER = 210;
const ALERT_RESULT_ALERT = 221;
const ALERT_NEXT_MESSAGE = 222;
const ALERT_NO_END_OF_DATA = 223;
// Not (really) implemented.
const ALERT_SUSPEND = 224; // New in SyncML 1.2
const ALERT_RESUME = 225; // New in SyncML 1.2
const MIME_SYNCML_XML = 'application/vnd.syncml+xml';
const MIME_SYNCML_WBXML = 'application/vnd.syncml+wbxml';
const MIME_SYNCML_DEVICE_INFO_XML = 'application/vnd.syncml-devinf+xml';
const MIME_SYNCML_DEVICE_INFO_WBXML = 'application/vnd.syncml-devinf+wbxml';
const MIME_TEXT_PLAIN = 'text/plain';
const MIME_VCARD_V21 = 'text/x-vcard';
const MIME_VCARD_V30 = 'text/vcard';
const MIME_VCALENDAR = 'text/x-vcalendar';
const MIME_ICALENDAR = 'text/calendar';
const MIME_XML_ICALENDAR = 'application/vnd.syncml-xcal';
const MIME_MESSAGE = 'text/message';
const MIME_SYNCML_XML_EMAIL = 'application/vnd.syncml-xmsg';
const MIME_SYNCML_XML_BOOKMARK = 'application/vnd.syncml-xbookmark';
const MIME_SYNCML_RELATIONAL_OBJECT = 'application/vnd.syncml-xrelational';
const RESPONSE_IN_PROGRESS = 101;
const RESPONSE_OK = 200;
const RESPONSE_ITEM_ADDED = 201;
const RESPONSE_ACCEPTED_FOR_PROCESSING = 202;
const RESPONSE_NONAUTHORIATATIVE_RESPONSE = 203;
const RESPONSE_NO_CONTENT = 204;
const RESPONSE_RESET_CONTENT = 205;
const RESPONSE_PARTIAL_CONTENT = 206;
const RESPONSE_CONFLICT_RESOLVED_WITH_MERGE = 207;
const RESPONSE_CONFLICT_RESOLVED_WITH_CLIENT_WINNING = 208;
const RESPONSE_CONFILCT_RESOLVED_WITH_DUPLICATE = 209;
const RESPONSE_DELETE_WITHOUT_ARCHIVE = 210;
const RESPONSE_ITEM_NO_DELETED = 211;
const RESPONSE_AUTHENTICATION_ACCEPTED = 212;
const RESPONSE_CHUNKED_ITEM_ACCEPTED_AND_BUFFERED = 213;
const RESPONSE_OPERATION_CANCELLED = 214;
const RESPONSE_NO_EXECUTED = 215;
const RESPONSE_ATOMIC_ROLL_BACK_OK = 216;
const RESPONSE_MULTIPLE_CHOICES = 300;
// Need to change names.
// const RESPONSE_MULTIPLE_CHOICES = 301;
// const RESPONSE_MULTIPLE_CHOICES = 302;
// const RESPONSE_MULTIPLE_CHOICES = 303;
// const RESPONSE_MULTIPLE_CHOICES = 304;
const RESPONSE_USE_PROXY = 305;
const RESPONSE_BAD_REQUEST = 400;
const RESPONSE_INVALID_CREDENTIALS = 401;
// Need to change names.
// const RESPONSE_INVALID_CREDENTIALS = 402;
// const RESPONSE_INVALID_CREDENTIALS = 403;
const RESPONSE_NOT_FOUND = 404;
// Need to change names.
// const RESPONSE_INVALID_CREDENTIALS = 405;
// const RESPONSE_INVALID_CREDENTIALS = 406;
const RESPONSE_CREDENTIALS_MISSING = 407;
// const RESPONSE_INVALID_CREDENTIALS = 408;
// const RESPONSE_INVALID_CREDENTIALS = 409;
// const RESPONSE_INVALID_CREDENTIALS = 410;
// const RESPONSE_INVALID_CREDENTIALS = 411;
// const RESPONSE_INVALID_CREDENTIALS = 412;
// const RESPONSE_INVALID_CREDENTIALS = 413;
// const RESPONSE_INVALID_CREDENTIALS = 414;
// const RESPONSE_INVALID_CREDENTIALS = 415;
const RESPONSE_REQUEST_SIZE_TOO_BIG = 416;
// Need to change names.
// const RESPONSE_INVALID_CREDENTIALS = 417;
// const RESPONSE_INVALID_CREDENTIALS = 418;
// const RESPONSE_INVALID_CREDENTIALS = 419;
// const RESPONSE_INVALID_CREDENTIALS = 420;
// const RESPONSE_INVALID_CREDENTIALS = 421;
// const RESPONSE_INVALID_CREDENTIALS = 422;
// const RESPONSE_INVALID_CREDENTIALS = 423;
const RESPONSE_SIZE_MISMATCH = 424;
const RESPONSE_COMMAND_FAILED = 500;
// Need to change names.
// const RESPONSE_COMMAND_FAILED = 501;
// const RESPONSE_COMMAND_FAILED = 502;
// const RESPONSE_COMMAND_FAILED = 503;
// const RESPONSE_COMMAND_FAILED = 504;
// const RESPONSE_COMMAND_FAILED = 505;
// const RESPONSE_COMMAND_FAILED = 506;
// const RESPONSE_COMMAND_FAILED = 507;
const RESPONSE_REFRESH_REQUIRED = 508;
// const RESPONSE_COMMAND_FAILED = 509;
// const RESPONSE_COMMAND_FAILED = 510;
// const RESPONSE_COMMAND_FAILED = 511;
// const RESPONSE_COMMAND_FAILED = 512;
// const RESPONSE_COMMAND_FAILED = 513;
// const RESPONSE_COMMAND_FAILED = 514;
// const RESPONSE_COMMAND_FAILED = 515;
// const RESPONSE_ATOMIC_ROLL_BACK_FAILED = 516;
const NAME_SPACE_URI_SYNCML = 'syncml:syncml';
const NAME_SPACE_URI_SYNCML_1_1 = 'syncml:syncml1.1';
const NAME_SPACE_URI_SYNCML_1_2 = 'syncml:syncml1.2';
const NAME_SPACE_URI_METINF = 'syncml:metinf';
const NAME_SPACE_URI_METINF_1_1 = 'syncml:metinf';
const NAME_SPACE_URI_METINF_1_2 = 'syncml:metinf';
const NAME_SPACE_URI_DEVINF = 'syncml:devinf';
const NAME_SPACE_URI_DEVINF_1_1 = 'syncml:devinf';
const NAME_SPACE_URI_DEVINF_1_2 = 'syncml:devinf';
/**
* Maximum Size of a data object. Currently global for all databases.
*/
const SERVER_MAXOBJSIZE = 1000000000;
/**
* Maximum size for one sync message as defined by SyncML protocol spec.
*/
const SERVER_MAXMSGSIZE = 1000000000;
/**
* The "safety margin" for the closing tags when finishing a message.
*
* When exporting a data entry, we have to ensure that the size of the
* complete message does not exceed MaxMsgSize sent by the client.
*/
const MSG_TRAILER_LEN = 150;
/**
* Standard size for a complete but empty SyncML message. Used in estimating
* the size for a message.
*/
const MSG_DEFAULT_LEN = 1000;
/**
* If true the client uid<->server uid map will be deleted when a SlowSync
* is requested.
*
* This produces duplicates if there are entries in the client and the
* server. This need to be true for the test conformance suite.
*/
const CONFIG_DELETE_MAP_ON_REQUESTED_SLOWSYNC = true;
/**
* If true the client uid<->server uid map will be deleted when a SlowSync
* is done due to an anchor mismatch. An anchor mismatch may happen if a
* session terminates unexpectedly.
*/
const CONFIG_DELETE_MAP_ON_ANCHOR_MISMATCH_SLOWSYNC = false;
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/ 0000775 0000000 0000000 00000000000 12130076041 0022677 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Backend.php 0000664 0000000 0000000 00000115644 12130076041 0024752 0 ustar 00root root 0000000 0000000 server ID map
* The SyncML protocol does not require clients and servers to use the same
* primary keys for the data entries. So a map has to be in place to
* convert between client primary keys (called cuid's here) and server
* primary keys (called suid's). It's up to the server to maintain this
* map. Method for this is createUidMap().
*
* 4) Sync anchor handling
* After a successful initial sync, the client and server sync timestamps
* are stored. This allows to perform subsequent syncs as delta syncs,
* where only new changes are replicated. Servers as well as clients need
* to be able to store two sync anchors (the client's and the server's) for
* a sync. Methods for this are readSyncAnchors() and writeSyncAnchors().
*
* 5) Test supporting functions
* The SyncML module comes with its own testing framework. All you need to
* do is implement the two methods testSetup() and testTearDown() and you
* are able to test your backend with all the test cases that are part of
* the module.
*
* 6) Miscellaneous functions
* This involves session handling (sessionStart() and sessionClose()),
* logging (logMessage() and logFile()), timestamp creation
* (getCurrentTimeStamp()), charset handling (getCharset(), setCharset())
* and database identification (isValidDatabaseURI()). For all of these
* functions, a default implementation is provided in Horde_SyncMl_Backend.
*
* If you want to create a backend for your own appliction, you can either
* derive from Horde_SyncMl_Backend and implement everything in groups 1 to 5
* or you derive from Horde_SyncMl_Backend_Sql which implements an example
* backend based on direct database access using the PEAR MDB2 package. In this
* case you only need to implement groups 1 to 3 and can use the implementation
* from Horde_SyncMl_Backend_Sql as a guideline for these functions.
*
* Key Concepts
* ------------
* In order to successfully create a backend, some understanding of a few key
* concepts in SyncML and the Horde_SyncMl package are certainly helpful. So
* here's some stuff that should make some issues clear (or at lest less
* obfuscated):
*
* 1) DatabaseURIs and Databases
* The SyncML protocol itself is completly independant from the data that
* is replicated. Normally the data are calendar or address book entries
* but it may really be anything from browser bookmarks to comeplete
* database tables. An ID (string name) of the database you want to
* actually replicate has to be configured in the client. Typically that's
* something like 'calendar' or 'tasks'. Client and server must agree on
* these names. In addition this string may be used to provide additional
* arguments. These are provided in a HTTP GET query style: like
* tasks?ignorecompletedtasks to replicate only pending tasks. Such a "sync
* identifier" is called a DatabaseURI and is really a database name plus
* some additional options.
* The Horde_SyncMl package completly ignores these options and simply passes
* them on to the backend. It's up to the backend to decide what to do with
* them. However when dealing with the internal maps (cuid<->suid and sync
* anchors), it's most likely to use the database name only rather than the
* full databaseURI. The map information saying that server entry
* 20070101203040xxa@mypc.org has id 768 in the client device is valid for
* the database "tasks", not for "tasks?somesillyoptions". So what you
* normally do is calling some kind of $database =
* $this->normalize($databaseURI) in every backend method that deals
* with databaseURIs and use $database afterwards. However actual usage of
* options is up to the backend implementation. SyncML works fine without.
*
* 2) Suid and Guid mapping
* This is the mapping of client IDs to server IDs and vice versa. Please
* note that this map is per user and per client device: the server entry
* 20070101203040xxa@mypc.org may have ID 720 in your PDA and AA10FC3A in
* your mobile phone.
*
* 3) Sync Anchors
* @todo describe sync anchors
* Have a look at the SyncML spec
* http://www.openmobilealliance.org/tech/affiliates/syncml/syncmlindex.html
* to find out more.
*
* 4) Changes and Timestamps
* @todo description of Changes and Timestamps, "mirroring effect"
* This is real tricky stuff.
* First it's important to know, that the SyncML protocol requires the
* ending timestamp of the sync timeframe to be exchanged _before_ the
* actual syncing starts. So all changes made during a sync have timestamps
* that are in the timeframe for the next upcoming sync. Data exchange in
* a sync session works in two steps: 1st) the clients sends its changes to
* the server, 2nd) the server sends its changes to the client.
* So when in step 2, the backend datastore API is called with a request
* like "give me all changes in the server since the last sync". Thus you
* also get the changes induced by the client in step 1 as well. You have
* to somehow "tag" them to avoid echoing (and thus duplicating) them back
* to the client. Simply storing the guids in the session is not
* sufficient: the changes are made _after_ the end timestamp (see 1) of
* the current sync so you'll dupe them in the next sync.
* The current implementation deals with this as follows: whenever a client
* induced change is done in the backend, the timestamp for this change is
* stored in the cuid<->suid map in an additional field. That's the perfect
* place as the tagging needs to be done "per client device": when an add
* is received from the PDA it must not be sent back as an add to this
* device, but to mobile phone it must be sent.
* This is sorted out during the getServerChanges() process: if a server
* change has a timestamp that's the same as in the guid<->suid map, it
* came from the client and must not be added to the list of changes to be
* sent to this client.
* See the description of Horde_SyncMl_Backend_Sql::_getChangeTS() for some
* more information.
*
* 5) Messages and Packages
* A message is a single HTTP Request. A package is single "logical
* message", a sync step. Normally the two coincide. However due to message
* size restrictions one package may be transferred in multiple messages
* (HTTP requests).
*
* 7) Server mode, client mode and test mode
* Per default, a backend is used for an SyncML server. Regarding the
* SyncML protocol, the working of client and server is similar, except
* that
* a) the client initiates the sync requests and the server respons to them,
* and
* b) the server must maintain the client id<->server id map.
*
* Currently the Horde_SyncMl package is designed to create servers. But
* is's an obvious (and straightforward) extension to do it for clients as
* well. And as a client has actually less work to do than a server, the
* backend should work for servers _and_ clients. During the sessionStart(),
* the backend gets a parameter to let it know whether it's in client or
* server mode (or test, see below). When in client mode, it should behave
* slightly different:
* a) the client doesn't do suid<->cuid mapping, so all invokations to the
* map creation method createUidMap().
* b) the client has only client ids, no server ids. So all arguments are
* considered cuids even when named suid. See the Horde_SyncMl_Backend_Sql
* implementation, it's actually not that difficult.
*
* Finally there's the test mode. The test cases consist of replaying
* pre-recorded sessions. For that to work, the test script must "simulate"
* user entries in the server data store. To do so, it creates a backend in
* test mode. This behaves similar to a client: when an server entry is
* created (modified) using addEntry() (replaceEntry()), no map entry must
* be done.
* The test backend uses also the two methods testSetup() and testTearDown()
* to create a clean (empty) enviroment for the test user "syncmltest". See
* the Horde_SyncMl_Backend_Sql implementation for details.
*
* Copyright 2005-2013 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Karsten Fourmont
* @package SyncMl
*/
class Horde_SyncMl_Backend
{
/** Types of logfiles. See logFile() method. */
const LOGFILE_CLIENTMESSAGE = 1;
const LOGFILE_SERVERMESSAGE = 2;
const LOGFILE_DEVINF = 3;
const LOGFILE_DATA = 4;
/** Backend modes. */
const MODE_SERVER = 1;
const MODE_CLIENT = 2;
const MODE_TEST = 3;
/**
* The State object.
*
* @var Horde_SyncMl_State
*/
public $state;
/**
* The concatenated log messages.
*
* @var string
*/
protected $_logtext = '';
/**
* The directory where debugging information is stored.
*
* @see Horde_SyncMl_Backend()
* @var string
*/
protected $_debugDir;
/**
* Whether to save SyncML messages in the debug directory.
*
* @see Horde_SyncMl_Backend()
* @var boolean
*/
protected $_debugFiles;
/**
* The log level.
*
* @see Horde_SyncMl_Backend()
* @var string
*/
protected $_logLevel = 'INFO';
/**
* The charset used in the SyncML messages.
*
* @var string
*/
protected $_charset;
/**
* The current user.
*
* @var string
*/
protected $_user;
/**
* The ID of the client device.
*
* This is used for all data access as an ID to allow to distinguish
* between syncs with different devices. $this->_user together with
* $this->_syncDeviceID is used as an additional key for all persistence
* operations.
*
* @var string
*/
protected $_syncDeviceID;
/**
* The backend mode. One of the Horde_SyncMl_Backend::MODE_* constants.
*
* @var integer
*/
protected $_backendMode;
/**
* Constructor.
*
* Sets up the default logging mechanism.
*
* @param array $params A hash with parameters. The following are
* supported by the default implementation.
* Individual backends may support other parameters.
* - debug_dir: A directory to write debug output
* to. Must be writeable by the web
* server.
* - debug_files: If true, log all incoming and
* outgoing packets and data
* conversions and devinf log in
* debug_dir.
* - log_level: Only log entries with at least
* this level. Defaults to 'INFO'.
*/
public function __construct($params)
{
if (!empty($params['debug_dir']) && is_dir($params['debug_dir'])) {
$this->_debugDir = $params['debug_dir'];
}
$this->_debugFiles = !empty($params['debug_files']);
if (isset($params['log_level'])) {
$this->_logLevel = $params['log_level'];
}
$this->logMessage('Backend of class ' . get_class($this) . ' created', 'DEBUG');
}
/**
* Attempts to return a concrete Horde_SyncMl_Backend instance based on $driver.
*
* @param string $driver The type of concrete Backend subclass to return.
* The code is dynamically included from
* Backend/$driver.php if no path is given or
* directly with "include_once $driver . '.php'"
* if a path is included. So make sure this parameter
* is "safe" and not directly taken from web input.
* The class in the file must be named
* 'Horde_SyncMl_Backend_' . basename($driver) and extend
* Horde_SyncMl_Backend.
* @param array $params A hash containing any additional configuration or
* connection parameters a subclass might need.
*
* @return Horde_SyncMl_Backend The newly created concrete Horde_SyncMl_Backend
* instance, or false on an error.
*/
public function factory($driver, $params = null)
{
if (empty($driver) || ($driver == 'none')) {
return false;
}
$driver = basename($driver);
$class = 'Horde_SyncMl_Backend_' . $driver;
if (class_exists($class)) {
$backend = new $class($params);
} else {
return false;
}
return $backend;
}
/**
* Sets the charset.
*
* All data passed to the backend uses this charset and data returned from
* the backend must use this charset, too.
*
* @param string $charset A valid charset.
*/
public function setCharset($charset)
{
$this->_charset = $charset;
}
/**
* Returns the charset.
*
* @return string The charset used when talking to the backend.
*/
public function getCharset()
{
return $this->_charset;
}
/**
* Returns the current device's ID.
*
* @return string The device ID.
*/
public function getSyncDeviceID()
{
return $this->_syncDeviceID;
}
/**
* Sets the user used for this session.
*
* This method is called by SyncML right after sessionStart() when either
* authentication is accepted via checkAuthentication() or a valid user
* has been retrieved from the state. $this->_user together with
* $this->_syncDeviceID is used as an additional key for all persistence
* operations.
* This method may have to force a "login", when the backend doesn't keep
* auth state within a session or when in test mode.
*
* @param string $user A user name.
*/
public function setUser($user)
{
$this->_user = $user;
}
/**
* Returns the current user.
*
* @return string The current user.
*/
public function getUser()
{
return $this->_user;
}
/**
* Is called after the Horde_SyncMl_State object has been set up, either
* restored from the session, or freshly created.
*/
public function setupState()
{
}
/**
* Starts a PHP session.
*
* @param string $syncDeviceID The device ID.
* @param string $session_id The session ID to use.
* @param integer $backendMode The backend mode, one of the
* Horde_SyncMl_Backend::MODE_* constants.
*/
public function sessionStart($syncDeviceID, $sessionId,
$backendMode = Horde_SyncMl_Backend::MODE_SERVER)
{
$this->_syncDeviceID = $syncDeviceID;
$this->_backendMode = $backendMode;
// Only the server needs to start a session:
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$sid = md5($syncDeviceID . $sessionId);
session_id($sid);
@session_start();
}
}
/**
* Closes the PHP session.
*/
public function sessionClose()
{
// Only the server needs to start a session:
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
session_unset();
session_destroy();
}
}
/**
* Returns whether a database URI is valid to be synced with this backend.
*
* This default implementation accepts "tasks", "calendar", "notes" and
* "contacts". However individual backends may offer replication of
* different or completly other databases (like browser bookmarks or
* cooking recipes).
*
* @param string $databaseURI URI of a database. Like calendar, tasks,
* contacts or notes. May include optional
* parameters:
* tasks?options=ignorecompleted.
*
* @return boolean True if a valid URI.
*/
public function isValidDatabaseURI($databaseURI)
{
$database = $this->normalize($databaseURI);
switch($database) {
case 'tasks':
case 'calendar':
case 'notes':
case 'contacts':
case 'configuration':
return true;
default:
$this->logMessage('Invalid database "' . $database
. '". Try tasks, calendar, notes or contacts.', 'ERR');
return false;
}
}
/**
* Returns entries that have been modified in the server database.
*
* @abstract
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param integer $from_ts Start timestamp.
* @param integer $to_ts Exclusive end timestamp. Not yet
* implemented.
* @param array &$adds Output array: hash of adds suid => 0
* @param array &$mods Output array: hash of modifications
* suid => cuid
* @param array &$dels Output array: hash of deletions suid => cuid
*
* @return mixed True on success or a PEAR_Error object.
*/
public function getServerChanges($databaseURI, $from_ts, $to_ts, &$adds, &$mods,
&$dels)
{
die('getServerChanges() not implemented!');
}
/**
* Retrieves an entry from the backend.
*
* @abstract
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid Server unique id of the entry: for horde
* this is the guid.
* @param string $contentType Content-Type: the MIME type in which the
* public function should return the data.
* @param array $fields Hash of field names and Horde_SyncMl_Property
* properties with the requested fields.
*
* @return mixed A string with the data entry or a PEAR_Error object.
*/
public function retrieveEntry($databaseURI, $suid, $contentType, $fields)
{
die('retrieveEntry() not implemented!');
}
/**
* Adds an entry into the server database.
*
* @abstract
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $cuid Client ID of this entry.
*
* @return array PEAR_Error or suid (Horde guid) of new entry
*/
public function addEntry($databaseURI, $content, $contentType, $cuid)
{
die('addEntry() not implemented!');
}
/**
* Replaces an entry in the server database.
*
* @abstract
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $cuid Client ID of this entry.
*
* @return string PEAR_Error or server ID (Horde GUID) of modified entry.
*/
public function replaceEntry($databaseURI, $content, $contentType, $cuid)
{
die('replaceEntry() not implemented!');
}
/**
* Deletes an entry from the server database.
*
* @abstract
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid Client ID of the entry.
*
* @return boolean True on success or false on failed (item not found).
*/
public function deleteEntry($databaseURI, $cuid)
{
die('deleteEntry() not implemented!');
}
/**
* Authenticates the user at the backend.
*
* For some types of authentications (notably auth:basic) the username
* gets extracted from the authentication data and is then stored in
* username. For security reasons the caller must ensure that this is the
* username that is used for the session, overriding any username
* specified in .
*
* @param string $username Username as provided in the .
* May be overwritten by $credData.
* @param string $credData Authentication data provided by
* in the .
* @param string $credFormat Format of data as in
* the . Typically 'b64'.
* @param string $credType Auth type as provided by
* in the . Typically
* 'syncml:auth-basic'.
*
* @return boolean|string The user name if authentication succeeded, false
* otherwise.
*/
public function checkAuthentication(&$username, $credData, $credFormat, $credType)
{
if (empty($credData) || empty($credType)) {
return false;
}
switch ($credType) {
case 'syncml:auth-basic':
list($username, $pwd) = explode(':', base64_decode($credData), 2);
$this->logMessage('Checking authentication for user ' . $username, 'DEBUG');
return $this->_checkAuthentication($username, $pwd);
case 'syncml:auth-md5':
/* syncml:auth-md5 only transfers hash values of passwords.
* Currently the syncml:auth-md5 hash scheme is not supported
* by the authentication backend. So we can't use Horde to do
* authentication. Instead here is a very crude direct manual hook:
* To allow authentication for a user 'dummy' with password 'sync',
* run
* php -r 'print base64_encode(pack("H*",md5("dummy:sync")));'
* from the command line. Then create an entry like
* 'dummy' => 'ZD1ZeisPeQs0qipHc9tEsw==' in the users array below,
* where the value is the command line output.
* This user/password combination is then accepted for md5-auth.
*/
$users = array(
// example for user dummy with pass pass:
// 'dummy' => 'ZD1ZeisPeQs0qipHc9tEsw=='
);
if (empty($users[$username])) {
return false;
}
// @todo: nonce may be specified by client. Use it then.
$nonce = '';
if (base64_encode(pack('H*', md5($users[$username] . ':' . $nonce))) === $credData) {
return $this->_setAuthenticated($username, $credData);
}
return false;
default:
$this->logMessage('Unsupported authentication type ' . $credType, 'ERR');
return false;
}
}
/**
* Authenticates the user at the backend.
*
* @abstract
*
* @param string $username A user name.
* @param string $password A password.
*
* @return boolean|string The user name if authentication succeeded, false
* otherwise.
*/
protected function _checkAuthentication($username, $password)
{
die('_checkAuthentication() not implemented!');
}
/**
* Sets a user as being authenticated at the backend.
*
* @abstract
*
* @param string $username A user name.
* @param string $credData Authentication data provided by
* in the .
*
* @return string The user name.
*/
protected function _setAuthenticated($username, $credData)
{
die('setAuthenticated() not implemented!');
}
/**
* Stores Sync anchors after a successful synchronization to allow two-way
* synchronization next time.
*
* The backend has to store the parameters in its persistence engine
* where user, syncDeviceID and database are the keys while client and
* server anchor ar the payload. See readSyncAnchors() for retrieval.
*
* @abstract
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $clientAnchorNext The client anchor as sent by the
* client.
* @param string $serverAnchorNext The anchor as used internally by the
* server.
*/
public function writeSyncAnchors($databaseURI, $clientAnchorNext,
$serverAnchorNext)
{
}
/**
* Reads the previously written sync anchors from the database.
*
* @abstract
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
*
* @return mixed Two-element array with client anchor and server anchor as
* stored in previous writeSyncAnchor() calls. False if no
* data found.
*/
public function readSyncAnchors($databaseURI)
{
}
/**
* Creates a map entry to map between server and client IDs.
*
* If an entry already exists, it is overwritten.
*
* @abstract
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid Client ID of the entry.
* @param string $suid Server ID of the entry.
* @param integer $timestamp Optional timestamp. This can be used to
* 'tag' changes made in the backend during the
* sync process. This allows to identify these,
* and ensure that these changes are not
* replicated back to the client (and thus
* duplicated). See key concept "Changes and
* timestamps".
*/
public function createUidMap($databaseURI, $cuid, $suid, $timestamp = 0)
{
}
/**
* Erases all mapping entries for one combination of user, device ID.
*
* This is used during SlowSync so that we really sync everything properly
* and no old mapping entries remain.
*
* @abstract
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
*/
public function eraseMap($databaseURI)
{
}
/**
* Logs a message in the backend.
*
* TODO: This should be done via Horde_Log or the equivalent.
*
* @param mixed $message Either a string or a PEAR_Error object.
* @param string $file What file was the log public function called from
* (e.g. __FILE__)?
* @param integer $line What line was the log public function called from
* (e.g. __LINE__)?
* @param integer $priority The priority of the message. One of:
* - EMERG
* - ALERT
* - CRIT
* - ERR
* - WARN
* - NOTICE
* - INFO
* - DEBUG
*/
public function logMessage($message, $priority = 'INFO')
{
if (is_string($priority)) {
$priority = defined('Horde_Log::' . $priority)
? constant('Horde_Log::' . $priority)
: Horde_Log::INFO;
}
if (is_string($this->_logLevel)) {
$loglevel = defined('Horde_Log::' . $this->_logLevel)
? constant('Horde_Log::' . $this->_logLevel)
: Horde_Log::INFO;
} else {
$loglevel = $this->_logLevel;
}
if ($priority > $loglevel) {
return;
}
// Internal logging to logtext
if (is_string($this->_logtext)) {
switch ($priority) {
case Horde_Log::EMERG:
$this->_logtext .= 'EMERG: ';
break;
case Horde_Log::ALERT:
$this->_logtext .= 'ALERT: ';
break;
case Horde_Log::CRIT:
$this->_logtext .= 'CRIT: ';
break;
case Horde_Log::ERR:
$this->_logtext .= 'ERR: ';
break;
case Horde_Log::WARN:
$this->_logtext .= 'WARNING:';
break;
case Horde_Log::NOTICE:
$this->_logtext .= 'NOTICE: ';
break;
case Horde_Log::INFO:
$this->_logtext .= 'INFO: ';
break;
case Horde_Log::DEBUG:
$this->_logtext .= 'DEBUG: ';
break;
default:
$this->_logtext .= 'UNKNOWN:';
}
if (is_string($message)) {
$this->_logtext .= $message;
} elseif (is_a($message, 'PEAR_Error')) {
$this->_logtext .= $message->getMessage();
}
$this->_logtext .= "\n";
}
}
/**
* Logs data to a file in the debug directory.
*
* @param integer $type The data type. One of the Horde_SyncMl_Backend::LOGFILE_*
* constants.
* @param string $content The data content.
* @param boolean $wbxml Whether the data is wbxml encoded.
* @param boolean $sessionClose Whether this is the last SyncML message
* in a session. Bump the file number.
*/
public function logFile($type, $content, $wbxml = false, $sessionClose = false)
{
if (empty($this->_debugDir) || !$this->_debugFiles) {
return;
}
switch ($type) {
case Horde_SyncMl_Backend::LOGFILE_CLIENTMESSAGE:
$filename = 'client_';
$mode = 'wb';
break;
case Horde_SyncMl_Backend::LOGFILE_SERVERMESSAGE:
$filename = 'server_';
$mode = 'wb';
break;
case Horde_SyncMl_Backend::LOGFILE_DEVINF:
$filename = 'devinf.txt';
$mode = 'wb';
break;
case Horde_SyncMl_Backend::LOGFILE_DATA:
$filename = 'data.txt';
$mode = 'a';
break;
default:
// Unkown type. Use $type as filename:
$filename = $type;
$mode = 'a';
break;
}
if ($type === Horde_SyncMl_Backend::LOGFILE_CLIENTMESSAGE ||
$type === Horde_SyncMl_Backend::LOGFILE_SERVERMESSAGE) {
$packetNum = @intval(file_get_contents($this->_debugDir
. '/packetnum.txt'));
if (empty($packetNum)) {
$packetNum = 10;
}
if ($wbxml) {
$filename .= $packetNum . '.wbxml';
} else {
$filename .= $packetNum . '.xml';
}
}
/* Write file */
$fp = @fopen($this->_debugDir . '/' . $filename, $mode);
if ($fp) {
@fwrite($fp, $content);
@fclose($fp);
}
if ($type === Horde_SyncMl_Backend::LOGFILE_CLIENTMESSAGE) {
$this->logMessage('Started at ' . date('Y-m-d H:i:s')
. '. Packet logged in '
. $this->_debugDir . '/' . $filename, 'DEBUG');
}
/* Increase packet number. */
if ($type === Horde_SyncMl_Backend::LOGFILE_SERVERMESSAGE) {
$this->logMessage('Finished at ' . date('Y-m-d H:i:s')
. '. Packet logged in '
. $this->_debugDir . '/' . $filename, 'DEBUG');
$fp = @fopen($this->_debugDir . '/packetnum.txt', 'w');
if ($fp) {
/* When one complete session is finished: go to next 10th. */
if ($sessionClose) {
$packetNum += 10 - $packetNum % 10;
} else {
$packetNum += 1;
}
fwrite($fp, $packetNum);
fclose($fp);
}
}
}
/**
* Cleanup public function called after all message processing is finished.
*
* Allows for things like closing databases or flushing logs. When
* running in test mode, tearDown() must be called rather than close.
*/
public function close()
{
if (!empty($this->_debugDir)) {
$f = @fopen($this->_debugDir . '/log.txt', 'a');
if ($f) {
fwrite($f, $this->_logtext . "\n");
fclose($f);
}
}
session_write_close();
}
/**
* Returns the current timestamp in the same format as used by
* getServerChanges().
*
* Backends can use their own way to represent timestamps, like unix epoch
* integers or UTC Datetime strings.
*
* @return mixed A timestamp of the current time.
*/
public function getCurrentTimeStamp()
{
/* Use unix epoch as default method for timestamps. */
return time();
}
/**
* Creates a clean test environment in the backend.
*
* Ensures there's a user with the given credentials and an empty data
* store.
*
* @abstract
*
* @param string $user This user accout has to be created in the backend.
* @param string $pwd The password for user $user.
*/
public function testSetup($user, $pwd)
{
die('testSetup() not implemented!');
}
/**
* Prepares the test start.
*
* @param string $user This user accout has to be created in the backend.
*/
public function testStart($user)
{
die('testStart() not implemented!');
}
/**
* Tears down the test environment after the test is run.
*
* @abstract
*
* Should remove the testuser created during testSetup and all its data.
*/
public function testTearDown()
{
die('testTearDown() not implemented!');
}
/**
* Normalizes a databaseURI to a database name, so that
* _normalize('tasks?ignorecompleted') should return just 'tasks'.
*
* @param string $databaseURI URI of a database. Like calendar, tasks,
* contacts or notes. May include optional
* parameters:
* tasks?options=ignorecompleted.
*
* @return string The normalized database name.
*/
public function normalize($databaseURI)
{
$database = Horde_String::lower(
basename(preg_replace('|\?.*$|', '', $databaseURI)));
/* Convert some commonly encountered types to a fixed set of known
* service names: */
switch($database) {
case 'contacts':
case 'contact':
case 'card':
case 'scard':
return 'contacts';
case 'calendar':
case 'event':
case 'events':
case 'cal':
case 'scal':
return 'calendar';
case 'notes':
case 'memo':
case 'note':
case 'snote':
return 'notes';
case 'tasks':
case 'task':
case 'stask':
return 'tasks';
default:
return $database;
}
}
/**
* Extracts an HTTP GET like parameter from an URL.
*
* Example: getParameter('test?q=1', 'q') == 1
*
* @static
*
* @param string $url The complete URL.
* @param string $parameter The parameter name to extract.
* @param string $default A default value to return if none has been
* provided in the URL.
*/
public function getParameter($url, $parameter, $default = null)
{
if (preg_match('|[&\?]' . $parameter . '=([^&]*)|', $url, $m)) {
return $m[1];
}
return $default;
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Backend/ 0000775 0000000 0000000 00000000000 12130076041 0024226 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Backend/Horde.php 0000664 0000000 0000000 00000104004 12130076041 0025777 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
class Horde_SyncMl_Backend_Horde extends Horde_SyncMl_Backend
{
/**
* A database instance.
*
* @var Horde_Db_Adapter_Base
*/
protected $_db;
/**
* The session ID used in the Horde session.
*
* @var string
*/
protected $_sessionId;
/**
* Constructor.
*
* Initializes the logger.
*
* @param array $params Any parameters the backend might need.
*/
public function __construct($params)
{
parent::__construct($params);
$this->_db = $GLOBALS['injector']->getInstance('Horde_Core_Factory_Db')->create();
}
/**
* Sets the user used for this session.
*
* @param string $user A user name.
*/
public function setUser($user)
{
parent::setUser($user);
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_TEST) {
/* After a session the user gets automatically logged out, so we
* have to login again. */
$GLOBALS['registry']->setAuth($this->_user, array());
}
}
/**
* Starts a PHP session.
*
* @param string $syncDeviceID The device ID.
* @param string $session_id The session ID to use.
* @param integer $backendMode The backend mode, one of the
* Horde_SyncMl_Backend::MODE_* constants.
*/
public function sessionStart($syncDeviceID, $sessionId,
$backendMode = Horde_SyncMl_Backend::MODE_SERVER)
{
$this->_backendMode = $backendMode;
$this->_syncDeviceID = $syncDeviceID;
$this->_sessionId = md5($syncDeviceID . $sessionId);
/* Only the server needs to start a session. */
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
/* Reload the Horde SessionHandler if necessary. */
$GLOBALS['session'] = new Horde_Session();
$GLOBALS['session']->destroy();
$GLOBALS['session']->setup(true, null, $this->_sessionId);
$this->state = $GLOBALS['session']->get('horde', 'syncml');
}
}
public function close()
{
if ($this->state) {
$GLOBALS['session']->set('horde', 'syncml', $this->state);
}
$GLOBALS['session']->close();
parent::close();
}
protected function _fastsync($databaseURI, $from_ts, $to_ts)
{
global $registry;
$results = array(
'adds' => array(),
'mods' => array(),
'dels' => array());
$map = array(
'adds' => 'add',
'dels' => 'delete',
'mods' => 'modify');
$database = $this->normalize($databaseURI);
// Get ALL server changes from backend
try {
$changes = $registry->{$database}->getChanges($from_ts, $to_ts);
} catch (Horde_Exception $e) {
$this->logMessage(
sprintf(
' %s getChanges() failed during _fastSync: %s', $database, $e->getMessage()),
'ERR');
}
$add_ts = array();
foreach (array_keys($results) as $type) {
foreach ($changes[$map[$type]] as $suid) {
// Only server needs to check for client sent entries:
if ($this->_backendMode != Horde_SyncMl_Backend::MODE_SERVER) {
switch ($type) {
case 'adds':
$id = 0;
break;
case 'mods':
case 'dels':
$id = $suid;
}
$results[$type][$suid] = $id;
continue;
}
try {
$change_ts = $registry->{$database}->getActionTimestamp(
$suid, $map[$type], Horde_SyncMl_Backend::getParameter($databaseURI, 'source'));
} catch (Horde_Exception $e) {
$this->logMessage($e->getMessage(), 'ERR');
return;
}
// If added, then deleted all since last sync, don't bother
// sending change
if ($type == 'adds') {
$add_ts[$suid] = $change_ts;
} elseif ($type == 'dels') {
if (isset($results['adds'][$suid]) && $add_ts[$suid] < $change_ts) {
unset($results['adds'][$suid]);
continue;
}
if (isset($results['mods'][$suid])) {
unset($results['mods'][$suid]);
}
}
$sync_ts = $this->_getChangeTS($database, $suid);
if ($sync_ts && $sync_ts >= $change_ts) {
// Change was done by us upon request of client. Don't
// mirror that back to the client.
$this->logMessage(
"Added to server from client: $suid ignored", 'DEBUG');
continue;
}
// Sanity check and prepare list of changes
if ($type != 'adds') {
$cuid = $this->_getCuid($database, $suid);
if (empty($cuid) && $type == 'mods') {
$this->logMessage(
"Unable to create change for server id $suid: client id not found in map, adding instead.", 'WARN');
$results['adds'][$suid] = 0;
continue;
} elseif (empty($cuid) && $type == 'dels') {
$this->logMessage(
"Unable to create delete for server id $suid: client id not found in map", 'WARN');
continue;
} else {
$id = $cuid;
}
} else {
$id = 0;
}
$results[$type][$suid] = $id;
}
}
return $results;
}
protected function _slowsync($databaseURI, $from_ts, $to_ts)
{
global $registry;
$results = array(
'adds' => array(),
'dels' => array(),
'mods' => array());
$database = $this->normalize($databaseURI);
// Return all db entries directly rather than bother history. But
// first check if we only want to sync data from a given start
// date:
$start = trim(Horde_SyncMl_Backend::getParameter($databaseURI, 'start'));
try {
if (!empty($start)) {
if (strlen($start) == 4) {
$start .= '0101000000';
} elseif (strlen($start) == 6) {
$start .= '01000000';
} elseif (strlen($start) == 8) {
$start .= '000000';
}
$start = new Horde_Date($start);
$this->logMessage('Slow-syncing all events starting from ' . (string)$start, 'DEBUG');
$data = $registry->{$database}->listUids(
Horde_SyncMl_Backend::getParameter($databaseURI, 'source'), $start);
} else {
$data = $registry->{$database}->listUids(
Horde_SyncMl_Backend::getParameter($databaseURI, 'source'));
}
} catch (Horde_Exception $e) {
$this->logMessage(
"$database/list or $database/listBy failed while retrieving server additions:"
. $e->getMessage(), 'ERR');
return;
}
foreach ($data as $suid) {
// Only server needs to check for client sent entries:
if ($this->_backendMode != Horde_SyncMl_Backend::MODE_SERVER) {
$results['adds'][$suid] = 0;
continue;
}
// Ignore if a map entry is present
$cuid = $this->_getCuid($database, $suid);
if ($cuid) {
$this->logMessage(
"Added to server from client during SlowSync: $suid ignored", 'DEBUG');
continue;
}
try {
$add_ts = $registry->{$database}->getActionTimestamp(
$suid,
'add',
Horde_SyncMl_Backend::getParameter($databaseURI, 'source'));
} catch (Horde_Exception $e) {
$this->logMessage($e->getMessage(), 'ERR');
return;
}
$sync_ts = $this->_getChangeTS($database, $suid);
if ($sync_ts && $sync_ts >= $add_ts) {
// Change was done by us upon request of client. Don't mirror
// that back to the client.
$this->logMessage("Added to server from client: $suid ignored", 'DEBUG');
continue;
}
$this->logMessage(
"Adding to client from db $database, server id $suid", 'DEBUG');
$results['adds'][$suid] = 0;
}
return $results;
}
/**
* Returns entries that have been modified in the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param integer $from_ts Start timestamp.
* @param integer $to_ts Exclusive end timestamp. Not yet
* implemented.
* @param array &$adds Output array: hash of adds suid => 0
* @param array &$mods Output array: hash of modifications
* suid => cuid
* @param array &$dels Output array: hash of deletions suid => cuid
*
* @return boolean true
*/
public function getServerChanges($databaseURI, $from_ts, $to_ts, &$adds, &$mods,
&$dels)
{
global $registry;
$slowsync = $from_ts == 0;
if ($slowsync) {
$results = $this->_slowsync($databaseURI, $from_ts, $to_ts);
} else {
$results = $this->_fastSync($databaseURI, $from_ts, $to_ts);
}
$adds = $results['adds'];
$mods = $results['mods'];
$dels = $results['dels'];
// @TODO: No need to return true, since errors are now thrown. H5 should
// remove this.
return true;
}
/**
* Retrieves an entry from the backend.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid Server unique id of the entry: for horde
* this is the guid.
* @param string $contentType Content-Type: the MIME type in which the
* public function should return the data.
* @param array $fields Hash of field names and Horde_SyncMl_Property
* properties with the requested fields.
*
* @return mixed A string with the data entry or a PEAR_Error object.
*/
public function retrieveEntry($databaseURI, $suid, $contentType, $fields)
{
try {
return $GLOBALS['registry']->call(
$this->normalize($databaseURI) . '/export',
array('guid' => $suid, 'contentType' => $contentType, 'dummy' => null, 'fields' => $fields));
} catch (Horde_Exception $e) {
return PEAR::raiseError($e->getMessage());
}
}
/**
* Adds an entry into the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $cuid Client ID of this entry.
*
* @return array PEAR_Error or suid (Horde guid) of new entry
*/
public function addEntry($databaseURI, $content, $contentType, $cuid = null)
{
global $registry;
$database = $this->normalize($databaseURI);
try {
$suid = $registry->call(
$database . '/import',
array($content,
$contentType,
Horde_SyncMl_Backend::getParameter($databaseURI, 'source')));
$this->logMessage(
"Added to server db $database client id $cuid -> server id $suid", 'DEBUG');
$ts = $registry->call(
$database . '/getActionTimestamp',
array($suid,
'add',
Horde_SyncMl_Backend::getParameter($databaseURI, 'source')));
if (!$ts) {
$this->logMessage(
"Unable to find addition timestamp for server id $suid at $ts", 'ERR');
}
// Only server needs to do a cuid<->suid map
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$this->createUidMap($database, $cuid, $suid, $ts);
}
} catch (Horde_Exception $e) {
// Failed import. Maybe the entry is already there. Check if a
// guid is returned:
/* Not working with exceptions
if ($suid->getDebugInfo()) {
$suid = $suid->getDebugInfo();
$this->logMessage(
'Adding client entry to server: already exists with server id ' . $suid, 'NOTICE');
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$this->createUidMap($database, $cuid, $suid, 0);
}
}
*/
}
return $suid;
}
/**
* Replaces an entry in the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $cuid Client ID of this entry.
*
* @return string PEAR_Error or server ID (Horde GUID) of modified entry.
*/
public function replaceEntry($databaseURI, $content, $contentType, $cuid)
{
global $registry;
$database = $this->normalize($databaseURI);
// Only server needs to do a cuid<->suid map
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$suid = $this->_getSuid($database, $cuid);
} else {
$suid = $cuid;
}
if (!$suid) {
return PEAR::raiseError("No map entry found for client id $cuid replacing on server");
}
// Entry exists: replace current one.
try {
$ok = $registry->call($database . '/replace',
array($suid, $content, $contentType));
} catch (Horde_Exception $e) {
return PEAR::raiseError($e->getMessage());
}
$this->logMessage(
"Replaced in server db $database client id $cuid -> server id $suid", 'DEBUG');
$ts = $registry->call(
$database . '/getActionTimestamp',
array($suid,
'modify',
Horde_SyncMl_Backend::getParameter($databaseURI,'source')));
// Only server needs to do a cuid<->suid map
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$this->createUidMap($database, $cuid, $suid, $ts);
}
return $suid;
}
/**
* Deletes an entry from the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid Client ID of the entry.
*
* @return boolean True on success or false on failed (item not found).
*/
public function deleteEntry($databaseURI, $cuid)
{
global $registry;
$database = $this->normalize($databaseURI);
// Find server ID for this entry:
// Only server needs to do a cuid<->suid map
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
try {
$suid = $this->_getSuid($database, $cuid);
} catch (Horde_Exception $e) {
return false;
}
} else {
$suid = $cuid;
}
if (empty($suid) || is_a($suid, 'PEAR_Error')) {
return false;
}
try {
$registry->call($database. '/delete', array($suid));
} catch (Horde_Exception $e) {
return false;
}
$this->logMessage(
"Deleted in server db $database client id $cuid -> server id $suid", 'DEBUG');
$ts = $registry->call($database . '/getActionTimestamp',
array($suid, 'delete'));
// We can't remove the mapping entry as we need to keep the timestamp
// information.
// Only server needs to do a cuid<->suid map
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$this->createUidMap($database, $cuid, $suid, $ts);
}
return true;
}
/**
* Authenticates the user at the backend.
*
* @param string $username A user name.
* @param string $password A password.
*
* @return boolean|string The user name if authentication succeeded, false
* otherwise.
*/
protected function _checkAuthentication($username, $password)
{
$auth = $GLOBALS['injector']
->getInstance('Horde_Core_Factory_Auth')
->create()
->authenticate($username, array('password' => $password))
? $GLOBALS['registry']->getAuth()
: false;
/* Horde is regenerating the session id at login, but we need to keep
* our own, predictable session to not lose state. */
session_id($this->_sessionId);
return $auth;
}
/**
* Sets a user as being authenticated at the backend.
*
* @abstract
*
* @param string $username A user name.
* @param string $credData Authentication data provided by
* in the .
*
* @return string The user name.
*/
protected function _setAuthenticated($username, $credData)
{
global $registry;
$registry->setAuth($username, $credData);
return $registry->getAuth();
}
/**
* Stores Sync anchors after a successful synchronization to allow two-way
* synchronization next time.
*
* The backend has to store the parameters in its persistence engine
* where user, syncDeviceID and database are the keys while client and
* server anchor ar the payload. See readSyncAnchors() for retrieval.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $clientAnchorNext The client anchor as sent by the
* client.
* @param string $serverAnchorNext The anchor as used internally by the
* server.
*/
public function writeSyncAnchors($databaseURI, $clientAnchorNext,
$serverAnchorNext)
{
$database = $this->normalize($databaseURI);
$values = array($clientAnchorNext, $serverAnchorNext,
$this->_syncDeviceID, $database, $this->_user);
if (!$this->readSyncAnchors($databaseURI)) {
$query = 'INSERT INTO horde_syncml_anchors '
. '(syncml_clientanchor, syncml_serveranchor, '
. 'syncml_syncpartner, syncml_db, syncml_uid) '
. 'VALUES (?, ?, ?, ?, ?)';
$this->_db->insert($query, $values);
} else {
$query = 'UPDATE horde_syncml_anchors '
. 'SET syncml_clientanchor = ?, syncml_serveranchor = ? '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ?';
$this->_db->update($query, $values);
}
}
/**
* Reads the previously written sync anchors from the database.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
*
* @return mixed Two-element array with client anchor and server anchor as
* stored in previous writeSyncAnchor() calls. False if no
* data found.
*/
public function readSyncAnchors($databaseURI)
{
$database = $this->normalize($databaseURI);
$query = 'SELECT syncml_clientanchor, syncml_serveranchor '
. 'FROM horde_syncml_anchors '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ?';
$values = array($this->_syncDeviceID, $database, $this->_user);
try {
if ($res = $this->_db->selectOne($query, $values)) {
return array(
$res['syncml_clientanchor'],
$res['syncml_serveranchor']
);
}
} catch (Horde_Db_Exception $e) {}
return false;
}
/**
* Returns all previously written sync anchors for a user.
*
* @param string $user A user name.
*
* @return array A hash tree with all devices, databases and sync anchors
* from the specified user.
*/
public function getUserAnchors($user)
{
$query = 'SELECT syncml_syncpartner, syncml_db, syncml_clientanchor, '
. 'syncml_serveranchor FROM horde_syncml_anchors '
. 'WHERE syncml_uid = ?';
$values = array($user);
return $this->_db->selectAll($query, $values);
}
/**
* Deletes previously written sync anchors for a user.
*
* If no device or database are specified, anchors for all devices and/or
* databases will be deleted.
*
* @param string $user A user name.
* @param string $device The ID of the client device.
* @param string $database Normalized URI of database to delete. Like
* calendar, tasks, contacts or notes.
*
* @return array
*/
public function removeAnchor($user, $device = null, $database = null)
{
$query = 'DELETE FROM horde_syncml_anchors WHERE syncml_uid = ?';
$values = array($user);
if (strlen($device)) {
$query .= ' AND syncml_syncpartner = ?';
$values[] = $device;
}
if (strlen($database)) {
$query .= ' AND syncml_db = ?';
$values[] = $database;
}
$this->_db->delete($query, $values);
}
/**
* Deletes previously written sync maps for a user.
*
* If no device or database are specified, maps for all devices and/or
* databases will be deleted.
*
* @param string $user A user name.
* @param string $device The ID of the client device.
* @param string $database Normalized URI of database to delete. Like
* calendar, tasks, contacts or notes.
*
* @return array
*/
public function removeMaps($user, $device = null, $database = null)
{
$query = 'DELETE FROM horde_syncml_map WHERE syncml_uid = ?';
$values = array($user);
if (strlen($device)) {
$query .= ' AND syncml_syncpartner = ?';
$values[] = $device;
}
if (strlen($database)) {
$query .= ' AND syncml_db = ?';
$values[] = $database;
}
$this->_db->delete($query, $values);
}
/**
* Creates a map entry to map between server and client IDs.
*
* If an entry already exists, it is overwritten.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid Client ID of the entry.
* @param string $suid Server ID of the entry.
* @param integer $timestamp Optional timestamp. This can be used to
* 'tag' changes made in the backend during the
* sync process. This allows to identify these,
* and ensure that these changes are not
* replicated back to the client (and thus
* duplicated). See key concept "Changes and
* timestamps".
*/
public function createUidMap($databaseURI, $cuid, $suid, $timestamp = 0)
{
$database = $this->normalize($databaseURI);
$values = array($suid, (int)$timestamp, $this->_syncDeviceID,
$database, $this->_user, $cuid);
// Check if entry exists. If not insert, otherwise update.
if (!$this->_getSuid($databaseURI, $cuid)) {
$query = 'INSERT INTO horde_syncml_map '
. '(syncml_suid, syncml_timestamp, syncml_syncpartner, '
. 'syncml_db, syncml_uid, syncml_cuid) '
. 'VALUES (?, ?, ?, ?, ?, ?)';
$this->_db->insert($query, $values);
} else {
$query = 'UPDATE horde_syncml_map '
. 'SET syncml_suid = ?, syncml_timestamp = ? '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ? AND syncml_cuid = ?';
$this->_db->update($query, $values);
}
}
/**
* Retrieves the Server ID for a given Client ID from the map.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid The client ID.
*
* @return mixed The server ID string or false if no entry is found.
*/
protected function _getSuid($databaseURI, $cuid)
{
$database = $this->normalize($databaseURI);
$query = 'SELECT syncml_suid FROM horde_syncml_map '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ? AND syncml_cuid = ?';
$values = array($this->_syncDeviceID, $database, $this->_user, $cuid);
return $this->_db->selectValue($query, $values);
}
/**
* Retrieves the Client ID for a given Server ID from the map.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid The server ID.
*
* @return mixed The client ID string or false if no entry is found.
*/
protected function _getCuid($databaseURI, $suid)
{
$database = $this->normalize($databaseURI);
$query = 'SELECT syncml_cuid FROM horde_syncml_map '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ? AND syncml_suid = ?';
$values = array($this->_syncDeviceID, $database, $this->_user, $suid);
return $this->_db->selectValue($query, $values);
}
/**
* Returns a timestamp stored in the map for a given Server ID.
*
* The timestamp is the timestamp of the last change to this server ID
* that was done inside a sync session (as a result of a change received
* by the server). It's important to distinguish changes in the backend a)
* made by the user during normal operation and b) changes made by SyncML
* to reflect client updates. When the server is sending its changes it
* is only allowed to send type a). However the history feature in the
* backend my not know if a change is of type a) or type b). So the
* timestamp is used to differentiate between the two.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid The server ID.
*
* @return mixed The previously stored timestamp or false if no entry is
* found.
*/
protected function _getChangeTS($databaseURI, $suid)
{
$database = $this->normalize($databaseURI);
$query = 'SELECT syncml_timestamp FROM horde_syncml_map '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ? AND syncml_suid = ?';
$values = array($this->_syncDeviceID, $database, $this->_user, $suid);
return $this->_db->selectValue($query, $values);
}
/**
* Erases all mapping entries for one combination of user, device ID.
*
* This is used during SlowSync so that we really sync everything properly
* and no old mapping entries remain.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
*/
public function eraseMap($databaseURI)
{
$database = $this->normalize($databaseURI);
$query = 'DELETE FROM horde_syncml_map '
. 'WHERE syncml_syncpartner = ? AND syncml_db = ? AND '
. 'syncml_uid = ?';
$values = array($this->_syncDeviceID, $database, $this->_user);
$this->_db->delete($query, $values);
}
/**
* Logs a message in the backend.
*
* @param mixed $message Either a string or a PEAR_Error object.
* @param string $priority The priority of the message. One of:
* - EMERG
* - ALERT
* - CRIT
* - ERR
* - WARN
* - NOTICE
* - INFO
* - DEBUG
*/
public function logMessage($message, $priority = 'INFO')
{
$trace = debug_backtrace();
$trace = $trace[1];
// Internal logging to $this->_logtext.
parent::logMessage($message, $priority);
// Logging to Horde log:
Horde::logMessage($message, $priority, array('file' => $trace['file'], 'line' => $trace['line']));
}
/**
* Creates a clean test environment in the backend.
*
* Ensures there's a user with the given credentials and an empty data
* store.
*
* @param string $user This user accout has to be created in the backend.
* @param string $pwd The password for user $user.
*
* @throws Horde_Exception
*/
public function testSetup($user, $pwd)
{
$this->_user = $user;
if (empty($pwd)) {
$pwd = rand() . rand();
}
/* Get an Auth object. */
$auth = $GLOBALS['injector']->getInstance('Horde_Core_Factory_Auth')->create();
/* Make this user an admin for the time beeing to allow deletion of
* user data. */
$GLOBALS['conf']['auth']['admins'][] = $user;
/* Always remove test user first. */
if ($auth->exists($user)) {
$GLOBALS['registry']->removeUser($user);
}
$auth->addUser($user, array('password' => $pwd));
}
/**
* Prepares the test start.
*
* @param string $user This user accout has to be created in the backend.
*/
public function testStart($user)
{
$this->_user = $user;
/* Make this user an admin for the time beeing to allow deletion of
* user data. */
$GLOBALS['conf']['auth']['admins'][] = $user;
$GLOBALS['registry']->setAuth($user, array());
}
/**
* Tears down the test environment after the test is run.
*
* Should remove the testuser created during testSetup and all its data.
*/
public function testTearDown()
{
/* Get an Auth object. */
try {
$auth = $GLOBALS['injector']->getInstance('Horde_Core_Factory_Auth')->create();
} catch (Horde_Exception $e) {
// TODO
}
/* We need to be logged in to call removeUserData, otherwise we run
* into permission issues. */
$GLOBALS['registry']->setAuth($this->_user, array());
print "\nCleaning up: removing test user data and test user...";
$registry->removeUser($this->_user);
print "OK\n";
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Backend/Sql.php 0000664 0000000 0000000 00000126045 12130076041 0025506 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
/*
* The SQL Database must contain five tables as created by the following SQL
* script:
*
* CREATE DATABASE syncml;
*
* USE syncml;
*
* CREATE TABLE syncml_data(
* syncml_id VARCHAR(255),
* syncml_db VARCHAR(255),
* syncml_uid VARCHAR(255),
* syncml_data TEXT,
* syncml_contenttype VARCHAR(255),
* syncml_created_ts INTEGER,
* syncml_modified_ts INTEGER
* );
*
* CREATE TABLE syncml_map(
* syncml_syncpartner VARCHAR(255),
* syncml_db VARCHAR(255),
* syncml_uid VARCHAR(255),
* syncml_cuid VARCHAR(255),
* syncml_suid VARCHAR(255),
* syncml_timestamp INTEGER
* );
*
* CREATE INDEX syncml_syncpartner_idx ON syncml_map (syncml_syncpartner);
* CREATE INDEX syncml_db_idx ON syncml_map (syncml_db);
* CREATE INDEX syncml_uid_idx ON syncml_map (syncml_uid);
* CREATE INDEX syncml_cuid_idx ON syncml_map (syncml_cuid);
* CREATE INDEX syncml_suid_idx ON syncml_map (syncml_suid);
*
* CREATE TABLE syncml_anchors(
* syncml_syncpartner VARCHAR(255),
* syncml_db VARCHAR(255),
* syncml_uid VARCHAR(255),
* syncml_clientanchor VARCHAR(255),
* syncml_serveranchor VARCHAR(255)
* );
*
* CREATE TABLE syncml_suidlist(
* syncml_syncpartner VARCHAR(255),
* syncml_db VARCHAR(255),
* syncml_uid VARCHAR(255),
* syncml_suid VARCHAR(255)
* );
*
* CREATE TABLE syncml_uids(
* syncml_uid VARCHAR(255),
* syncml_password VARCHAR(255)
* );
*/
/**
*/
class Horde_SyncMl_Backend_Sql extends Horde_SyncMl_Backend
{
/**
* A PEAR MDB2 instance.
*
* @var MDB2
*/
protected $_db;
/**
* Constructor.
*
* @param array $params A hash with parameters. In addition to those
* supported by the Horde_SyncMl_Backend class one more
* parameter is required for the database connection:
* 'dsn' => connection DSN.
*/
public function __construct($params)
{
parent::__construct($params);
$this->_db = &MDB2::connect($params['dsn']);
if (is_a($this->_db, 'PEAR_Error')) {
$this->logMessage($this->_db, 'ERR');
}
}
/**
* Returns whether a database URI is valid to be synced with this backend.
*
* @param string $databaseURI URI of a database. Like calendar, tasks,
* contacts or notes. May include optional
* parameters:
* tasks?options=ignorecompleted.
*
* @return boolean True if a valid URI.
*/
public function isValidDatabaseURI($databaseURI)
{
$database = $this->normalize($databaseURI);
switch($database) {
case 'tasks';
case 'calendar';
case 'notes';
case 'contacts';
case 'events':
case 'memo':
return true;
default:
$this->logMessage('Invalid database ' . $database
. '. Try tasks, calendar, notes or contacts.', 'ERR');
return false;
}
}
/**
* Returns entries that have been modified in the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param integer $from_ts Start timestamp.
* @param integer $to_ts Exclusive end timestamp. Not yet
* implemented.
* @param array &$adds Output array: hash of adds suid => 0
* @param array &$mods Output array: hash of modifications
* suid => cuid
* @param array &$dels Output array: hash of deletions suid => cuid
*
* @return mixed True on success or a PEAR_Error object.
*/
public function getServerChanges($databaseURI, $from_ts, $to_ts, &$adds, &$mods,
&$dels)
{
$database = $this->normalize($databaseURI);
$adds = $mods = $dels = array();
// Handle additions:
$data = $this->_db->queryAll(
'SELECT syncml_id, syncml_created_ts from syncml_data '
. 'WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_created_ts >= '
. $this->_db->quote($from_ts, 'integer')
. ' AND syncml_created_ts < '
. $this->_db->quote($to_ts, 'integer'));
if ($this->_checkForError($data)) {
return $data;
}
foreach ($data as $d) {
$suid = $d[0];
$suid_ts = $d[1];
$sync_ts = $this->_getChangeTS($databaseURI, $suid);
if ($sync_ts && $sync_ts >= $suid_ts) {
// Change was done by us upon request of client, don't mirror
// that back to the client.
$this->logMessage("Added to server from client: $suid ignored", 'DEBUG');
continue;
}
$adds[$suid] = 0;
}
// Only compile changes on delta sync:
if ($from_ts > 0) {
// Handle replaces. We might get IDs that are already in the adds
// array but that's ok: The calling code takes care to ignore
// these.
$data = $this->_db->queryAll(
'SELECT syncml_id, syncml_modified_ts from syncml_data '
.'WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_modified_ts >= '
. $this->_db->quote($from_ts, 'integer')
. ' AND syncml_modified_ts < '
. $this->_db->quote($to_ts, 'integer'));
if ($this->_checkForError($data)) {
return $data;
}
foreach($data as $d) {
// Only the server needs to check the change timestamp do
// identify client-sent changes.
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$suid = $d[0];
$suid_ts = $d[1];
$sync_ts = $this->_getChangeTS($databaseURI, $suid);
if ($sync_ts && $sync_ts >= $suid_ts) {
// Change was done by us upon request of client, don't
// mirror that back to the client.
$this->logMessage(
"Changed on server after sent from client: $suid ignored", 'DEBUG');
continue;
}
$mods[$suid] = $this->_getCuid($databaseURI, $suid);
} else {
$mods[$d[0]] = $d[0];
}
}
}
// Handle deletions:
// We assume stupid a backend datastore (syncml_data) where deleted
// items are simply "gone" from the datastore. So we need to do our
// own bookkeeping to identify entries that have been deleted since
// the last sync run.
// This is done by the _trackDeless() helper function: we feed it with
// a current list of all suids and get the ones missing (and thus
// deleted) in return.
$data = $this->_db->queryCol(
'SELECT syncml_id from syncml_data WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text'));
if ($this->_checkForError($data)) {
return $data;
}
// Get deleted items and store current items:
// Only use the deleted information on delta sync. On initial slowsync
// we just need to call _trackDeletes() once to init the list.
$data = $this->_trackDeletes($databaseURI, $data);
if ($this->_checkForError($data)) {
return $data;
}
if ($from_ts > 0) {
foreach($data as $suid) {
// Only the server needs to handle the cuid suid map:
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$dels[$suid] = $this->_getCuid($databaseURI, $suid);
} else {
$dels[$suid] = $suid;
}
}
}
}
/**
* Retrieves an entry from the backend.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid Server unique id of the entry: for horde
* this is the guid.
* @param string $contentType Content-Type: the MIME type in which the
* public function should return the data.
* @param array $fields Hash of field names and Horde_SyncMl_Property
* properties with the requested fields.
*
* @return mixed A string with the data entry or a PEAR_Error object.
*/
public function retrieveEntry($databaseURI, $suid, $contentType, $fields)
{
$database = $this->normalize($databaseURI);
return $this->_db->queryOne(
'SELECT syncml_data from syncml_data '
. 'WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_id = '
. $this->_db->quote($suid, 'text'));
}
/**
* Adds an entry into the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $cuid Client ID of this entry.
*
* @return array PEAR_Error or suid (Horde guid) of new entry
*/
public function addEntry($databaseURI, $content, $contentType, $cuid = null)
{
$database = $this->normalize($databaseURI);
// Generate an id (suid). It's also possible to use a database
// generated primary key here.
$suid = strval(new Horde_Support_Uuid());
$created_ts = $this->getCurrentTimeStamp();
$r = $this->_db->exec(
'INSERT INTO syncml_data (syncml_id, syncml_db, syncml_uid, '
. 'syncml_data, syncml_contenttype, syncml_created_ts, '
. 'syncml_modified_ts) VALUES ('
. $this->_db->quote($suid, 'text') . ','
. $this->_db->quote($database, 'text') . ','
. $this->_db->quote($this->_user, 'text') . ','
. $this->_db->quote($content, 'text') . ','
. $this->_db->quote($contentType, 'text') . ','
. $this->_db->quote($created_ts, 'integer') . ','
. $this->_db->quote($created_ts, 'integer')
. ')');
if ($this->_checkForError($r)) {
return $r;
}
// Only the server needs to handle the cuid suid map:
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$this->createUidMap($databaseURI, $cuid, $suid, $created_ts);
}
}
/**
* Replaces an entry in the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $cuid Client ID of this entry.
*
* @return string PEAR_Error or server ID (Horde GUID) of modified entry.
*/
public function replaceEntry($databaseURI, $content, $contentType, $cuid)
{
$database = $this->normalize($databaseURI);
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$suid = $this->_getSuid($databaseURI, $cuid);
} else {
$suid = $cuid;
}
if ($suid) {
// Entry exists: replace current one.
$modified_ts = $this->getCurrentTimeStamp();
$r = $this->_db->exec(
'UPDATE syncml_data '
. 'SET syncml_modified_ts = '
. $this->_db->quote($modified_ts, 'integer')
. ', syncml_data = '
. $this->_db->quote($content, 'text')
. ', syncml_contenttype = '
. $this->_db->quote($contentType, 'text')
. 'WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_id = '
. $this->_db->quote($suid, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
// Only the server needs to keep the map:
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$this->createUidMap($databaseURI, $cuid, $suid, $modified_ts);
}
} else {
return PEAR::raiseError("No map entry found for client id $cuid replacing on server");
}
return $suid;
}
/**
* Deletes an entry from the server database.
*
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid Client ID of the entry.
*
* @return boolean True on success or false on failed (item not found).
*/
public function deleteEntry($databaseURI, $cuid)
{
$database = $this->normalize($databaseURI);
// Find ID for this entry:
if ($this->_backendMode == Horde_SyncMl_Backend::MODE_SERVER) {
$suid = $this->_getSuid($databaseURI, $cuid);
} else {
$suid = $cuid;
}
if (!is_a($suid, 'PEAR_Error')) {
// A clever backend datastore would store some information about a
// deletion so this information can be extracted from the history.
// However we do a "stupid" datastore here where deleted items are
// simply gone. This allows us to illustrate the _trackDeletes()
// bookkeeping mechanism.
$r = $this->_db->queryOne(
'DELETE FROM syncml_data '
. ' WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_id = '
. $this->_db->quote($suid, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
// Deleted bookkeeping is required for server and client, but not
// for test mode:
if ($this->_backendMode != Horde_SyncMl_Backend::MODE_TEST) {
$this->_removeFromSuidList($databaseURI, $suid);
}
// @todo: delete from map!
} else {
return false;
}
if (is_a($r, 'PEAR_Error')) {
return false;
}
return true;
}
/**
* Authenticates the user at the backend.
*
* @param string $username A user name.
* @param string $password A password.
*
* @return boolean|string The user name if authentication succeeded, false
* otherwise.
*/
protected function _checkAuthentication($username, $password)
{
// Empty passwords result in errors for some authentication
// backends, don't call the backend in this case.
if ($pwd === '') {
return false;
}
$r = $this->_db->queryOne(
'SELECT syncml_uid FROM syncml_uids'
. ' WHERE syncml_uid = '
. $this->_db->quote($username, 'text')
. ' AND syncml_password = '
. $this->_db->quote($pwd, 'text'));
$this->_checkForError($r);
if ($r === $username) {
return $username;
}
return false;
}
/**
* Sets a user as being authenticated at the backend.
*
* @abstract
*
* @param string $username A user name.
* @param string $credData Authentication data provided by
* in the .
*
* @return string The user name.
*/
protected function _setAuthenticated($username, $credData)
{
return $username;
}
/**
* Stores Sync anchors after a successful synchronization to allow two-way
* synchronization next time.
*
* The backend has to store the parameters in its persistence engine
* where user, syncDeviceID and database are the keys while client and
* server anchor ar the payload. See readSyncAnchors() for retrieval.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $clientAnchorNext The client anchor as sent by the
* client.
* @param string $serverAnchorNext The anchor as used internally by the
* server.
*/
public function writeSyncAnchors($databaseURI, $clientAnchorNext,
$serverAnchorNext)
{
$database = $this->normalize($databaseURI);
// Check if entry exists. If not insert, otherwise update.
if (!$this->readSyncAnchors($databaseURI)) {
$r = $this->_db->exec(
'INSERT INTO syncml_anchors (syncml_syncpartner, '
. 'syncml_db,syncml_uid, syncml_clientanchor, '
. 'syncml_serveranchor) VALUES ('
. $this->_db->quote($this->_syncDeviceID, 'text') . ', '
. $this->_db->quote($database, 'text') . ', '
. $this->_db->quote($this->_user, 'text') . ', '
. $this->_db->quote($clientAnchorNext, 'text') . ', '
. $this->_db->quote($serverAnchorNext, 'text')
. ')');
} else {
$r = $this->_db->exec(
'UPDATE syncml_anchors '
. ' SET syncml_clientanchor = '
. $this->_db->quote($clientAnchorNext, 'text')
. ', syncml_serveranchor = '
. $this->_db->quote($serverAnchorNext, 'text')
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text'));
}
if ($this->_checkForError($r)) {
return $r;
}
return true;
}
/**
* Reads the previously written sync anchors from the database.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
*
* @return mixed Two-element array with client anchor and server anchor as
* stored in previous writeSyncAnchor() calls. False if no
* data found.
*/
public function readSyncAnchors($databaseURI)
{
$database = $this->normalize($databaseURI);
$r = $this->_db->queryRow(
'SELECT syncml_clientanchor, syncml_serveranchor '
. 'FROM syncml_anchors WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text'));
$this->_checkForError($r);
if (!is_array($r)) {
return false;
}
return array($r[0], $r[1]);
}
/**
* Creates a map entry to map between server and client IDs.
*
* If an entry already exists, it is overwritten.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid Client ID of the entry.
* @param string $suid Server ID of the entry.
* @param integer $timestamp Optional timestamp. This can be used to
* 'tag' changes made in the backend during the
* sync process. This allows to identify these,
* and ensure that these changes are not
* replicated back to the client (and thus
* duplicated). See key concept "Changes and
* timestamps".
*/
public function createUidMap($databaseURI, $cuid, $suid, $timestamp = 0)
{
$database = $this->normalize($databaseURI);
// Check if entry exists. If not insert, otherwise update.
if (!$this->_getSuid($databaseURI, $cuid)) {
$r = $this->_db->exec(
'INSERT INTO syncml_map (syncml_syncpartner, '
. 'syncml_db, syncml_uid, syncml_cuid, syncml_suid, '
. 'syncml_timestamp) VALUES ('
. $this->_db->quote($this->_syncDeviceID, 'text') . ', '
. $this->_db->quote($database, 'text') . ', '
. $this->_db->quote($this->_user, 'text') . ', '
. $this->_db->quote($cuid, 'text') . ', '
. $this->_db->quote($suid, 'text') . ', '
. $this->_db->quote($timestamp, 'integer')
. ')');
} else {
$r = $this->_db->exec(
'UPDATE syncml_map SET syncml_suid = '
. $this->_db->quote($suid, 'text')
. ', syncml_timestamp = '
. $this->_db->quote($timestamp, 'text')
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_cuid = '
. $this->_db->quote($cuid, 'text'));
}
if ($this->_checkForError($r)) {
return $r;
}
return true;
}
/**
* Retrieves the Server ID for a given Client ID from the map.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $cuid The client ID.
*
* @return mixed The server ID string or false if no entry is found.
*/
protected function _getSuid($databaseURI, $cuid)
{
$database = $this->normalize($databaseURI);
$r = $this->_db->queryOne(
'SELECT syncml_suid FROM syncml_map '
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_cuid = '
. $this->_db->quote($cuid, 'text'));
$this->_checkForError($r);
if (!empty($r)) {
return $r;
}
return false;
}
/**
* Retrieves the Client ID for a given Server ID from the map.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid The server ID.
*
* @return mixed The client ID string or false if no entry is found.
*/
protected function _getCuid($databaseURI, $suid)
{
$database = $this->normalize($databaseURI);
$r = $this->_db->queryOne(
'SELECT syncml_cuid FROM syncml_map '
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_suid = '
. $this->_db->quote($suid, 'text'));
$this->_checkForError($r);
if (!empty($r)) {
return $r;
}
return false;
}
/**
* Returns a timestamp stored in the map for a given Server ID.
*
* The timestamp is the timestamp of the last change to this server ID
* that was done inside a sync session (as a result of a change received
* by the server). It's important to distinguish changes in the backend a)
* made by the user during normal operation and b) changes made by SyncML
* to reflect client updates. When the server is sending its changes it
* is only allowed to send type a). However the history feature in the
* backend my not know if a change is of type a) or type b). So the
* timestamp is used to differentiate between the two.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid The server ID.
*
* @return mixed The previously stored timestamp or false if no entry is
* found.
*/
protected function _getChangeTS($databaseURI, $suid)
{
$database = $this->normalize($databaseURI);
$r = $this->_db->queryOne(
'SELECT syncml_timestamp FROM syncml_map '
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_suid = '
. $this->_db->quote($suid, 'text'));
$this->_checkForError($r);
if (!empty($r)) {
return $r;
}
return false;
}
/**
* Erases all mapping entries for one combination of user, device ID.
*
* This is used during SlowSync so that we really sync everything properly
* and no old mapping entries remain.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
*/
public function eraseMap($databaseURI)
{
$database = $this->normalize($databaseURI);
$r = $this->_db->exec(
'DELETE FROM syncml_map '
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
$r = $this->_db->exec(
'DELETE FROM syncml_suidlist '
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
return true;
}
/**
* Cleanup public function called after all message processing is finished.
*
* Allows for things like closing databases or flushing logs. When
* running in test mode, tearDown() must be called rather than close.
*/
public function close()
{
parent::close();
$this->_db->disconnect();
}
/**
* Checks if the parameter is a PEAR_Error object and if so logs the
* error.
*
* @param mixed $o An object or value to check.
*
* @return mixed The error object if an error has been passed or false if
* no error has been passed.
*/
protected function _checkForError($o)
{
if (is_a($o, 'PEAR_Error')) {
$this->logMessage($o);
return $o;
}
return false;
}
/**
* Returns a list of item IDs that have been deleted since the last sync
* run and stores a complete list of IDs for next sync run.
*
* Some backend datastores don't keep information about deleted entries.
* So we have to create a workaround that finds out what entries have been
* deleted since the last sync run. This method provides this
* functionality: it is called with a list of all IDs currently in the
* database. It then compares this list with its own previously stored
* list of IDs to identify those missing (and thus deleted). The passed
* list is then stored for the next invocation.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param array $currentSuids Array of all SUIDs (primary keys) currently
* in the server datastore.
*
* @return array Array of all entries that have been deleted since the
* last call.
*/
protected function _trackDeletes($databaseURI, $currentSuids)
{
$database = $this->normalize($databaseURI);
if (!is_array($currentSuids)) {
$currentSuids = array();
}
$this->logMessage('_trackDeletes() with ' . count($currentSuids)
. ' current ids', 'DEBUG');
$r = $this->_db->queryCol(
'SELECT syncml_suid FROM syncml_suidlist '
. ' WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
$this->logMessage('_trackDeletes() found ' . count($r)
. ' items in prevlist', 'DEBUG');
// Convert to hash with suid as key.
if (is_array($r)) {
$prevSuids = array_flip($r);
} else {
$prevSuids = array();
}
foreach ($currentSuids as $suid) {
if (isset($prevSuids[$suid])) {
// Entry is there now and in $prevSuids. Unset in $prevSuids
// array so we end up with only those in $prevSuids that are
// no longer there now.
unset($prevSuids[$suid]);
} else {
// Entry is there now but not in $prevSuids. New entry, store
// in syncml_suidlist
$r = $this->_db->exec(
'INSERT INTO syncml_suidlist '
. ' (syncml_syncpartner, syncml_db, syncml_uid, '
. 'syncml_suid) VALUES ('
. $this->_db->quote($this->_syncDeviceID, 'text') . ', '
. $this->_db->quote($database, 'text') . ', '
. $this->_db->quote($this->_user, 'text') . ', '
. $this->_db->quote($suid, 'text')
. ')');
if ($this->_checkForError($r)) {
return $r;
}
}
}
// $prevSuids now contains the deleted suids. Remove those from
// syncml_suidlist so we have a current list of all existing suids.
foreach ($prevSuids as $suid => $cuid) {
$r = $this->_removeFromSuidList($databaseURI, $suid);
}
$this->logMessage('_trackDeletes() with ' . count($prevSuids)
. ' deleted items', 'DEBUG');
return array_keys($prevSuids);
}
/**
* Removes a suid from the suidlist.
*
* Called by _trackDeletes() when updating the suidlist and deleteEntry()
* when removing an entry due to a client request.
*
* @param string $databaseURI URI of database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param array $suid The suid to remove from the list.
*/
protected function _removeFromSuidList($databaseURI, $suid)
{
$database = $this->normalize($databaseURI);
$this->logMessage('_removeFromSuidList(): item ' . $suid, 'DEBUG');
$r = $this->_db->queryCol(
'DELETE FROM syncml_suidlist '
. 'WHERE syncml_syncpartner = '
. $this->_db->quote($this->_syncDeviceID, 'text')
. ' AND syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($this->_user, 'text')
. ' AND syncml_suid = '
. $this->_db->quote($suid, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
$this->logMessage('_removeFromSuidList(): result ' . implode('!', $r), 'DEBUG');
return true;
}
/**
* Creates a clean test environment in the backend.
*
* Ensures there's a user with the given credentials and an empty data
* store.
*
* @param string $user This user accout has to be created in the backend.
* @param string $pwd The password for user $user.
*/
public function testSetup($user, $pwd)
{
$this->_user = $user;
$this->_cleanUser($user);
$this->_backend->_user = $user;
$r = $this->_db->exec(
'INSERT INTO syncml_uids (syncml_uid, syncml_password)'
. ' VALUES ('
. $this->_db->quote($user, 'text') . ', '
. $this->_db->quote($pwd, 'text') . ')');
$this->_checkForError($r);
}
/**
* Prepares the test start.
*
* @param string $user This user accout has to be created in the backend.
*/
public function testStart($user)
{
$this->_user = $user;
$this->_backend->_user = $user;
}
/**
* Tears down the test environment after the test is run.
*
* Should remove the testuser created during testSetup and all its data.
*/
public function testTearDown()
{
$this->_cleanUser($this->_user);
$this->_db->disconnect();
}
/* Database access functions. The following methods are not part of the
* backend API. They are here to illustrate how a backend application
* (like a web calendar) has to modify the data with respect to the
* history. There are three functions:
* addEntry_backend(), replaceEntry_backend(), deleteEntry_backend().
* They are very similar to the API methods above, but don't use cuids or
* syncDeviceIDs as these are only relevant for syncing. */
/**
* Adds an entry into the server database.
*
* @param string $user The username to use. Not strictly necessery
* to store this, but it helps for the test
* environment to clean up all entries for a
* test user.
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
*
* @return array PEAR_Error or suid of new entry.
*/
public function addEntry_backend($user, $databaseURI, $content, $contentType)
{
$database = $this->normalize($databaseURI);
// Generate an id (suid). It's also possible to use a database
// generated primary key here. */
$suid = strval(new Horde_Support_Uuid());
$created_ts = $this->getCurrentTimeStamp();
$r = $this->_db->exec(
'INSERT INTO syncml_data (syncml_id, syncml_db, syncml_uid, '
. 'syncml_data, syncml_contenttype, syncml_created_ts, '
. 'syncml_modified_ts) VALUES ('
. $this->_db->quote($suid, 'text') . ', '
. $this->_db->quote($database, 'text') . ', '
. $this->_db->quote($user, 'text') . ', '
. $this->_db->quote($content, 'text') . ', '
. $this->_db->quote($contentType, 'text') . ', '
. $this->_db->quote($created_ts, 'integer') . ', '
. $this->_db->quote($created_ts, 'integer')
. ')');
if ($this->_checkForError($r)) {
return $r;
}
return $suid;
}
/**
* Replaces an entry in the server database.
*
* @param string $user The username to use. Not strictly necessery
* to store this but, it helps for the test
* environment to clean up all entries for a
* test user.
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $content The actual data.
* @param string $contentType MIME type of the content.
* @param string $suid Server ID of this entry.
*
* @return string PEAR_Error or suid of modified entry.
*/
public function replaceEntry_backend($user, $databaseURI, $content, $contentType,
$suid)
{
$database = $this->normalize($databaseURI);
$modified_ts = $this->getCurrentTimeStamp();
// Entry exists: replace current one.
$r = $this->_db->exec(
'UPDATE syncml_data '
. 'SET syncml_modified_ts = '
. $this->_db->quote($modified_ts, 'integer')
. ',syncml_data = '
. $this->_db->quote($content, 'text')
. ',syncml_contenttype = '
. $this->_db->quote($contentType, 'text')
. 'WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($user, 'text')
. ' AND syncml_id = '
. $this->_db->quote($suid, 'text'));
if ($this->_checkForError($r)) {
return $r;
}
return $suid;
}
/**
* Deletes an entry from the server database.
*
* @param string $user The username to use. Not strictly necessery
* to store this, but it helps for the test
* environment to clean up all entries for a
* test user.
* @param string $databaseURI URI of Database to sync. Like calendar,
* tasks, contacts or notes. May include
* optional parameters:
* tasks?options=ignorecompleted.
* @param string $suid Server ID of the entry.
*
* @return boolean True on success or false on failed (item not found).
*/
public function deleteEntry_backend($user, $databaseURI, $suid)
{
$database = $this->normalize($databaseURI);
$r = $this->_db->queryOne(
'DELETE FROM syncml_data '
. 'WHERE syncml_db = '
. $this->_db->quote($database, 'text')
. ' AND syncml_uid = '
. $this->_db->quote($user, 'text')
. ' AND syncml_id = '
. $this->_db->quote($suid, 'text'));
if ($this->_checkForError($r)) {
return false;
}
return true;
}
protected function _cleanUser($user)
{
$r = $this->_db->exec('DELETE FROM syncml_data WHERE syncml_uid = '
. $this->_db->quote($user, 'text'));
$this->_checkForError($r);
$r = $this->_db->exec('DELETE FROM syncml_map WHERE syncml_uid = '
. $this->_db->quote($user, 'text'));
$this->_checkForError($r);
$r = $this->_db->exec('DELETE FROM syncml_anchors WHERE syncml_uid = '
. $this->_db->quote($user, 'text'));
$this->_checkForError($r);
$r = $this->_db->exec('DELETE FROM syncml_uids WHERE syncml_uid = '
. $this->_db->quote($user, 'text'));
$this->_checkForError($r);
$r = $this->_db->exec('DELETE FROM syncml_suidlist WHERE syncml_uid = '
. $this->_db->quote($user, 'text'));
$this->_checkForError($r);
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Command.php 0000664 0000000 0000000 00000011125 12130076041 0024766 0 ustar 00root root 0000000 0000000 commands.
*
* A SyncML command is a protocol primitive. Each SyncML command specifies to a
* recipient an individual operation that is to be performed.
*
* The Horde_SyncMl_Command objects are hooked into the XML parser of the
* Horde_SyncMl_ContentHandler class and are reponsible for parsing a single
* command inside the SyncBody section of a SyncML message. All actions that
* must be executed for a single SyncML command are handled by these objects,
* by means of the handleCommand() method.
*
* Copyright 2003-2013 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Anthony Mills
* @author Jan Schneider
* @package SyncMl
*/
class Horde_SyncMl_Command
{
/**
* Name of the command, like 'Put'.
*
* Must be overwritten by a sub class.
*
* @var string
*/
protected $_cmdName;
/**
* The command ID ().
*
* @var integer
*/
protected $_cmdID;
/**
* Stack for holding the XML elements during creation of the object from
* the XML event flow.
*
* @var array
*/
protected $_stack = array();
/**
* Buffer for the parsed character data.
*
* @var string
*/
protected $_chars = '';
/**
* A Horde_SyncMl_XmlOutput instance responsible for generating the output.
*
* @var Horde_SyncMl_XmlOutput
*/
protected $_outputHandler;
/**
* Constructor.
*
* @param Horde_SyncMl_XmlOutput $outputHandler A Horde_SyncMl_XmlOutput object.
*/
public function __construct(&$outputHandler)
{
$this->_outputHandler = &$outputHandler;
}
/**
* Start element handler for the XML parser, delegated from
* Horde_SyncMl_ContentHandler::startElement().
*
* @param string $uri The namespace URI of the element.
* @param string $element The element tag name.
* @param array $attrs A hash with the element's attributes.
*/
public function startElement($uri, $element, $attrs)
{
$this->_stack[] = $element;
}
/**
* End element handler for the XML parser, delegated from
* Horde_SyncMl_ContentHandler::endElement().
*
* @param string $uri The namespace URI of the element.
* @param string $element The element tag name.
*/
public function endElement($uri, $element)
{
if (count($this->_stack) == 2 &&
$element == 'CmdID') {
$this->_cmdID = intval(trim($this->_chars));
}
if (strlen($this->_chars)) {
$this->_chars = '';
}
array_pop($this->_stack);
}
/**
* Character data handler for the XML parser, delegated from
* Horde_SyncMl_ContentHandler::characters().
*
* @param string $str The data string.
*/
public function characters($str)
{
$this->_chars .= $str;
}
/**
* Returns the command name this instance is reponsible for.
*
* @return string The command name this object is handling.
*/
public function getCommandName()
{
return $this->_cmdName;
}
/**
* This method is supposed to implement the actual business logic of the
* command once the XML parsing is complete.
*
* @abstract
*/
public function handleCommand($debug = false)
{
}
/**
* Attempts to return a concrete Horde_SyncMl_Command instance based on
* $command.
*
* @param string $command The type of the concrete
* Horde_SyncMl_Comment subclass to
* return.
* @param Horde_SyncMl_XmlOutput $outputHandler A Horde_SyncMl_XmlOutput object.
*
* @return Horde_SyncMl_Command The newly created concrete Horde_SyncMl_Command
* instance, or false on error.
*/
public function &factory($command, &$outputHandler)
{
$command = basename($command);
$class = 'Horde_SyncMl_Command_' . $command;
if (class_exists($class)) {
$cmd = new $class($outputHandler);
} else {
$msg = 'Class definition of ' . $class . ' not found.';
$GLOBALS['backend']->logMessage($msg, __FILE__, __LINE__, 'ERR');
$cmd = PEAR::raiseError($msg);
}
return $cmd;
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Command/ 0000775 0000000 0000000 00000000000 12130076041 0024255 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Command/Alert.php 0000664 0000000 0000000 00000027203 12130076041 0026041 0 ustar 00root root 0000000 0000000
* @author Karsten Fourmont
* @author Jan Schneider
* @package SyncMl
*/
class Horde_SyncMl_Command_Alert extends Horde_SyncMl_Command
{
/**
* Name of the command.
*
* @var string
*/
protected $_cmdName = 'Alert';
/**
* The alert type. Should be one of the Horde_SyncMl::ALERT_* constants.
*
* @var integer
*/
protected $_alert;
/**
* Source database of the Alert command.
*
* @var string
*/
protected $_sourceLocURI;
/**
* Target database of the Alert command.
*
* @var string
*/
protected $_targetLocURI;
/**
* The current time this synchronization happens, from the
* element.
*
* @var string
*/
protected $_metaAnchorNext;
/**
* The last time when synchronization happened, from the
* element.
*
* @var integer
*/
protected $_metaAnchorLast;
/**
* End element handler for the XML parser, delegated from
* Horde_SyncMl_ContentHandler::endElement().
*
* @param string $uri The namespace URI of the element.
* @param string $element The element tag name.
*/
public function endElement($uri, $element)
{
switch (count($this->_stack)) {
case 2:
if ($element == 'Data') {
$this->_alert = intval(trim($this->_chars));
}
break;
case 4:
if ($element == 'LocURI') {
switch ($this->_stack[2]) {
case 'Source':
$this->_sourceLocURI = trim($this->_chars);
break;
case 'Target':
$this->_targetLocURI = trim($this->_chars);
break;
}
}
break;
case 5:
switch ($element) {
case 'Next':
$this->_metaAnchorNext = trim($this->_chars);
break;
case 'Last':
$this->_metaAnchorLast = trim($this->_chars);
break;
}
break;
}
parent::endElement($uri, $element);
}
/**
* Implements the actual business logic of the Alert command.
*/
public function handleCommand($debug = false)
{
$state = $GLOBALS['backend']->state;
// Handle unauthenticated first.
if (!$state->authenticated) {
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
Horde_SyncMl::RESPONSE_INVALID_CREDENTIALS);
return;
}
// Handle NEXT_MESSAGE Alert by doing nothing, except OK status
// response. Exception for Funambol: here we produce the output only
// after an explicit Horde_SyncMl::ALERT_NEXT_MESSAGE.
if ($this->_alert == Horde_SyncMl::ALERT_NEXT_MESSAGE) {
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
Horde_SyncMl::RESPONSE_OK);
// @TODO: create a getDevice()->sentyncDataLate() method instead
// of this:
if (is_a($state->getDevice(), 'Horde_SyncMl_Device_sync4j')) {
// Now send client changes to server. This will produce the
// response.
$sync = &$state->getSync($this->_targetLocURI);
if ($sync) {
$sync->createSyncOutput($this->_outputHandler);
}
}
return;
}
$database = $this->_targetLocURI;
if (!$GLOBALS['backend']->isValidDatabaseURI($database)) {
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
Horde_SyncMl::RESPONSE_NOT_FOUND);
return;
}
if ($database == 'configuration') {
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
Horde_SyncMl::RESPONSE_OK);
}
$clientAnchorNext = $this->_metaAnchorNext;
if (!$debug &&
($this->_alert == Horde_SyncMl::ALERT_TWO_WAY ||
$this->_alert == Horde_SyncMl::ALERT_ONE_WAY_FROM_CLIENT ||
$this->_alert == Horde_SyncMl::ALERT_ONE_WAY_FROM_SERVER)) {
// Check if we have information about previous sync.
$r = $GLOBALS['backend']->readSyncAnchors($this->_targetLocURI);
if (is_array($r)) {
// Info about previous successful sync sessions found.
list($clientlast, $serverAnchorLast) = $r;
$GLOBALS['backend']->logMessage(
'Previous sync found for database ' . $database
. '; client timestamp: ' . $clientlast, 'DEBUG');
// Check if anchor sent from client matches our own stored
// data.
if ($clientlast == $this->_metaAnchorLast) {
// Last sync anchors matche, TwoWaySync will do.
$anchormatch = true;
$GLOBALS['backend']->logMessage(
'Anchor timestamps match, TwoWaySync possible. Syncing data since '
. date('Y-m-d H:i:s', $serverAnchorLast), 'DEBUG');
} else {
// Server and client have different anchors, enforce
// SlowSync/RefreshSync
$GLOBALS['backend']->logMessage(
'Client requested sync with anchor timestamp '
. $this->_metaAnchorLast
. ' but server has recorded timestamp '
. $clientlast . '. Enforcing SlowSync', 'INFO');
$anchormatch = false;
$clientlast = 0;
}
} else {
// No info about previous sync, use SlowSync or RefreshSync.
$GLOBALS['backend']->logMessage(
'No info about previous syncs found for device ' .
$state->sourceURI . ' and database ' . $database, 'DEBUG');
$clientlast = 0;
$serverAnchorLast = 0;
$anchormatch = false;
}
} else {
// SlowSync requested, no anchor check required.
$anchormatch = true;
}
// Determine sync type and status response code.
switch ($this->_alert) {
case Horde_SyncMl::ALERT_TWO_WAY:
if ($anchormatch) {
$synctype = Horde_SyncMl::ALERT_TWO_WAY;
$response = Horde_SyncMl::RESPONSE_OK;
} else {
$synctype = Horde_SyncMl::ALERT_SLOW_SYNC;
$response = Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
}
break;
case Horde_SyncMl::ALERT_SLOW_SYNC:
$synctype = Horde_SyncMl::ALERT_SLOW_SYNC;
$response = $anchormatch ? Horde_SyncMl::RESPONSE_OK : Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
break;
case Horde_SyncMl::ALERT_ONE_WAY_FROM_CLIENT:
if ($anchormatch) {
$synctype = Horde_SyncMl::ALERT_ONE_WAY_FROM_CLIENT;
$response = Horde_SyncMl::RESPONSE_OK;
} else {
$synctype = Horde_SyncMl::ALERT_REFRESH_FROM_CLIENT;
$response = Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
}
break;
case Horde_SyncMl::ALERT_REFRESH_FROM_CLIENT:
$synctype = Horde_SyncMl::ALERT_REFRESH_FROM_CLIENT;
$response = $anchormatch ? Horde_SyncMl::RESPONSE_OK : Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
break;
case Horde_SyncMl::ALERT_ONE_WAY_FROM_SERVER:
if ($anchormatch) {
$synctype = Horde_SyncMl::ALERT_ONE_WAY_FROM_SERVER;
$response = Horde_SyncMl::RESPONSE_OK;
} else {
$synctype = Horde_SyncMl::ALERT_REFRESH_FROM_SERVER;
$response = Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
}
break;
case Horde_SyncMl::ALERT_REFRESH_FROM_SERVER:
$synctype = Horde_SyncMl::ALERT_REFRESH_FROM_SERVER;
$response = $anchormatch ? Horde_SyncMl::RESPONSE_OK : Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
break;
case Horde_SyncMl::ALERT_RESUME:
// @TODO: Suspend and Resume is not supported yet
$synctype = Horde_SyncMl::ALERT_SLOW_SYNC;
$response = Horde_SyncMl::RESPONSE_REFRESH_REQUIRED;
break;
default:
$GLOBALS['backend']->logMessage(
'Unknown sync type ' . $this->_alert, 'ERR');
break;
}
// Now set interval to retrieve server changes from, defined by
// ServerAnchor [Last,Next]
if ($synctype != Horde_SyncMl::ALERT_TWO_WAY &&
$synctype != Horde_SyncMl::ALERT_ONE_WAY_FROM_CLIENT &&
$synctype != Horde_SyncMl::ALERT_ONE_WAY_FROM_SERVER) {
$serverAnchorLast = 0;
// Erase existing map:
if (!$debug &&
(($anchormatch &&
Horde_SyncMl::CONFIG_DELETE_MAP_ON_REQUESTED_SLOWSYNC) ||
(!$anchormatch &&
Horde_SyncMl::CONFIG_DELETE_MAP_ON_ANCHOR_MISMATCH_SLOWSYNC))) {
$GLOBALS['backend']->eraseMap($this->_targetLocURI);
}
}
$serverAnchorNext = $debug ? time() : $GLOBALS['backend']->getCurrentTimeStamp();
// Now create the actual Horde_SyncMl_Sync object, if it doesn't exist yet.
$sync = &$state->getSync($this->_targetLocURI);
if (!$sync) {
$GLOBALS['backend']->logMessage(
'Creating Horde_SyncMl_Sync object for database '
. $this->_targetLocURI . '; sync type ' . $synctype, 'DEBUG');
$sync = new Horde_SyncMl_Sync($synctype,
$this->_targetLocURI,
$this->_sourceLocURI,
(int)$serverAnchorLast, (int)$serverAnchorNext,
$clientAnchorNext);
$state->setSync($this->_targetLocURI, $sync);
}
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
$response,
$this->_targetLocURI,
$this->_sourceLocURI,
$this->_metaAnchorNext,
$this->_metaAnchorLast);
$this->_outputHandler->outputAlert($synctype,
$sync->getClientLocURI(),
$sync->getServerLocURI(),
$sync->getServerAnchorLast(),
$sync->getServerAnchorNext());
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Command/Final.php 0000664 0000000 0000000 00000002643 12130076041 0026024 0 ustar 00root root 0000000 0000000
* @author Jan Schneider
* @package SyncMl
*/
class Horde_SyncMl_Command_Final extends Horde_SyncMl_Command
{
/**
* Name of the command.
*
* @var string
*/
protected $_cmdName = 'Final';
/**
* Implements the actual business logic of the Alert command.
*/
public function handleCommand($debug = false)
{
$state = $GLOBALS['backend']->state;
// If the client hasn't sent us device info, request it now.
// @todo: only do this once, not in every msg if the client does not
// implement DevInf.
$di = $state->deviceInfo;
if (empty($di->Man)) {
$this->_outputHandler->outputGetDevInf();
}
$GLOBALS['backend']->logMessage('Received from client.', 'DEBUG');
$state->handleFinal($this->_outputHandler, $debug);
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Command/Get.php 0000664 0000000 0000000 00000002640 12130076041 0025507 0 ustar 00root root 0000000 0000000
* @author Jan Schneider
* @package SyncMl
*/
class Horde_SyncMl_Command_Get extends Horde_SyncMl_Command
{
/**
* Name of the command.
*
* @var string
*/
protected $_cmdName = 'Get';
/**
* Implements the actual business logic of the Alert command.
*/
public function handleCommand($debug = false)
{
$state = $GLOBALS['backend']->state;
// Create status response.
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
Horde_SyncMl::RESPONSE_OK,
$state->getDevInfURI());
if (!$state->authenticated) {
return;
}
$this->_outputHandler->outputDevInf($this->_cmdID);
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Command/Map.php 0000664 0000000 0000000 00000006542 12130076041 0025512 0 ustar 00root root 0000000 0000000
* @author Jan Schneider
* @package SyncMl
*/
class Horde_SyncMl_Command_Map extends Horde_SyncMl_Command
{
/**
* Name of the command.
*
* @var string
*/
protected $_cmdName = 'Map';
/**
* Source database of the Map command.
*
* @var string
*/
protected $_sourceLocURI;
/**
* Target database of the Map command.
*
* @var string
*/
protected $_targetLocURI;
/**
* Recipient map item specifiers.
*
* @var array
*/
protected $_mapTargets = array();
/**
* Originator map item specifiers.
*
* @var array
*/
protected $_mapSources = array();
/**
* End element handler for the XML parser, delegated from
* Horde_SyncMl_ContentHandler::endElement().
*
* @param string $uri The namespace URI of the element.
* @param string $element The element tag name.
*/
public function endElement($uri, $element)
{
switch (count($this->_stack)) {
case 3:
if ($element == 'LocURI') {
if ($this->_stack[1] == 'Source') {
$this->_sourceLocURI = trim($this->_chars);
} elseif ($this->_stack[1] == 'Target') {
$this->_targetLocURI = trim($this->_chars);
}
}
break;
case 4:
if ($element == 'LocURI') {
if ($this->_stack[2] == 'Source') {
$this->_mapSources[] = trim($this->_chars);
} elseif ($this->_stack[2] == 'Target') {
$this->_mapTargets[] = trim($this->_chars);
}
}
break;
}
parent::endElement($uri, $element);
}
/**
* Implements the actual business logic of the Alert command.
*
* @todo No OK response on error.
*/
public function handleCommand($debug = false)
{
if (!$debug && $this->_mapSources) {
$state = $GLOBALS['backend']->state;
$sync = &$state->getSync($this->_targetLocURI);
if (!$state->authenticated) {
$GLOBALS['backend']->logMessage(
'Not authenticated while processing
if (trim($this->_chars) == 'SyncML/1.1') {
$this->_version = 1;
} elseif (trim($this->_chars) == 'SyncML/1.2') {
$this->_version = 2;
} else {
$this->_version = 0;
}
} elseif ($element == 'SessionID') {
//
$this->_sessionID = trim($this->_chars);
} elseif ($element == 'MsgID') {
//
$this->_message = intval(trim($this->_chars));
}
break;
case 3:
if ($element == 'LocURI') {
if ($this->_stack[1] == 'Source') {
//
$this->_sourceURI = trim($this->_chars);
} elseif ($this->_stack[1] == 'Target') {
//
$this->_targetURI = trim($this->_chars);
}
} elseif ($element == 'LocName') {
if ($this->_stack[1] == 'Source') {
//
$this->user = trim($this->_chars);
}
} elseif ($element == 'Data') {
//
if ($this->_stack[1] == 'Cred') {
$this->credData = trim($this->_chars);
}
} elseif ($element == 'MaxMsgSize') {
//
$this->_maxMsgSize = intval($this->_chars);
}
break;
case 4:
if ($this->_stack[1] == 'Cred') {
if ($element == 'Format') {
//
$this->credFormat = trim($this->_chars);
} elseif ($element == 'Type') {
//
$this->credType = trim($this->_chars);
}
}
break;
}
parent::endElement($uri, $element);
}
/**
* Starts the PHP session and instantiates the global Horde_SyncMl_State object
* if doesn't exist yet.
*/
public function setupState()
{
global $backend;
$backend->sessionStart($this->_sourceURI, $this->_sessionID);
if (!$backend->state) {
$backend->logMessage(
'New session created: ' . session_id(), 'DEBUG');
$backend->state = new Horde_SyncMl_State($this->_sourceURI,
$this->user,
$this->_sessionID);
} else {
$backend->logMessage('Existing session continued: ' . session_id(), 'DEBUG');
}
$backend->state->setVersion($this->_version);
$backend->state->messageID = $this->_message;
$backend->state->targetURI = $this->_targetURI;
$backend->state->sourceURI = $this->_sourceURI;
$backend->state->sessionID = $this->_sessionID;
if (!empty($this->_maxMsgSize)) {
$backend->state->maxMsgSize = $this->_maxMsgSize;
}
$backend->setupState();
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/ContentHandler.php 0000664 0000000 0000000 00000043431 12130076041 0026325 0 ustar 00root root 0000000 0000000
* @author Anthony Mills
* @package SyncMl
*/
class Horde_SyncMl_ContentHandler
{
/**
* Stack for holding the xml elements during creation of the object from
* the xml event flow.
*
* @var array
*/
protected $_Stack = array();
/**
* @var string
*/
protected $_chars;
/**
* Instance of Horde_SyncMl_Command. Events are passed through to this
* ContentHandler.
*
* @var Horde_SyncMl_Command
*/
protected $_currentCommand;
/**
* Whether we received a final element in this message.
*/
protected $_gotFinal = false;
protected $_xmlWriter;
protected $_wbxmlparser = null;
/**
* The response URI as sent by the server.
*
* This is the endpoint URL of the RPC server.
*
* @var string
*/
protected $_respURI;
public $debug = false;
public function __construct()
{
/* Set to true to indicate that we expect another message from the
* client. If this is still false at the end of processing, the sync
* session is finished and we can close the session. */
$GLOBALS['message_expectresponse'] = false;
}
/**
* Here's were all the processing takes place: gets the SyncML request
* data and returns a SyncML response. The only thing that needs to be in
* place before invoking this public function is a working backend.
*
* @param string $request The raw request string.
* @param string $contentType The MIME content type of the request. Should
* be either application/vnd.syncml or
* application/vnd.syncml+wbxml.
* @param string $respURI The url of the server endpoint. Will be
* returned in the RespURI element.
*/
public function process($request, $contentType, $respURI = null)
{
$isWBXML = $contentType =='application/vnd.syncml+wbxml';
$this->_respURI = $respURI;
/* Catch any errors/warnings/notices that may get thrown while
* processing. Don't want to let anything go to the client that's not
* part of the valid response. */
ob_start();
$GLOBALS['backend']->logFile(Horde_SyncMl_Backend::LOGFILE_CLIENTMESSAGE, $request, $isWBXML);
if (!$isWBXML) {
/* XML code. */
/* try to extract charset from XML text */
if (preg_match('/^\s*<\?xml[^>]*encoding\s*=\s*"([^"]*)"/i',
$request, $m)) {
$charset = $m[1];
} else {
$charset = 'UTF-8';
}
$GLOBALS['backend']->setCharset($charset);
/* Init output handler. */
$this->_xmlWriter = &Horde_SyncMl_XmlOutput::singleton();
/* Horde_Xml_Wbxml_ContentHandler Is a class that produces plain XML
* output. */
$this->_xmlWriter->init(new Horde_Xml_Wbxml_ContentHandler());
/* Create the XML parser and set method references. */
$parser = xml_parser_create_ns($charset);
xml_set_object($parser, $this);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
xml_set_element_handler($parser, '_startElement', '_endElement');
xml_set_character_data_handler($parser, '_characters');
xml_set_processing_instruction_handler($parser, '');
xml_set_external_entity_ref_handler($parser, '');
/* Here we go: fire off events: */
if (!xml_parse($parser, $request)) {
$s = sprintf('XML error: %s at line %d',
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser));
$GLOBALS['backend']->logMessage($s, 'ERR');
xml_parser_free($parser);
return new PEAR_Error($s);
}
xml_parser_free($parser);
} else {
/* The decoder works like the parser in the XML code above: It
* parses the input and calls the callback functions of $this. */
$this->_wbxmlparser = new Horde_Xml_Wbxml_Decoder();
$this->_wbxmlparser->setContentHandler($this);
/* Init output handler. */
$this->_xmlWriter = &Horde_SyncMl_XmlOutput::singleton();
$this->_xmlWriter->init(new Horde_Xml_Wbxml_Encoder());
/* Here we go: fire off events: */
/* @todo catch exceptions */
$this->_wbxmlparser->decode($request);
}
$id = @session_id();
$sessionclose = empty($id);
$output = $this->getOutput();
if (!$isWBXML) {
$output = '' . $output;
}
$GLOBALS['backend']->logFile(Horde_SyncMl_Backend::LOGFILE_SERVERMESSAGE, $output, $isWBXML, $sessionclose);
/* Clear the output buffer that we started above, and log anything
* that came up for later debugging. */
$errorLogging = ob_get_clean();
if (!empty($errorLogging)) {
$GLOBALS['backend']->logMessage('Caught output: ' . $errorLogging, 'WARN');
}
return $output;
}
/*
* CONTENTHANDLER CALLBACK FUNCTIONS
* The following functions are callback functions that are called by the
* XML parser. The XML and WBXML parsers use slightly different functions,
* so the methods are duplicated.
*/
/**
* Returns the XML|WBXML output once processing is finished.
*
* @return string The XML or WBXML output data.
*/
public function getOutput()
{
return $this->_xmlWriter->getOutput();
}
/**
* Callback public function called by XML parser.
*/
protected function _startElement($parser, $tag, $attributes)
{
list($uri, $name) = $this->_splitURI($tag);
$this->startElement($uri, $name, $attributes);
}
/**
* Callback public function called by XML parser.
*/
protected function _characters($parser, $chars)
{
$this->characters($chars);
}
/**
* Callback public function called by XML parser.
*/
protected function _endElement($parser, $tag)
{
list($uri, $name) = $this->_splitURI($tag);
$this->endElement($uri, $name);
}
/**
* Splits an URI as provided by the XML parser.
*/
protected function _splitURI($tag)
{
$parts = explode(':', $tag);
$name = array_pop($parts);
$uri = implode(':', $parts);
return array($uri, $name);
}
/**
* Callback public function called by WBXML parser.
*/
public function startElement($uri, $element, $attrs)
{
$this->_Stack[] = $element;
// : don't do anyhting yet
if (count($this->_Stack) == 1) {
return;
}
// header or body?
if ($this->_Stack[1] == 'SyncHdr') {
if (count($this->_Stack) == 2) {
$this->_currentCommand = new Horde_SyncMl_Command_SyncHdr($this->_xmlWriter);
}
$this->_currentCommand->startElement($uri, $element, $attrs);
} else {
switch (count($this->_Stack)) {
case 2:
// : do nothing yet
break;
case 3:
// new Command:
// <[Command]>
$this->_currentCommand = &Horde_SyncMl_Command::factory($element,$this->_xmlWriter);
$this->_currentCommand->startElement($uri, $element, $attrs);
break;
default:
// pass on to current command handler:
// <...>
$this->_currentCommand->startElement($uri, $element, $attrs);
break;
}
}
}
/**
* Callback public function called by WBXML parser.
*/
public function endElement($uri, $element)
{
// : everything done already by end of SyncBody
if (count($this->_Stack) == 1) {
return;
}
// header or body?
if ($this->_Stack[1] == 'SyncHdr') {
switch (count($this->_Stack)) {
case 2:
// end of header
$this->handleHeader($this->_currentCommand);
if ($this->debug) {
var_dump($this->_currentCommand);
}
unset($this->_currentCommand);
break;
default:
// pass on to command handler:
$this->_currentCommand->endElement($uri, $element);
break;
}
} else {
switch (count($this->_Stack)) {
case 2:
// end of SyncBody. Finish everything:
$this->handleEnd();
break;
case 3:
// [Command]>
// Command finished. Complete parsing and pass on to Handler
$this->_currentCommand->endElement($uri, $element);
$this->handleCommand($this->_currentCommand);
if ($this->debug) {
var_dump($this->_currentCommand);
}
unset($this->_currentCommand);
break;
default:
// [Command]>
// pass on to command handler:
$this->_currentCommand->endElement($uri, $element);
break;
}
}
if (isset($this->_chars)) {
unset($this->_chars);
}
array_pop($this->_Stack);
}
/**
* Callback public function called by WBXML parser.
*/
public function characters($str)
{
if (isset($this->_currentCommand)) {
$this->_currentCommand->characters($str);
} else {
if (isset($this->_chars)) {
$this->_chars = $this->_chars . $str;
} else {
$this->_chars = $str;
}
}
}
/*
* PROCESSING FUNCTIONS
*
* The following functions are called by the callback functions
* and do the actual processing.
*/
/**
* Handles the header logic.
*
* Invoked after header is parsed.
*/
public function handleHeader(&$hdr)
{
if (is_object($this->_wbxmlparser)) {
/* The WBXML parser only knows about the charset once parsing is
* started. So setup charset now. */
$this->_xmlWriter->output->setVersion($this->_wbxmlparser->getVersion());
$this->_xmlWriter->output->setCharset($this->_wbxmlparser->getCharsetStr());
$GLOBALS['backend']->setCharset($this->_wbxmlparser->getCharsetStr());
}
/* Start the session. */
$hdr->setupState();
$state = $GLOBALS['backend']->state;
$state->wbxml = $this->_xmlWriter->isWBXML();
/* Check auth. */
if (!$state->authenticated) {
$auth = $GLOBALS['backend']->checkAuthentication(
$hdr->user, $hdr->credData, $hdr->credFormat, $hdr->credType);
if ($auth !== false) {
$state->authenticated = true;
$statuscode = Horde_SyncMl::RESPONSE_AUTHENTICATION_ACCEPTED;
$state->user = $auth;
$GLOBALS['backend']->setUser($auth);
} else {
if (!$hdr->credData) {
$statuscode = Horde_SyncMl::RESPONSE_CREDENTIALS_MISSING;
} else {
$statuscode = Horde_SyncMl::RESPONSE_INVALID_CREDENTIALS;
}
$GLOBALS['backend']->logMessage('Invalid authentication', 'DEBUG');
}
} else {
$statuscode = Horde_SyncMl::RESPONSE_OK;
$GLOBALS['backend']->setUser($state->user);
}
/* Create . */
$this->_xmlWriter->outputInit();
/* Got the state; now write our SyncHdr header. */
$this->_xmlWriter->outputHeader($this->_respURI);
/* Creates . */
$this->_xmlWriter->outputBodyStart();
/* Output status for SyncHdr. */
$this->_xmlWriter->outputStatus('0', 'SyncHdr', $statuscode,
$state->targetURI,
$state->sourceURI);
/* Debug logging string. */
$str = 'Authenticated: ' . ($state->authenticated ? 'yes' : 'no')
. '; version: ' . $state->getVerDTD()
. '; message ID: ' . $state->messageID
. '; source URI: ' . $state->sourceURI
. '; target URI: ' . $state->targetURI
. '; user: ' . $state->user
. '; charset: ' . $GLOBALS['backend']->getCharset()
. '; wbxml: ' . ($state->wbxml ? 'yes' : 'no');
$GLOBALS['backend']->logMessage($str, 'DEBUG');
}
/**
* Processes one command after it has been completely parsed.
*
* Invoked after a command is parsed.
*/
public function handleCommand(&$cmd)
{
$name = $cmd->getCommandName();
if ($name != 'Status' && $name != 'Map' && $name != 'Final' &&
$name != 'Sync' && $name != 'Results') {
/* We've got to do something! This can't be the last packet. */
$GLOBALS['message_expectresponse'] = true;
}
if ($name == 'Final') {
$this->_gotFinal = true;
}
/* Actual processing takes place here. */
$cmd->handleCommand($this->debug);
}
/**
* Finishes the response.
*
* Invoked after complete message is parsed.
*/
public function handleEnd()
{
global $messageFull;
$state = $GLOBALS['backend']->state;
/* If there's pending sync data and space left in the message, send
* data now. */
if ($messageFull || $state->hasPendingSyncs()) {
/* still something to do: don't close session. */
$GLOBALS['message_expectresponse'] = true;
}
if (!$messageFull &&
count($p = $state->getPendingSyncs()) > 0) {
foreach ($p as $pendingSync) {
if (!$messageFull) {
$GLOBALS['backend']->logMessage(
'Continuing sync for syncType ' . $pendingSync, 'DEBUG');
$sync = &$state->getSync($pendingSync);
$sync->createSyncOutput($this->_xmlWriter);
}
}
}
if (isset($state->curSyncItem)) {
$this->_xmlWriter->outputAlert(
Horde_SyncMl::ALERT_NO_END_OF_DATA,
$state->curSyncItem->sync->getClientLocURI(),
$state->curSyncItem->sync->getServerLocURI(),
$state->curSyncItem->sync->getServerAnchorLast(),
$state->curSyncItem->sync->getServerAnchorNext());
}
/* Don't send the final tag if we haven't sent all sync data yet. */
if ($this->_gotFinal) {
if (!$messageFull &&
!$state->hasPendingSyncs()) {
/* Create . */
$this->_xmlWriter->outputFinal();
$GLOBALS['backend']->logMessage('Sending to client', 'DEBUG');
$state->delayedFinal = false;
} else {
$GLOBALS['message_expectresponse'] = true;
/* Remember to send a Final. */
$state->delayedFinal = true;
}
} elseif ($state->delayedFinal) {
if (!$messageFull &&
!$state->hasPendingSyncs()) {
/* Create . */
$this->_xmlWriter->outputFinal();
$GLOBALS['backend']->logMessage(
'Sending delayed to client', 'DEBUG');
$state->delayedFinal = false;
} else {
$GLOBALS['message_expectresponse'] = true;
}
}
/* Create . Message is finished now! */
$this->_xmlWriter->outputEnd();
if ($this->_gotFinal &&
!$GLOBALS['message_expectresponse'] &&
$state->isAllSyncsComplete()) {
/* This packet did not contain any real actions, just status and
* map. This means we're done. The session can be closed and the
* anchors saved for the next sync. */
foreach ($state->getSyncs() as $sync) {
$sync->closeSync();
}
$GLOBALS['backend']->logMessage('Session completed and closed', 'DEBUG');
/* Session can be closed here. */
$GLOBALS['backend']->sessionClose();
} else {
$GLOBALS['backend']->logMessage('Return message completed', 'DEBUG');
}
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/DataStore.php 0000664 0000000 0000000 00000006037 12130076041 0025304 0 ustar 00root root 0000000 0000000
* @author Jan Schneider
* @package SyncMl
*/
class Horde_SyncMl_DataStore
{
/**
* The local URI of the datastore.
*
* @var string
*/
public $SourceRef;
/**
* The display name of the datastore
*
* @var string
*/
public $DisplayName;
/**
* The maximum size of a global unique identifier for the datastore in
* bytes.
*
* @var integer
*/
public $MaxGUIDSize;
/**
* The preferred types and versions of a content type received by the
* device.
*
* The content types (CTType) are the keys, the versions (VerCT) are the
* values.
*
* @var array
*/
public $Rx_Pref = array();
/**
* The supported types and versions of a content type received by the
* device.
*
* The content types (CTType) are the keys, the versions (VerCT) are the
* values.
*
* @var array
*/
public $Rx = array();
/**
* The preferred types and versions of a content type transmitted by the
* device.
*
* The content types (CTType) are the keys, the versions (VerCT) are the
* values.
*
* @var array
*/
public $Tx_Pref = array();
/**
* The supported types and versions of a content type transmitted by the
* device.
*
* The content types (CTType) are the keys, the versions (VerCT) are the
* values.
*
* @var array
*/
public $Tx = array();
/**
* The maximum memory and item identifier for the datastore.
*
* Not implemented yet.
*/
public $DSMem;
/**
* The synchronization capabilities of the datastore.
*
* The synchronization types (SyncType) are stored in the keys of the
* hash.
*
* @var array
*/
public $SyncCap = array();
/**
* Returns the preferred content type the client wants to receive.
*
* @return string The device's preferred content type or null if not
* specified (which is not allowed).
*/
public function getPreferredRXContentType()
{
reset($this->Rx_Pref);
return key($this->Rx_Pref);
}
/**
* Returns the version of the preferred content type the client wants to
* receive.
*
* @return string The device's preferred content type version or null if
* not specified (which is not allowed).
*/
public function getPreferredRXContentTypeVersion()
{
return reset($this->Rx_Pref);
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Device.php 0000664 0000000 0000000 00000024120 12130076041 0024606 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
class Horde_SyncMl_Device
{
/**
* The original preferred content type of the client, if provided through
* DevInf.
*
* @var string
*/
public $requestedContentType;
/**
* Attempts to return a concrete Horde_SyncMl_Device instance based on $driver.
*
* @param string $driver The type of concrete Horde_SyncMl_Device subclass to
* return.
*
* @return Horde_SyncMl_Device The newly created concrete Horde_SyncMl_Device
* instance, or false on error.
*/
public function factory($driver)
{
$driver = basename($driver);
if (empty($driver) || $driver == 'none' || $driver == 'default') {
$GLOBALS['backend']->logMessage(
'Using default device class', 'DEBUG');
return new Horde_SyncMl_Device();
}
$class = 'Horde_SyncMl_Device_' . $driver;
if (!class_exists($class)) {
return false;
}
$device = new $class();
$GLOBALS['backend']->logMessage('Created device class ' . $class, 'DEBUG');
return $device;
}
/**
* Returns the guessed content type for a database URI.
*
* When a client sends data during a sync but does not provide information
* about the MIME content type with this individual item, this function
* returns the content type the item is supposed to be in.
*
* @param string $database A database URI.
*
* @return string A MIME type that might match the database URI.
*/
public function getPreferredContentType($database)
{
$database = $GLOBALS['backend']->normalize($database);
/* Use some wild guessings. */
if (strpos($database, 'contact') !== false ||
strpos($database, 'card') !== false) {
return 'text/x-vcard';
} elseif (strpos($database, 'note') !== false ||
strpos($database, 'snote') !== false ||
strpos($database, 'memo') !== false) {
return 'text/plain';
} elseif (strpos($database, 'task') !== false ||
strpos($database, 'cal') !== false ||
strpos($database, 'event') !== false) {
return 'text/calendar';
}
}
/**
* Returns the preferrred MIME content type of the client for the given
* sync data type (contacts/tasks/notes/calendar).
*
* The result is passed as an option to the backend export functions.
* This is not the content type ultimately passed to the client but rather
* the content type presented to the backend export functions.
*
* After the data is retrieved from the backend, convertServer2Client()
* can do some post-processing and set the correct content type acceptable
* for the client if necessary.
*
* The default implementation tries to extract the content type from the
* device info. If this does not work, some defaults are used.
*
* If the client does not provice proper DevInf data, this public function may
* have to be overwritten to return the correct values.
*
* @param string $serverSyncURI The URI for the server database: contacts,
* notes, calendar or tasks.
* @param string $sourceSyncURI The URI for the client database. This is
* needed as the DevInf is grouped by
* sourceSyncURIs.
*/
public function getPreferredContentTypeClient($serverSyncURI, $sourceSyncURI)
{
$di = $GLOBALS['backend']->state->deviceInfo;
$ds = $di->getDataStore($sourceSyncURI);
if (!empty($ds)) {
$r = $ds->getPreferredRXContentType();
if (!empty($r)) {
$this->requestedContentType = $r;
return $r;
}
}
$database = $GLOBALS['backend']->normalize($serverSyncURI);
/* No information in DevInf, use some wild guessings. */
if (strpos($database, 'contact') !== false ||
strpos($database, 'card') !== false) {
return 'text/x-vcard';
} elseif (strpos($database, 'note') !== false ||
strpos($database, 'snote') !== false ||
strpos($database, 'memo') !== false) {
// SyncML conformance suite expects this rather than text/x-vnote
return 'text/plain';
} elseif (strpos($database, 'task') !== false ||
strpos($database, 'cal') !== false ||
strpos($database, 'event') !== false) {
return 'text/calendar';
}
}
/**
* Converts the content received from the client for the backend.
*
* Currently strips UID (primary key) information as client and server
* might use different ones.
*
* Charset conversions might be added here too.
*
* @todo remove UID stripping or move it anywhere else.
*
* @param string $content The content to convert.
* @param string $contentType The content type of the content.
*
* @return array Two-element array with the converted content and the
* (possibly changed) new content type.
*/
public function convertClient2Server($content, $contentType)
{
$GLOBALS['backend']->logFile(
Horde_SyncMl_Backend::LOGFILE_DATA,
"\nInput received from client ($contentType):\n$content\n");
// Always remove client UID. UID will be seperately passed in XML.
$content = preg_replace('/(\r\n|\r|\n)UID:.*?(\r\n|\r|\n)/',
'\1', $content, 1);
return array($content, $contentType);
}
/**
* Converts the content from the backend to a format suitable for the
* client device.
*
* Strips the UID (primary key) information as client and server might use
* different ones.
*
* Charset conversions might be added here too.
*
* @param string $content The content to convert
* @param string $contentType The content type of content as returned
* from the backend
* @param string $database The server database URI.
*
* @return array Three-element array with the converted content, the
* (possibly changed) new content type, and encoding type
* (like b64 as used by Funambol).
*/
public function convertServer2Client($content, $contentType, $database)
{
if (is_array($contentType)) {
$contentType = $contentType['ContentType'];
}
$GLOBALS['backend']->logFile(
Horde_SyncMl_Backend::LOGFILE_DATA,
"\nOutput received from backend ($contentType):\n" . $content
. "\n");
/* Always remove server UID. UID will be seperately passed in XML. */
$content = preg_replace('/(\r\n|\r|\n)UID:.*?(\r\n|\r|\n)/',
'\1', $content, 1);
if ($this->useLocalTime()) {
$content = preg_replace_callback(
'/\d{8}T\d{6}Z/',
array($this, '_convertUTC2LocalTime'),
$content);
}
return array($content, $contentType, null);
}
/**
* Returns whether the device handles tasks and events in a single
* "calendar" sync.
*
* This requires special actions on our side as we store this in different
* backend databases.
*
* @return boolean True if tasks and events are processed in a single
* request.
*/
public function handleTasksInCalendar()
{
return false;
}
/**
* Returns whether to send individual status response for each Add, Delete
* and Replace.
*
* @return boolean False if individual status responses should be send.
*/
public function omitIndividualSyncStatus()
{
return false;
}
/**
* Returns whether the payload data should be enclosed in a [CDATA[
* section when sending via XML.
*
* The synchronized data may contain XML special characters like &,
* < or >. Clients might choke when sending these embedded in XML.
* The data should be enclosed in [CDATA[ in these cases. This applies
* only to XML, not to WBXML devices.
*
* @return boolean True if the data should be enclosed in [CDATA[.
*/
public function useCdataTag()
{
return true;
}
/**
* Returns whether the device accepts datetimes only in local time format
* (DTSTART:20061222T130000) instead of the more robust UTC time
* (DTSTART:20061222T110000Z).
*
* @return boolean True if the client doesn't accept UTC datetimes.
*/
public function useLocalTime()
{
return false;
}
/**
* Converts an UTC timestamp like "20061222T110000Z" into a local
* timestamp like "20061222T130000" using the server timezone.
*
* @param array $utc Array with a datetime string in UTC.
*
* @return string The datetime string converted to the local timezone.
*/
protected function _convertUTC2LocalTime($utc)
{
$date = new Horde_Date($utc[0]);
$date->setTimezone(date_default_timezone_get());
return $date->format("Ymd\THis");
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Device/ 0000775 0000000 0000000 00000000000 12130076041 0024076 5 ustar 00root root 0000000 0000000 php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Device/Nokia.php 0000664 0000000 0000000 00000006446 12130076041 0025662 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
class Horde_SyncMl_Device_Nokia extends Horde_SyncMl_Device
{
/**
* Converts the content received from the client for the backend.
*
* @param string $content The content to convert.
* @param string $contentType The content type of the content.
*
* @return array Two-element array with the converted content and the
* (possibly changed) new content type.
*/
public function convertClient2Server($content, $contentType)
{
list($content, $contentType) =
parent::convertClient2Server($content, $contentType);
/* At least the Nokia E series seems to prefix category values with
* X-, see bugs #6849 and #7824. */
$di = $GLOBALS['backend']->state->deviceInfo;
if ($di->Mod[0] == 'E') {
$content = preg_replace('/(\r\n|\r|\n)CATEGORIES:X-/',
'\1CATEGORIES:', $content, 1);
}
$GLOBALS['backend']->logFile(
Horde_SyncMl_Backend::LOGFILE_DATA,
"\nInput converted for server ($contentType):\n$content\n");
return array($content, $contentType);
}
/**
* Converts the content from the backend to a format suitable for the
* client device.
*
* Strips the UID (primary key) information as client and server might use
* different ones.
*
* Charset conversions might be added here too.
*
* @param string $content The content to convert
* @param string $contentType The content type of content as returned
* from the backend
* @param string $database The server database URI.
*
* @return array Three-element array with the converted content, the
* (possibly changed) new content type, and encoding type
* (like b64 as used by Funambol).
*/
public function convertServer2Client($content, $contentType, $database)
{
$database = $GLOBALS['backend']->normalize($database);
list($content, $contentType, $encodingType) =
parent::convertServer2Client($content, $contentType, $database);
$content = preg_replace('/(\r\n|\r|\n)PHOTO;ENCODING=b[^:]*:(.+?)(\r\n|\r|\n)/',
'\1PHOTO;ENCODING=BASE64:\1\2\1\1',
$content, 1);
$GLOBALS['backend']->logFile(
Horde_SyncMl_Backend::LOGFILE_DATA,
"\nOutput converted for client ($contentType):\n$content\n");
return array($content, $contentType, null);
}
public function handleTasksInCalendar()
{
return true;
}
/**
* Some devices accept datetimes only in local time format:
* DTSTART:20061222T130000
* instead of the more robust (and default) UTC time:
* DTSTART:20061222T110000Z
*/
public function useLocalTime()
{
return true;
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Device/P800.php 0000664 0000000 0000000 00000014057 12130076041 0025245 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
class Horde_SyncMl_Device_P800 extends Horde_SyncMl_Device
{
/**
* Convert the content.
*
* @param string $content The content to convert.
* @param string $contentType The contentType of the content.
* @return array array($newcontent, $newcontentType):
* the converted content and the
* (possibly changed) new ContentType.
*/
public function convertClient2Server($content, $contentType)
{
list($content, $contentType) =
parent::convertClient2Server($content, $contentType);
/* P800 sends categories as "X-Category". Remove the "X-".
* @todo: This hack only works with a single category. */
$content = preg_replace('/(\r\n|\r|\n)CATEGORIES:X-/', '\1CATEGORIES:',
$content, 1);
/* P800 sends all day events as s.th. like
* DTSTART:20050505T000000Z^M
* DTEND:20050505T240000Z^M
* This is no longer an all day event when converted to local timezone.
* So manually handle this. */
if (preg_match('/(\r\n|\r|\n)DTSTART:.*T000000Z(\r\n|\r|\n)/',
$content) &&
preg_match('/(\r\n|\r|\n)DTEND:(\d\d\d\d)(\d\d)(\d\d)T240000Z(\r\n|\r|\n)/',
$content, $m)) {
$content = preg_replace(
'/(\r\n|\r|\n)DTSTART:(.*)T000000Z(\r\n|\r|\n)/',
"$1DTSTART;VALUE=DATE:$2$3", $content);
/* End timestamp must be converted to next day's date. Or maybe
* not? */
$s = date('Ymd', mktime(0, 0, 0, $m[3], $m[4], $m[2]) /* + 24*3600 */);
$content = preg_replace(
'/(\r\n|\r|\n)DTEND:(.*)T240000Z(\r\n|\r|\n)/',
"$1DTEND;VALUE=DATE:$s$3", $content);
}
$GLOBALS['backend']->logFile(
Horde_SyncMl_Backend::LOGFILE_DATA,
"\ninput converted for server ($contentType):\n$content\n");
return array($content, $contentType);
}
/**
* Converts the content from the backend to a format suitable for the
* client device.
*
* Strips the uid (primary key) information as client and server might use
* different ones.
*
* @param string $content The content to convert
* @param string $contentType The content type of content as returned
* from the backend
* @param string $database The server database URI.
*
* @return array Three-element array with the converted content, the
* (possibly changed) new content type, and encoding type
* (like b64 as used by Funambol).
*/
public function convertServer2Client($content, $contentType, $database)
{
list($content, $contentType, $encodingType) =
parent::convertServer2Client($content, $contentType, $database);
/* Convert all day events. */
if (preg_match('/(\r\n|\r|\n)DTSTART:(\d{8})T000000/',
$content)
&& preg_match('/(\r\n|\r|\n)DTEND:(\d\d\d\d)(\d\d)(\d\d)T235959/',
$content, $m)) {
/* @TODO: This is for P990. Check if it's different for P900.
* This might require T000000Z rather than T000000 */
/* The P990 seems to require this to recognize an entry as all day: */
$a = $m[1] . 'X-EPOCAGENDAENTRYTYPE:EVENT';
$content = preg_replace('/(\r\n|\r|\n)DTSTART:(\d{8})T000000/',
"$a$1DTSTART:$2T000000", $content);
/* End date must be converted to timestamp. */
$s = date('Ymd', mktime(0, 0, 0, $m[3], $m[4]+1, $m[2]));
$content = preg_replace('/(\r\n|\r|\n)DTEND:(\d{8})T235959/',
"$1DTEND:${s}T000000", $content);
}
$l = "\noutput converted for client ($contentType):\n" . $content . "\n";
$GLOBALS['backend']->logFile(Horde_SyncMl_Backend::LOGFILE_DATA, $l);
return array($content, $contentType, $encodingType);
}
/**
* Some devices like the Sony Ericsson P800/P900/P910 handle vtodos (tasks)
* and vevents in the same "calendar" sync.
* This requires special actions on our side as we store this in different
* databases (nag and kronolith).
* This public function could directly return true but tries to be a bit more
* generic so it might work for other phones as well.
*/
public function handleTasksInCalendar()
{
$di = $GLOBALS['backend']->state->deviceInfo;
if (isset($di->CTCaps['text/x-vcalendar']) &&
!empty($di->CTCaps['text/x-vcalendar']['BEGIN']->ValEnum['VEVENT']) &&
!empty($di->CTCaps['text/x-vcalendar']['BEGIN']->ValEnum['VTODO'])) {
return true;
}
return parent::handleTasksInCalendar();
}
/**
* Send individual status response for each Add,Delete,Replace.
* The P800 class of devices seem to have trouble with too many
* status responses. So omit them for these (and only these),
*/
public function omitIndividualSyncStatus()
{
return true;
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Device/Sync4JMozilla.php 0000775 0000000 0000000 00000004247 12130076041 0027263 0 ustar 00root root 0000000 0000000
* @package SyncMl
*/
class Horde_SyncMl_Device_Sync4JMozilla extends Horde_SyncMl_Device
{
/**
* Converts the content from the backend to a format suitable for the
* client device.
*
* Strips the uid (primary key) information as client and server might use
* different ones.
*
* @param string $content The content to convert
* @param string $contentType The content type of content as returned
* from the backend
* @param string $database The server database URI.
*
* @return array Three-element array with the converted content, the
* (possibly changed) new content type, and encoding type
* (like b64 as used by Funambol).
*/
public function convertServer2Client($content, $contentType, $database)
{
list($content, $contentType, $encodingType) =
parent::convertServer2Client($content, $contentType, $database);
/* The plugin does currently not handle lines that are both folded
* and QUOTED-PRINTABLE encoded. Like this one with a note "abc":
* NOTE;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:=
* a=
* bc
*/
if (preg_match_all('/\r\n[^:]*ENCODING=QUOTED-PRINTABLE[^:]*:.*?=\r\n.*?[^=](?=\r\n)/mis', $content, $m)) {
foreach($m[0] as $v) {
/* Remove line folding */
$content = str_replace($v,str_replace("=\r\n", '', $v), $content);
}
}
$l = "\noutput converted for client ($contentType):\n" . $content . "\n";
$GLOBALS['backend']->logFile(Horde_SyncMl_Backend::LOGFILE_DATA, $l);
return array($content, $contentType, $encodingType);
}
}
php-horde-syncml-2.0.3/Horde_SyncMl-2.0.3/lib/Horde/SyncMl/Device/Sync4j.php 0000664 0000000 0000000 00000137056 12130076041 0025775 0 ustar 00root root 0000000 0000000 ' which should be the default anyhow.
*
* Copyright 2005-2013 Horde LLC (http://www.horde.org/)
*
* See the enclosed file COPYING for license information (LGPL). If you
* did not receive this file, see http://www.horde.org/licenses/lgpl21.
*
* @author Karsten Fourmont
* @package SyncMl
*/
class Horde_SyncMl_Device_sync4j extends Horde_SyncMl_Device
{
/**
* Convert the content.
*/
public function convertClient2Server($content, $contentType)
{
list($content, $contentType) =
parent::convertClient2Server($content, $contentType);
switch ($contentType) {
case 'text/x-s4j-sifn' :
case 'text/x-sifn' :
$content = Horde_SyncMl_Device_sync4j::sif2vnote($content);
$contentType = 'text/x-vnote';
break;
case 'text/x-s4j-sifc' :
case 'text/x-sifc' :
$content = Horde_SyncMl_Device_sync4j::sif2vcard($content);
$contentType = 'text/x-vcard';
break;
case 'text/x-s4j-sife' :
case 'text/x-sife' :
$content = Horde_SyncMl_Device_sync4j::sif2vevent($content);
$contentType = 'text/calendar';
break;
case 'text/x-s4j-sift' :
case 'text/x-sift' :
$content = Horde_SyncMl_Device_sync4j::sif2vtodo($content);
$contentType = 'text/calendar';
break;
case 'text/calendar':
case 'text/x-vcalendar':
$si = $GLOBALS['backend']->state->sourceURI;
if (stristr($si, 'fol-') !== false) {
// The Funambol Outlook connector uses invalid STATUS
// values. Actually it maps MeetingStatus values of the
// Outlook event to the STATUS property, which is
// completely useless. So drop the STATUS altogether.
$content = preg_replace('/^STATUS:.*\r?\n/im', '', $content);
}
break;
}
$GLOBALS['backend']->logFile(
Horde_SyncMl_Backend::LOGFILE_DATA,
"\nInput converted for server ($contentType):\n$content\n");
return array($content, $contentType);
}
/**
* Converts the content from the backend to a format suitable for the
* client device.
*
* Strips the uid (primary key) information as client and server might use
* different ones.
*
* @param string $content The content to convert
* @param string $contentType The content type of content as returned
* from the backend
* @param string $database The server database URI.
*
* @return array Three-element array with the converted content, the
* (possibly changed) new content type, and encoding type
* (like b64 as used by Funambol).
*/
public function convertServer2Client($content, $contentType, $database)
{
$database = $GLOBALS['backend']->normalize($database);
list($content, $contentType, $encodingType) =
parent::convertServer2Client($content, $contentType, $database);
if ($this->requestedContentType == $contentType) {
if ($contentType == 'text/calendar' ||
$contentType == 'text/x-vcalendar') {
$si = $GLOBALS['backend']->state->sourceURI;
if (stristr($si, 'fol-') !== false) {
// The Funambol Outlook connector uses invalid STATUS
// values. Actually it maps MeetingStatus values of the
// Outlook event to the STATUS property, which is
// completely useless. So drop the STATUS altogether.
$content = preg_replace('/^STATUS:.*\r?\n/im', '', $content);
}
}
return array($content, $contentType, $encodingType);
}
switch ($contentType) {
case 'text/calendar' :
case 'text/x-vcalendar' :
switch($database) {
case 'calendar':
$content = Horde_SyncMl_Device_sync4j::vevent2sif($content);
$content = base64_encode($content);
$contentType = 'text/x-s4j-sife';
break 2;
case 'tasks':
$content = Horde_SyncMl_Device_sync4j::vtodo2sif($content);
$content = base64_encode($content);
$contentType = 'text/x-s4j-sift';
break 2;
}
break;
case 'text/x-vcard' :
$content = Horde_SyncMl_Device_sync4j::vcard2sif($content);
$content = base64_encode($content);
$contentType = 'text/x-s4j-sifc';
break;
case 'text/x-vnote':
case 'text/plain':
$content = Horde_SyncMl_Device_sync4j::vnote2sif($content);
$content = base64_encode($content);
$contentType = 'text/x-s4j-sifn';
break;
}
$l = "\nOutput converted for client ($contentType):\n" . base64_decode($content) . "\n";
$GLOBALS['backend']->logFile(Horde_SyncMl_Backend::LOGFILE_DATA, $l);
return array($content, $contentType, 'b64');
}
/**
* Decodes a sif xml string to an associative array.
*
* Quick hack to convert from text/vcard and text/vcalendar to
* Sync4J's proprietery sif datatypes and vice versa. For details
* about the sif format see the appendix of the developer guide on
* www.sync4j.org.
*
* @access private
*
* @param string $sif A sif string like v1>v2
*
* @return array Assoc array in utf8 like array ('k1' => 'v1>', 'k2' => 'v2');
*/
public function sif2array($sif)
{
$r = array();
if (preg_match_all('/<([^>]*)>([^<]*)<\/\1>/si', $sif, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
if (isset($r[$match[1]])) {
if (!is_array($r[$match[1]])) {
$r[$match[1]] = array($r[$match[1]]);
}
$r[$match[1]][] = html_entity_decode($match[2]);
} else {
$r[$match[1]] = html_entity_decode($match[2]);
}
}
}
return $r;
}
/**
* Converts a hash to a SIF XML structure.
*
* @param array $array A hash.
* @param string $pre A prefix string for the XML result.
* @param string $post A suffix string for the XML result.
*
* @return string The resulting XML string.
*/
public function array2sif($array, $pre = '', $post = '')
{
$xml = $pre;
foreach ($array as $key => $value) {
if (is_a($value, 'PEAR_Error')) {
continue;
}
if (is_array($value)) {
if (is_array($value[0])) {
$subxml = '';
foreach ($value as $val) {
$subkey = key($val);
$subxml .= '<' . $subkey . '>'
. htmlspecialchars($val[$subkey])
. '' . $subkey . '>';
}
$xml .= '<' . $key . '>' . $subxml . '' . $key . '>';
continue;
}
$value = $value[0];
}
$xml .= '<' . $key . '>' . htmlspecialchars($value) . '' . $key . '>';
}
return $xml . $post;
}
public function sif2vnote($sif)
{
$a = Horde_SyncMl_Device_sync4j::sif2array($sif);
$iCal = new Horde_Icalendar();
$iCal->setAttribute('VERSION', '1.1');
$iCal->setAttribute('PRODID', '-//The Horde Project//SyncML//EN');
$iCal->setAttribute('METHOD', 'PUBLISH');
$vnote = Horde_Icalendar::newComponent('vnote', $iCal);
$vnote->setAttribute('BODY', isset($a['Body']) ? $a['Body'] : '');
if (isset($a['Subject'])) {
$vnote->setAttribute('SUMMARY', $a['Subject']);
}
if (isset($a['Categories'])) {
$vnote->setAttribute('CATEGORIES', $a['Categories']);
}
return $vnote->exportvCalendar();
}
public function sif2vcard($sif)
{
$a = Horde_SyncMl_Device_sync4j::sif2array($sif);
$iCal = new Horde_Icalendar();
$iCal->setAttribute('VERSION', '3.0');
$iCal->setAttribute('PRODID', '-//The Horde Project//SyncML//EN');
$iCal->setAttribute('METHOD', 'PUBLISH');
$vcard = Horde_Icalendar::newComponent('vcard', $iCal);
$map = array(
'FileAs' => array('FN'),
'NickName' => array('NICKNAME'),
'HomeTelephoneNumber' => array('TEL', array('TYPE' => 'HOME')),
'Home2TelephoneNumber' => array('TEL', array('TYPE' => 'HOME')),
'HomeFaxNumber' => array('TEL', array('TYPE' => 'HOME')),
'BusinessTelephoneNumber' => array('TEL', array('TYPE' => 'WORK')),
'Business2TelephoneNumber' => array('TEL', array('TYPE' => 'WORK')),
'BusinessFaxNumber' => array('TEL', array('TYPE' => 'FAX')),
'PrimaryTelephoneNumber' => array('TEL', array('TYPE' => 'PREF')),
'MobileTelephoneNumber' => array('TEL', array('TYPE' => 'CELL')),
'CarTelephoneNumber' => array('TEL', array('TYPE' => 'CAR')),
'PagerNumber' => array('TEL', array('TYPE' => 'PAGER')),
'OtherTelephoneNumber' => array('TEL'),
'OtherFaxNumber' => array('TEL'),
'Email1Address' => array('EMAIL'),
'Email2Address' => array('EMAIL', array('TYPE' => 'HOME')),
'Email3Address' => array('EMAIL', array('TYPE' => 'WORK')),
'HomeLabel' => array('LABEL', array('TYPE' => 'HOME')),
'BusinessLabel' => array('LABEL', array('TYPE' => 'WORK')),
'OtherLabel' => array('LABEL'),
'Profession' => array('ROLE'),
'JobTitle' => array('TITLE'),
'Body' => array('NOTE'),
'WebPage' => array('URL'),
'Birthday' => array('BDAY'),
'Categories' => array('CATEGORIES'),
'Timezone' => array('TZ'),
'Anniversary' => array('X-ANNIVERSARY'),
'Spouse' => array('X-SPOUSE'),
'Children' => array('X-CHILDREN'),
);
foreach ($map as $sif_value => $vcard_value) {
if (isset($a[$sif_value])) {
$vcard->setAttribute($vcard_value[0],
$a[$sif_value],
isset($vcard_value[1]) ? $vcard_value[1] : array());
}
}
$map = array(
array(
'N',
array(Horde_Icalendar_Vcard::N_FAMILY => 'LastName',
Horde_Icalendar_Vcard::N_GIVEN => 'FirstName',
Horde_Icalendar_Vcard::N_ADDL => 'MiddleName',
Horde_Icalendar_Vcard::N_PREFIX => 'Title',
Horde_Icalendar_Vcard::N_SUFFIX => 'Suffix'),
array(),
false),
array(
'ADR',
array(Horde_Icalendar_Vcard::ADR_POB => 'HomeAddressPostOfficeBox',
Horde_Icalendar_Vcard::ADR_EXTEND => '',
Horde_Icalendar_Vcard::ADR_STREET => 'HomeAddressStreet',
Horde_Icalendar_Vcard::ADR_LOCALITY => 'HomeAddressCity',
Horde_Icalendar_Vcard::ADR_REGION => 'HomeAddressState',
Horde_Icalendar_Vcard::ADR_POSTCODE => 'HomeAddressPostalCode',
Horde_Icalendar_Vcard::ADR_COUNTRY => 'HomeAddressCountry'),
array('TYPE' => 'HOME'),
true),
array(
'ADR',
array(Horde_Icalendar_Vcard::ADR_POB => 'BusinessAddressPostOfficeBox',
Horde_Icalendar_Vcard::ADR_EXTEND => '',
Horde_Icalendar_Vcard::ADR_STREET => 'BusinessAddressStreet',
Horde_Icalendar_Vcard::ADR_LOCALITY => 'BusinessAddressCity',
Horde_Icalendar_Vcard::ADR_REGION => 'BusinessAddressState',
Horde_Icalendar_Vcard::ADR_POSTCODE => 'BusinessAddressPostalCode',
Horde_Icalendar_Vcard::ADR_COUNTRY => 'BusinessAddressCountry'),
array('TYPE' => 'WORK'),
true),
array(
'ADR',
array(Horde_Icalendar_Vcard::ADR_POB => 'OtherAddressPostOfficeBox',
Horde_Icalendar_Vcard::ADR_EXTEND => '',
Horde_Icalendar_Vcard::ADR_STREET => 'OtherAddressStreet',
Horde_Icalendar_Vcard::ADR_LOCALITY => 'OtherAddressCity',
Horde_Icalendar_Vcard::ADR_REGION => 'OtherAddressState',
Horde_Icalendar_Vcard::ADR_POSTCODE => 'OtherAddressPostalCode',
Horde_Icalendar_Vcard::ADR_COUNTRY => 'OtherAddressCountry'),
array(),
true),
);
foreach ($map as $struct) {
$values = array();
foreach ($struct[1] as $vcard_value => $sif_value) {
$values[$vcard_value] = isset($a[$sif_value]) ? $a[$sif_value] : '';
}
$check = array_flip($values);
if (count($check) > 1 || strlen(key($check))) {
$vcard->setAttribute($struct[0],
implode(';', $values),
$struct[2],
$struct[3],
$values);
}
}
$org = array();
if (isset($a['CompanyName'])) {
$org[] = $a['CompanyName'];
if (isset($a['Department'])) {
$org[] = $a['Department'];
}
}
if (count($org)) {
$vcard->setAttribute('ORG', null, array(), true, $org);
}
return $vcard->exportvCalendar();
}
public function sif2vevent($sif)
{
$a = Horde_SyncMl_Device_sync4j::sif2array($sif);
$iCal = new Horde_Icalendar();
$iCal->setAttribute('PRODID', '-//The Horde Project//SyncML//EN');
$iCal->setAttribute('METHOD', 'PUBLISH');
$vEvent = Horde_Icalendar::newComponent('vevent', $iCal);
$vEvent->setAttribute('DTSTAMP', time());
$map = array('Subject' => 'SUMMARY',
'Body' => 'DESCRIPTION',
'Categories' => 'CATEGORIES',
'Location' => 'LOCATION');
foreach ($map as $source => $target) {
if (!empty($a[$source])) {
$vEvent->setAttribute($target, $a[$source]);
}
}
if ($a['AllDayEvent'] == 1) {
// Not exactly correct, we ignore the start and end time of
// all-day events and simple assume that the client had set them
// correctly to 0:00.
$startTime = $iCal->_parseDateTime($a['Start']);
$vEvent->setAttribute('DTSTART',
array('year' => date('Y', $startTime),
'month' => date('m', $startTime),
'mday' => date('d', $startTime)),
array('VALUE' => 'DATE'));
$t = $iCal->_parseDateTime($a['End']);
$d = new Horde_Date(array('year' => date('Y', $t),
'month' => date('m', $t),
'mday' => date('d', $t) + 1));
$vEvent->setAttribute('DTEND',$d, array('VALUE' => 'DATE'));
} else {
$startTime = $iCal->_parseDateTime($a['Start']);
$vEvent->setAttribute('DTSTART', $startTime);
$vEvent->setAttribute('DTEND',
$iCal->_parseDateTime($a['End']));
}
if (isset($a['IsRecurring']) && $a['IsRecurring'] == 1) {
$interval = '';
switch ($a['RecurrenceType']) {
case 0:
/* olDaily */
if (!empty($a['DayOfWeekMask'])) {
$freq = 'WEEKLY';
$interval = ';INTERVAL=1';
} else {
$freq = 'DAILY';
$interval = ';INTERVAL=' . $a['Interval'];
}
break;
case 1:
/* olWeekly */
$freq = 'WEEKLY';
$interval = ';INTERVAL=' . $a['Interval'];
break;
case 2:
/* olMonthly */
$freq = 'MONTHLY';
$interval = ';INTERVAL=' . $a['Interval'];
break;
case 3:
/* olMonthNth */
$freq = 'MONTHLY';
$interval = ';INTERVAL=' . $a['Interval'];
break;
case 5:
/* olYearly */
$freq = 'YEARLY';
$interval = ';INTERVAL=' . $a['Interval'];
break;
case 6:
/* olYearNth */
$freq = 'YEARLY';
$interval = ';INTERVAL=' . $a['Interval'];
break;
}
$rrule = 'FREQ=' . $freq;
if (isset($a['Occurrences'])) {
$rrule .= ';COUNT=' . $a['Occurrences'];
} elseif (!isset($a['NoEndDate']) || $a['NoEndDate'] != 1) {
$rrule .= ';UNTIL=' . $a['PatternEndDate'];
}
$rrule .= $interval;
if (!empty($a['DayOfMonth'])) {
$rrule .= ';BYMONTHDAY=' . $a['DayOfMonth'];
}
if (!empty($a['MonthOfYear'])) {
$rrule .= ';BYMONTH=' . $a['MonthOfYear'];
}
if (!empty($a['DayOfWeekMask'])) {
$rrule .= ';BYDAY=';
$icaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
for ($i = $flag = 0; $i <= 7 ; ++$i) {
if (pow(2, $i) & $a['DayOfWeekMask']) {
if ($flag) {
$rrule .= ',';
}
$rrule .= $icaldays[$i];
$flag = true;
}
}
}
$vEvent->setAttribute('RRULE', $rrule);
}
if (isset($a['ExcludeDate'])) {
$dates = array();
if (!is_array($a['ExcludeDate'])) {
$dates[] = $a['AllDayEvent'] == 1
? $iCal->_parseDate($a['ExcludeDate'])
: $iCal->_parseDateTime($a['ExcludeDate']);
} else {
foreach ($a['ExcludeDate'] as $date) {
$dates[] = $a['AllDayEvent'] == 1
? $iCal->_parseDate($date)
: $iCal->_parseDateTime($date);
}
}
if ($a['AllDayEvent'] == 1) {
$vEvent->setAttribute('EXDATE', $dates, array('VALUE' => 'DATE'));
} else {
$vEvent->setAttribute('EXDATE', $dates);
}
}
if (isset($a['ReminderSet']) && $a['ReminderSet'] == 1) {
$vEvent->setAttribute('AALARM', $startTime - $a['ReminderMinutesBeforeStart'] * 60);
}
if (isset($a['BusyStatus'])) {
switch ($a['BusyStatus']) {
case 0:
/* olFree - FREE is not a iCalendar standard value. */
$vEvent->setAttribute('STATUS', 'FREE');
break;
case 1:
/* olTentative */
$vEvent->setAttribute('STATUS', 'TENTATIVE');
break;
case 2:
/* olBusy */
case 3:
/* olOutOfOffice */
$vEvent->setAttribute('STATUS', 'CONFIRMED');
break;
}
}
if (isset($a['Sensitivity'])) {
switch ($a['Sensitivity']) {
case 0:
/* olNormal - FREE is not a iCalendar standard value. */
$vEvent->setAttribute('CLASS', 'PUBLIC');
break;
case 1:
/* olPersonal */
case 2:
/* olPrivate */
$vEvent->setAttribute('CLASS', 'PRIVATE');
break;
case 3:
/* olConfidential */
$vEvent->setAttribute('CLASS', 'CONFIDENTIAL');
break;
}
}
return $vEvent->exportvCalendar();
}
public function sif2vtodo($sif)
{
$a = Horde_SyncMl_Device_sync4j::sif2array($sif);
$iCal = new Horde_Icalendar();
$iCal->setAttribute('PRODID', '-//The Horde Project//SyncML//EN');
$iCal->setAttribute('METHOD', 'PUBLISH');
$vtodo = Horde_Icalendar::newComponent('vtodo', $iCal);
$vtodo->setAttribute('SUMMARY', $a['Subject']);
$vtodo->setAttribute('DESCRIPTION', $a['Body']);
if ($a['Importance'] == 0) {
$vtodo->setAttribute('PRIORITY', 5);
} elseif ($a['Importance'] == 2) {
$vtodo->setAttribute('PRIORITY', 1);
} else {
$vtodo->setAttribute('PRIORITY', 3);
}
if (!empty($a['StartDate']) && $a['StartDate'] != '45001231T230000Z') {
$vtodo->setAttribute('DTSTART', $iCal->_parseDateTime($a['StartDate']));
}
$dueSet = false;
if (!empty($a['DueDate']) && $a['DueDate'] != '45001231T230000Z') {
$vtodo->setAttribute('DUE', $iCal->_parseDateTime($a['DueDate']));
$dueSet = true;
}
if (!empty($a['ReminderSet'])) {
if (!$dueSet) {
$vtodo->setAttribute('DUE', $iCal->_parseDateTime($a['ReminderTime']));
}
$vtodo->setAttribute('AALARM', $iCal->_parseDateTime($a['ReminderTime']));
}
if (!empty($a['Complete'])) {
$vtodo->setAttribute('STATUS', 'COMPLETED');
}
$vtodo->setAttribute('CATEGORIES', isset($a['Categories']) ? $a['Categories'] : '');
if (isset($a['Sensitivity'])) {
switch ($a['Sensitivity']) {
case 0:
/* olNormal */
$vtodo->setAttribute('CLASS', 'PUBLIC');
break;
case 1:
/* olPersonal */
case 2:
/* olPrivate */
$vtodo->setAttribute('CLASS', 'PRIVATE');
break;
case 3:
/* olConfidential */
$vtodo->setAttribute('CLASS', 'CONFIDENTIAL');
break;
}
}
return $vtodo->exportvCalendar();
}
public function vnote2sif($vnote)
{
$iCal = new Horde_Icalendar();
if (!$iCal->parsevCalendar($vnote)) {
// handle plain text:
$a = array('Body' => $vnote);
} else {
$components = $iCal->getComponents();
if (!is_array($components) || count($components) == 0) {
$a = array(
'Body' => $GLOBALS['backend']->t("Error converting notes."));
} else {
$a = array(
'Body' => $components[0]->getAttribute('BODY'),
'Categories' => $components[0]->getAttribute('CATEGORIES'));
try {
$sum = $components[0]->getAttribute('SUMMARY');
$a['Subject'] = $sum;
} catch (Horde_Icalendar_Exception $e) {
}
}
}
return Horde_SyncMl_Device_sync4j::array2sif($a, '', '');
}
public function vcard2sif($vcard)
{
$iCal = new Horde_Icalendar();
if (!$iCal->parsevCalendar($vcard)) {
// @TODO: NEVER use die() in a library.
die("There was an error importing the data.");
}
$components = $iCal->getComponents();
switch (count($components)) {
case 0:
// @TODO: NEVER use die() in a library.
die("No data was found.");
case 1:
$content = $components[0];
break;
default:
// @TODO: NEVER use die() in a library.
die("Multiple components found; only one is supported.");
}
// from here on, the code is taken from
// Turba_Driver::toHash, v 1.65 2005/03/12
// and modified for the Sync4J attribute names.
$attr = $content->getAllAttributes();
foreach ($attr as $item) {
switch ($item['name']) {
case 'FN':
$hash['FileAs'] = $item['value'];
break;
case 'N':
$name = $item['values'];
$hash['LastName'] = $name[Horde_Icalendar_Vcard::N_FAMILY];
$hash['FirstName'] = $name[Horde_Icalendar_Vcard::N_GIVEN];
$hash['MiddleName'] = $name[Horde_Icalendar_Vcard::N_ADDL];
$hash['Title'] = $name[Horde_Icalendar_Vcard::N_PREFIX];
$hash['Suffix'] = $name[Horde_Icalendar_Vcard::N_SUFFIX];
break;
case 'NICKNAME':
$hash['NickName'] = $item['value'];
break;
// For vCard 3.0.
case 'ADR':
if (isset($item['params']['TYPE'])) {
if (!is_array($item['params']['TYPE'])) {
$item['params']['TYPE'] = array($item['params']['TYPE']);
}
} else {
$item['params']['TYPE'] = array();
if (isset($item['params']['WORK'])) {
$item['params']['TYPE'][] = 'WORK';
}
if (isset($item['params']['HOME'])) {
$item['params']['TYPE'][] = 'HOME';
}
}
$address = $item['values'];
foreach ($item['params']['TYPE'] as $adr) {
switch (Horde_String::upper($adr)) {
case 'HOME':
$prefix = 'HomeAddress';
break;
case 'WORK':
$prefix = 'BusinessAddress';
break;
default:
$prefix = 'HomeAddress';
}
if ($prefix) {
$hash[$prefix . 'Street'] =
isset($address[Horde_Icalendar_Vcard::ADR_STREET])
? $address[Horde_Icalendar_Vcard::ADR_STREET]
: null;
$hash[$prefix . 'City'] =
isset($address[Horde_Icalendar_Vcard::ADR_LOCALITY])
? $address[Horde_Icalendar_Vcard::ADR_LOCALITY]
: null;
$hash[$prefix . 'State'] =
isset($address[Horde_Icalendar_Vcard::ADR_REGION])
? $address[Horde_Icalendar_Vcard::ADR_REGION]
: null;
$hash[$prefix . 'PostalCode'] =
isset($address[Horde_Icalendar_Vcard::ADR_POSTCODE])
? $address[Horde_Icalendar_Vcard::ADR_POSTCODE]
: null;
$hash[$prefix . 'Country'] =
isset($address[Horde_Icalendar_Vcard::ADR_COUNTRY])
? $address[Horde_Icalendar_Vcard::ADR_COUNTRY]
: null;
$hash[$prefix . 'PostOfficeBox'] =
isset($address[Horde_Icalendar_Vcard::ADR_POB])
? $address[Horde_Icalendar_Vcard::ADR_POB]
: null;
}
}
break;
case 'TEL':
if (isset($item['params']['FAX'])) {
if (isset($item['params']['WORK'])) {
$hash['BusinessFaxNumber'] = $item['value'];
} elseif (isset($item['params']['HOME'])) {
$hash['HomeFaxNumber'] = $item['value'];
} else {
$hash['OtherFaxNumber'] = $item['value'];
}
} elseif (isset($item['params']['TYPE'])) {
if (!is_array($item['params']['TYPE'])) {
$item['params']['TYPE'] = array($item['params']['TYPE']);
}
// For vCard 3.0.
foreach ($item['params']['TYPE'] as $tel) {
if (Horde_String::upper($tel) == 'WORK') {
$hash['BusinessTelephoneNumber'] = $item['value'];
} elseif (Horde_String::upper($tel) == 'HOME') {
$hash['HomeTelephoneNumber'] = $item['value'];
} elseif (Horde_String::upper($tel) == 'CELL') {
$hash['MobileTelephoneNumber'] = $item['value'];
} elseif (Horde_String::upper($tel) == 'FAX') {
$hash['BusinessFaxNumber'] = $item['value'];
}
}
} else {
if (isset($item['params']['HOME'])) {
$hash['HomeTelephoneNumber'] = $item['value'];
} elseif (isset($item['params']['WORK'])) {
$hash['BusinessTelephoneNumber'] = $item['value'];
} elseif (isset($item['params']['CELL'])) {
$hash['MobileTelephoneNumber'] = $item['value'];
} elseif (!isset($hash['HomeTelephoneNumber'])) {
$hash['HomeTelephoneNumber'] = $item['value'];
}
}
break;
case 'EMAIL':
$email_set = false;
if (isset($item['params']['HOME']) && (!isset($hash['Email2Address']) ||
isset($item['params']['PREF']))) {
$hash['Email2Address'] = Horde_Icalendar_Vcard::getBareEmail($item['value']);
$email_set = true;
} elseif (isset($item['params']['WORK']) && (!isset($hash['Email3Address']) ||
isset($item['params']['PREF']))) {
$hash['Email3Address'] = Horde_Icalendar_Vcard::getBareEmail($item['value']);
$email_set = true;
} elseif (isset($item['params']['TYPE'])) {
if (!is_array($item['params']['TYPE'])) {
$item['params']['TYPE'] = array($item['params']['TYPE']);
}
if (in_array('HOME', $item['params']['TYPE']) &&
(!isset($hash['Email2Address']) || in_array('PREF', $item['params']['TYPE']))) {
$hash['Email2Address'] = Horde_Icalendar_Vcard::getBareEmail($item['value']);
$email_set = true;
} elseif (in_array('WORK', $item['params']['TYPE']) &&
(!isset($hash['Email3Address']) || in_array('PREF', $item['params']['TYPE']))) {
$hash['Email3Address'] = Horde_Icalendar_Vcard::getBareEmail($item['value']);
$email_set = true;
}
}
if (!$email_set && (!isset($hash['Email1Address']) || isset($item['params']['PREF']))) {
$hash['Email1Address'] = Horde_Icalendar_Vcard::getBareEmail($item['value']);
}
break;
case 'TITLE':
$hash['JobTitle'] = $item['value'];
break;
case 'ORG':
$values = preg_split('/(?',
'');
}
public function vevent2sif($vcard)
{
/* Some special handling for all-day vEvents that are not passed
* as TYPE=DATE (TYPE=DATE does not exist for vCalendar 1.0) */
if (preg_match('/(\r\n|\r|\n)DTSTART:.*T000000(\r\n|\r|\n)/', $vcard)) {
if (preg_match('/(\r\n|\r|\n)DTEND:(\d\d\d\d)(\d\d)(\d\d)T235959(\r\n|\r|\n)/', $vcard, $m)) {
$vcard = preg_replace('/(\r\n|\r|\n)DTSTART:(.*)T000000(\r\n|\r|\n)/',
"$1DTSTART;VALUE=DATE:$2$3", $vcard);
$vcard = preg_replace('/(\r\n|\r|\n)DTEND:(.*)T235959(\r\n|\r|\n)/',
"$1DTEND;VALUE=DATE:$2$3", $vcard);
}
// @TODO: else: handle case with DTEND= T240000
}
$iCal = new Horde_Icalendar();
if (!$iCal->parsevCalendar($vcard)) {
// @TODO: NEVER use die() in a library.
die("There was an error importing the data.");
}
$components = $iCal->getComponents();
switch (count($components)) {
case 0:
// @TODO: NEVER use die() in a library.
die("No data was found.");
case 1:
$content = $components[0];
break;
default:
// @TODO: NEVER use die() in a library.
die("Multiple components found; only one is supported.");
}
$hash = array('ReminderSet' => 0,
'IsRecurring' => 0,
'BusyStatus' => 2);
$alarm = $end = null;
$start = $content->getAttribute('DTSTART');
$start_params = $content->getAttribute('DTSTART', true);
if (!empty($start_params[0]['VALUE']) &&
$start_params[0]['VALUE'] == 'DATE') {
$hash['AllDayEvent'] = 1;
$hash['Start'] = sprintf('%04d-%02d-%02d',
$start['year'],
$start['month'],
$start['mday']);
$start = mktime(0, 0, 0,
$start['month'],
$start['mday'],
$start['year']);
} else {
$hash['AllDayEvent'] = 0;
$hash['Start'] = Horde_Icalendar::_exportDateTime($start);
}
foreach ($content->getAllAttributes() as $item) {
$GLOBALS['backend']->logMessage(
sprintf('Sync4j for name %s, value %s',
$item['name'],
is_string($item['value'])
? $item['value'] : var_export($item['value'], true)), 'DEBUG');
switch (Horde_String::upper($item['name'])) {
case 'DTSTART':
break;
case 'DTEND':
if (!empty($item['params']['VALUE']) &&
$item['params']['VALUE'] == 'DATE') {
$hash['AllDayEvent'] = 1;
$date = new Horde_Date($item['value']['year'],
$item['value']['month'],
$item['value']['mday']);
$date->mday--;
$hash['End'] = $date->format('Y-m-d');
$end = $date->datestamp();
} else {
$hash['AllDayEvent'] = 0;
$hash['End'] = Horde_Icalendar::_exportDateTime($item['value']);
$end = $item['value'];
}
break;
case 'SUMMARY':
$hash['Subject'] = $item['value'];
break;
case 'DESCRIPTION':
$hash['Body'] = $item['value'];
break;
case 'LOCATION':
$hash['Location'] = $item['value'];
break;
case 'CATEGORIES':
$hash['Categories'] = $item['value'];
break;
case 'AALARM':
$hash['ReminderSet'] = 1;
$alarm = $item['value'];
break;
case 'STATUS':
switch (Horde_String::upper($item['value'])) {
case 'FREE':
case 'CANCELLED':
$hash['BusyStatus'] = 0;
break;
case 'TENTATIVE':
$hash['BusyStatus'] = 1;
break;
case 'CONFIRMED':
$hash['BusyStatus'] = 2;
break;
}
break;
case 'CLASS':
switch (Horde_String::upper($item['value'])) {
case 'PUBLIC':
$hash['Sensitivity'] = 0;
break;
case 'PRIVATE':
$hash['Sensitivity'] = 2;
break;
case 'CONFIDENTIAL':
$hash['Sensitivity'] = 3;
break;
}
break;
case 'RRULE':
// Parse the recurrence rule into keys and values.
$rdata = array();
$parts = explode(';', $item['value']);
foreach ($parts as $part) {
list($key, $value) = explode('=', $part, 2);
$rdata[Horde_String::upper($key)] = $value;
}
if (!isset($rdata['FREQ'])) {
break;
}
$hash['IsRecurring'] = 1;
if (isset($rdata['BYDAY'])) {
$maskdays = array('SU' => Horde_Date::MASK_SUNDAY,
'MO' => Horde_Date::MASK_MONDAY,
'TU' => Horde_Date::MASK_TUESDAY,
'WE' => Horde_Date::MASK_WEDNESDAY,
'TH' => Horde_Date::MASK_THURSDAY,
'FR' => Horde_Date::MASK_FRIDAY,
'SA' => Horde_Date::MASK_SATURDAY);
$days = explode(',', $rdata['BYDAY']);
$mask = 0;
foreach ($days as $day) {
$instance = (int)$day;
$mask |= $maskdays[str_replace($instance, '', $day)];
}
}
$hash['Interval'] = isset($rdata['INTERVAL'])
? $rdata['INTERVAL']
: 1;
switch (Horde_String::upper($rdata['FREQ'])) {
case 'DAILY':
$hash['RecurrenceType'] = 0;
break;
case 'WEEKLY':
$hash['RecurrenceType'] = 1;
if (isset($rdata['BYDAY'])) {
$hash['DayOfWeekMask'] = $mask;
}
break;
case 'MONTHLY':
if (isset($rdata['BYDAY'])) {
$hash['RecurrenceType'] = 3;
$hash['Instance'] = $instance;
$hash['DayOfWeekMask'] = $mask;
} else {
$hash['RecurrenceType'] = 2;
$hash['DayOfMonth'] = date('j', $start);
}
break;
case 'YEARLY':
if (isset($rdata['BYDAY'])) {
$hash['RecurrenceType'] = 6;
$hash['Instance'] = $instance;
$hash['DayOfWeekMask'] = $mask;
} else {
$hash['RecurrenceType'] = 5;
$hash['DayOfMonth'] = date('j', $start);
}
$hash['MonthOfYear'] = date('n', $start);
unset($hash['Interval']);
break;
}
if (isset($rdata['UNTIL'])) {
$hash['NoEndDate'] = 0;
$hash['PatternEndDate'] = $rdata['UNTIL'];
} elseif (isset($rdata['COUNT'])) {
$hash['NoEndDate'] = 0;
$hash['Occurrences'] = $rdata['COUNT'];
} else {
$hash['NoEndDate'] = 1;
}
break;
case 'EXDATE':
if (empty($hash['Exceptions'])) {
$hash['Exceptions'] = array();
}
foreach ($item['values'] as $date) {
if ($hash['AllDayEvent'] == 1) {
$d = new Horde_Date(array('year' => $date['year'],
'month' => $date['month'],
'mday' => $date['mday'] + 1));
$hash['Exceptions'][] = array('ExcludeDate' => $d->format('Y-m-d'));
} else {
$hash['Exceptions'][] = array('ExcludeDate' => Horde_Icalendar::_exportDate($date));
}
}
break;
}
}
if (!empty($start)) {
if ($hash['ReminderSet'] && !empty($alarm) && $start != $alarm) {
$hash['ReminderMinutesBeforeStart'] = ($start - $alarm) / 60;
} else {
// Parse VALARM components.
foreach ($content->getComponents() as $component) {
if ($component->getType() != 'vAlarm') {
continue;
}
try {
$trigger = $component->getAttribute('TRIGGER');
} catch (Horde_Icalendar_Exception $e) {
continue;
}
if (is_array($trigger) || empty($trigger)) {
continue;
}
$hash['ReminderSet'] = 1;
$hash['ReminderMinutesBeforeStart'] = (-$trigger) / 60;
}
}
}
if (empty($hash['AllDayEvent']) && !empty($start) &&
!empty($end) && $start != $end) {
$hash['Duration'] = ($end - $start) / 60;
$GLOBALS['backend']->logMessage(
'Duration set to ' . $hash['Duration'], 'DEBUG');
}
return Horde_SyncMl_Device_sync4j::array2sif(
$hash,
'',
'');
}
public function vtodo2sif($vcard)
{
$iCal = new Horde_Icalendar();
if (!$iCal->parsevCalendar($vcard)) {
return PEAR::raiseError('There was an error importing the data.');
}
$components = $iCal->getComponents();
switch (count($components)) {
case 0:
return PEAR::raiseError('No data was found');
case 1:
$content = $components[0];
break;
default:
return PEAR::raiseError('Multiple components found; only one is supported.');
}
$hash['Complete'] = 0;
$due = false;
$attr = $content->getAllAttributes();
foreach ($attr as $item) {
switch ($item['name']) {
case 'SUMMARY':
$hash['Subject'] = $item['value'];
break;
case 'DESCRIPTION':
$hash['Body'] = $item['value'];
break;
case 'PRIORITY':
if ($item['value'] == 1) {
$hash['Importance'] = 2;
} elseif ($item['value'] == 5) {
$hash['Importance'] = 0;
} else {
$hash['Importance'] = 1;
}
break;
case 'DTSTART':
$hash['StartDate'] = Horde_Icalendar::_exportDateTime($item['value']);
break;
case 'DUE':
$hash['DueDate'] = Horde_Icalendar::_exportDateTime($item['value']);
$due = $item['value'];
break;
case 'AALARM':
$hash['ReminderTime'] = $item['value'];
$hash['ReminderSet'] = 1;
break;
case 'STATUS':
$hash['Complete'] = $item['value'] == 'COMPLETED' ? 1 : 0;
break;
case 'CATEGORIES':
$hash['Categories'] = $item['value'];
break;
case 'CLASS':
switch (Horde_String::upper($item['value'])) {
case 'PUBLIC':
$hash['Sensitivity'] = 0;
break;
case 'PRIVATE':
$hash['Sensitivity'] = 2;
break;
case 'CONFIDENTIAL':
$hash['Sensitivity'] = 3;
break;
}
break;
}
}
if ($due && !isset($hash['ReminderSet'])) {
// Parse VALARM components.
foreach ($content->getComponents() as $component) {
if ($component->getType() != 'vAlarm') {
continue;
}
try {
$trigger = $component->getAttribute('TRIGGER');
} catch (Horde_Icalendar_Exception $e) {
continue;
}
if (is_array($trigger) || empty($trigger)) {
continue;
}
$hash['ReminderSet'] = 1;
$hash['ReminderTime'] = Horde_Icalendar::_exportDateTime($due - $trigger);
}
}
return Horde_SyncMl_Device_sync4j::array2sif(
$hash,
'',
'');
}
/**
* Sync4j as of Funambol Outlook connector 3.0.15 can't deal
* with