package.xml 0000664 0001750 0001750 00000323521 12700700443 011302 0 ustar jan jan
Horde_SyncMlpear.horde.orgSyncMLHorde_SyncMl provides an API for processing SyncML requestsClasses for implementing a SyncML server.Jan Schneiderjanjan@horde.orgyes2016-04-052.0.71.0.0stablestableLGPL-2.1
* [jan] Update Greek translation (Limperis Antonis <limperis@cti.gr>).
5.3.08.0.0alpha18.0.0alpha11.7.0Horde_Datepear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Icalendarpear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Logpear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Supportpear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Utilpear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Xml_Wbxmlpear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Translationpear.horde.org2.2.03.0.0alpha13.0.0alpha1Horde_Authpear.horde.org2.0.03.0.0alpha13.0.0alpha1Horde_Corepear.horde.org2.0.03.0.0alpha13.0.0alpha10.0.10.0.1alphaalpha2004-01-19LGPL-2.1
Initial implementation
0.0.30.0.3alphaalpha2005-04-23LGPL-2.1
Major update
0.6.00.6.0betabeta2006-01-01LGPL-2.1
Passes all tests of SyncML conformance suite now.
0.7.00.7.0betabeta2011-03-06LGPL-2.1
Make the SyncML package independant from Horde, provide a new Sql backend as a reference implementation for a backend.
1.0.0beta11.0.0betabeta2011-03-16LGPL-2.1
* First beta release for Horde 4.
1.0.0RC11.0.0betabeta2011-03-22LGPL-2.1
* First release candidate for Horde 4.
* [jan] Fix calendar synchronization with certain Nokia phones (Bug #9646).
1.0.0RC21.0.0betabeta2011-03-29LGPL-2.1
* Second release candidate for Horde 4.
1.0.01.0.0stablestable2011-04-06LGPL-2.1
* First stable release for Horde 4.
* [jan] Add removeMaps() method to Horde backend driver.
* [jan] Convert database access to use Horde_Db.
1.0.11.0.0stablestable2011-05-03LGPL-2.1
* [mms] Fix issue causing slow syncs only (Bug #10008).
1.0.21.0.0stablestable2011-05-25LGPL-2.1
* [mms] Complete fix for issue causing slow syncs only (Bug #10008).
1.0.31.0.0stablestable2011-07-05LGPL-2.1
* [jan] Update Lithuanian translation.
* [jan] Fix duplication of objects during synchronization (joniw@t-online.de, Bug #10081).
1.0.41.0.0stablestable2011-07-27LGPL-2.1
* [jan] Fix log level output in log file.
* [jan] Update Latvian translation.
* [mjr] Use the more efficient getChanges() API.
1.0.51.0.0stablestable2011-08-17LGPL-2.1
* [jan] Fix logging errors while retrieving server changes.
1.0.61.0.0stablestable2011-11-02LGPL-2.1
* [jan] Fix encoding of CDATA (horde@chk.cksf.de, Bug #10692).
1.0.71.0.0stablestable2011-12-21LGPL-2.1
* [jan] Catch exceptions when changing or retrieving objects from the applications.
1.0.81.0.0stablestable2012-01-17LGPL-2.1
* [jan] Fix undefined method while synchronizing events with Funambol (Bug #10908).
1.0.91.0.0stablestable2012-05-01LGPL-2.1
* [jan] Don't corrupt binary data like images if sent in several messages (Jonathan Westerholt <joniw@t-online.de>, Bug #10864).
2.0.0alpha11.0.0alphastable2012-07-06LGPL-2.1
* First alpha release for Horde 5.
2.0.0beta11.0.0betastable2012-07-19LGPL-2.1
* First beta release for Horde 5.
* [jan] Fix session handling (Bug #11242).
* [jan] Fix finding locale directory if installed with PEAR.
2.0.01.0.0stablestable2012-10-30LGPL-2.1
* First stable release for Horde 5.
2.0.11.0.0stablestable2012-11-06LGPL-2.1
* [jan] Update Dutch translation (Arjen de Korte <build+horde@de-korte.org>).
2.0.21.0.0stablestable2013-01-10LGPL-2.1
* [jan] Update Basque translation (Ibon Igartua <ibon.igartua@ehu.es>).
2.0.31.0.0stablestable2013-03-05LGPL-2.1
* [jan] Improve documentation.
2.0.41.0.0stablestable2014-07-24LGPL-2.1
* [mjr] Hotfix to deal with failure exporting non-contact data due to inconsistency in export methods between applications (Bug #13394).
2.0.51.0.0stablestable2014-12-03LGPL-2.1
* [jan] Fix exporting notes to Funambol clients (horde@albasoft.com, Bug #9487).
* [jan] Fix creating server-client-mapping if backend returns multiple server IDs per client ID (horde@albasoft.com, Bug #13706).
2.0.61.0.0stablestable2016-02-02LGPL-2.1
* [jan] Split large objects into multiple messages (thomas@trethan.net, Request #11071).
* [jan] Remove workarounds for ancient Synthesis clients (Bug #10942).
* [jan] Mark PHP 7 as supported.
2.0.71.0.0stablestable2016-04-05LGPL-2.1
* [jan] Update Greek translation (Limperis Antonis <limperis@cti.gr>).
Horde_SyncMl-2.0.7/doc/Horde/SyncMl/COPYING 0000664 0001750 0001750 00000057646 12700700442 016236 0 ustar jan jan 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
Horde_SyncMl-2.0.7/doc/Horde/SyncMl/INSTALL.p900.txt 0000664 0001750 0001750 00000002711 12700700442 017520 0 ustar jan jan
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.
Horde_SyncMl-2.0.7/doc/Horde/SyncMl/README.program_flow.txt 0000664 0001750 0001750 00000007651 12700700442 021365 0 ustar jan jan 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.
Horde_SyncMl-2.0.7/doc/Horde/SyncMl/README.syncml_primer.txt 0000664 0001750 0001750 00000011013 12700700442 021535 0 ustar jan jan
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...
Horde_SyncMl-2.0.7/doc/Horde/SyncMl/TODO 0000664 0001750 0001750 00000001511 12700700442 015647 0 ustar jan jan 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
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Backend/Horde.php 0000664 0001750 0001750 00000104442 12700700443 020271 0 ustar jan jan
* @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)
{
// Hotfix hack to work around differing function signatures for
// export methods in each database. See Bug: 13394
$parameters = array($suid, $contentType);
$database = $this->normalize($databaseURI);
if ($database == 'contacts') {
$parameters[] = null;
$parameters[] = $fields;
}
try {
return $GLOBALS['registry']->call(
$database . '/export', $parameters);
} 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')));
$suid = is_array($suid) ? $suid[0] : $suid;
$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::log($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";
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Backend/Sql.php 0000664 0001750 0001750 00000126045 12700700443 017772 0 ustar jan jan
* @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);
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Command/Alert.php 0000664 0001750 0001750 00000026456 12700700443 020336 0 ustar jan jan
* @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 sending either pending elements or
// OK status response.
if ($this->_alert == Horde_SyncMl::ALERT_NEXT_MESSAGE) {
if ($sync = &$state->getSync($this->_targetLocURI)) {
if ($sync->hasPendingElements()) {
$sync->createSyncOutput($this->_outputHandler);
return;
}
}
$this->_outputHandler->outputStatus($this->_cmdID, $this->_cmdName,
Horde_SyncMl::RESPONSE_OK);
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());
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Command/Final.php 0000664 0001750 0001750 00000002643 12700700443 020310 0 ustar jan jan
* @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);
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Command/Get.php 0000664 0001750 0001750 00000002640 12700700443 017773 0 ustar jan jan
* @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);
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Command/Map.php 0000664 0001750 0001750 00000006542 12700700443 017776 0 ustar jan jan
* @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);
} elseif ($element == 'MaxObjSize') {
//
$this->_maxObjSize = 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;
}
if (!empty($this->_maxObjSize)) {
$backend->state->maxObjSize = $this->_maxObjSize;
}
$backend->setupState();
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Device/Nokia.php 0000664 0001750 0001750 00000006446 12700700443 020146 0 ustar jan jan
* @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;
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Device/P800.php 0000664 0001750 0001750 00000014057 12700700443 017531 0 ustar jan jan
* @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;
}
}
Horde_SyncMl-2.0.7/lib/Horde/SyncMl/Device/Sync4j.php 0000664 0001750 0001750 00000140465 12700700443 020257 0 ustar jan jan ' which should be the default anyhow.
*
* Copyright 2005-2016 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
{
public function getPreferredContentTypeClient($serverSyncURI, $sourceSyncURI)
{
$contentType = parent::getPreferredContentTypeClient($serverSyncURI, $sourceSyncURI);
switch ($contentType) {
case 'text/x-s4j-sifn' :
case 'text/x-sifn' :
$contentType = 'text/x-vnote';
break;
case 'text/x-s4j-sifc' :
case 'text/x-sifc' :
$contentType = 'text/x-vcard';
break;
case 'text/x-s4j-sife' :
case 'text/x-sife' :
$contentType = 'text/calendar';
break;
case 'text/x-s4j-sift' :
case 'text/x-sift' :
$contentType = 'text/calendar';
break;
}
return $contentType;
}
/**
* 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]->getAttributeDefault('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