SynchronizationTool.py 25.8 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
## Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#          Sebastien Robin <seb@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

"""\
ERP portal_synchronizations tool.
"""

from OFS.SimpleItem import SimpleItem
from OFS.Folder import Folder
from Products.CMFCore.utils import UniqueObject
from Globals import InitializeClass, DTMLFile, PersistentMapping, Persistent
from AccessControl import ClassSecurityInfo, getSecurityManager
from Products.CMFCore import CMFCorePermissions
from Products.ERP5SyncML import _dtmldir
from Publication import Publication,Subscriber
from Subscription import Subscription,Signature
from xml.dom.ext.reader.Sax2 import FromXmlStream, FromXml
from XMLSyncUtils import *
Sebastien Robin's avatar
Sebastien Robin committed
42
from Products.ERP5Type import Permissions
Jean-Paul Smets's avatar
Jean-Paul Smets committed
43 44
from PublicationSynchronization import PublicationSynchronization
from SubscriptionSynchronization import SubscriptionSynchronization
45 46
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.User import UnrestrictedUser
Jean-Paul Smets's avatar
Jean-Paul Smets committed
47 48
#import sys
#import StringIO
49
import urllib
Jean-Paul Smets's avatar
Jean-Paul Smets committed
50
import string
51 52
import commands
import random
Jean-Paul Smets's avatar
Jean-Paul Smets committed
53 54
from zLOG import *

55

Jean-Paul Smets's avatar
Jean-Paul Smets committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
from Conduit.ERP5Conduit import ERP5Conduit

class SynchronizationError( Exception ):
  pass

class SynchronizationTool( UniqueObject, SimpleItem,
                           SubscriptionSynchronization, PublicationSynchronization ):
  """
    This tool implements the synchronization algorithm
  """


  id       = 'portal_synchronizations'
  meta_type    = 'ERP5 Synchronizations'

  security = ClassSecurityInfo()

  #
  #  Default values.
  #
  list_publications = PersistentMapping()
  list_subscriptions = PersistentMapping()

  # Do we want to use emails ?
  #email = None
  email = 1
  same_export = 1

  def __init__( self ):
    self.list_publications = PersistentMapping()
    self.list_subscriptions = PersistentMapping()

  #
  #  ZMI methods
  #
  manage_options = ( ( { 'label'   : 'Overview'
             , 'action'   : 'manage_overview'
             }
            , { 'label'   : 'Publications'
             , 'action'   : 'managePublications'
             }
            , { 'label'   : 'Subscriptions'
             , 'action'   : 'manageSubscriptions'
             }
            , { 'label'   : 'Conflicts'
             , 'action'   : 'manageConflicts'
             }
            )
           + SimpleItem.manage_options
           )

  security.declareProtected( CMFCorePermissions.ManagePortal
               , 'manage_overview' )
  manage_overview = DTMLFile( 'dtml/explainSynchronizationTool', globals() )

  security.declareProtected( CMFCorePermissions.ManagePortal
               , 'managePublications' )
  managePublications = DTMLFile( 'dtml/managePublications', globals() )

  security.declareProtected( CMFCorePermissions.ManagePortal
116 117
               , 'manage_addPublicationForm' )
  manage_addPublicationForm = DTMLFile( 'dtml/manage_addPublication', globals() )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
118 119 120 121 122 123 124 125 126 127

  security.declareProtected( CMFCorePermissions.ManagePortal
               , 'manageSubsciptions' )
  manageSubscriptions = DTMLFile( 'dtml/manageSubscriptions', globals() )

  security.declareProtected( CMFCorePermissions.ManagePortal
               , 'manageConflicts' )
  manageConflicts = DTMLFile( 'dtml/manageConflicts', globals() )

  security.declareProtected( CMFCorePermissions.ManagePortal
128 129
               , 'manage_addSubscriptionForm' )
  manage_addSubscriptionForm = DTMLFile( 'dtml/manage_addSubscription', globals() )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

  security.declareProtected( CMFCorePermissions.ManagePortal
               , 'editProperties' )
  def editProperties( self
           , publisher=None
           , REQUEST=None
           ):
    """
      Form handler for "tool-wide" properties (including list of
      metadata elements).
    """
    if publisher is not None:
      self.publisher = publisher

    if REQUEST is not None:
      REQUEST[ 'RESPONSE' ].redirect( self.absolute_url()
                    + '/propertiesForm'
                    + '?manage_tabs_message=Tool+updated.'
                    )

150 151
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_addPublication')
  def manage_addPublication(self, id, publication_url, destination_path,
152
            query, xml_mapping, gpg_key, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
153 154 155 156
    """
      create a new publication
    """
    pub = Publication(id, publication_url, destination_path,
157
                      query, xml_mapping, gpg_key)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
158 159 160 161 162 163
    if len(self.list_publications) == 0:
      self.list_publications = PersistentMapping()
    self.list_publications[id] = pub
    if RESPONSE is not None:
      RESPONSE.redirect('managePublications')

164 165
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_addSubscription')
  def manage_addSubscription(self, id, publication_url, subscription_url,
166
                       destination_path, query, xml_mapping, gpg_key, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
167
    """
Sebastien Robin's avatar
Sebastien Robin committed
168
      XXX should be renamed as addSubscription
Jean-Paul Smets's avatar
Jean-Paul Smets committed
169 170 171
      create a new subscription
    """
    sub = Subscription(id, publication_url, subscription_url,
172
                       destination_path, query, xml_mapping, gpg_key)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
173 174 175 176 177 178
    if len(self.list_subscriptions) == 0:
      self.list_subscriptions = PersistentMapping()
    self.list_subscriptions[id] = sub
    if RESPONSE is not None:
      RESPONSE.redirect('manageSubscriptions')

179 180
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_editPublication')
  def manage_editPublication(self, id, publication_url, destination_path,
181
                       query, xml_mapping, gpg_key, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
182 183 184 185
    """
      modify a publication
    """
    pub = Publication(id, publication_url, destination_path,
186
                      query, xml_mapping, gpg_key)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
187 188 189 190
    self.list_publications[id] = pub
    if RESPONSE is not None:
      RESPONSE.redirect('managePublications')

191 192
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_editSubscription')
  def manage_editSubscription(self, id, publication_url, subscription_url,
193
             destination_path, query, xml_mapping, gpg_key, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
194 195 196 197
    """
      modify a subscription
    """
    sub = Subscription(id, publication_url, subscription_url,
198
                       destination_path, query, xml_mapping, gpg_key)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
199 200 201 202
    self.list_subscriptions[id] = sub
    if RESPONSE is not None:
      RESPONSE.redirect('manageSubscriptions')

203 204
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_deletePublication')
  def manage_deletePublication(self, id, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
205 206 207 208 209 210 211
    """
      delete a publication
    """
    del self.list_publications[id]
    if RESPONSE is not None:
      RESPONSE.redirect('managePublications')

212 213
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_deleteSubscription')
  def manage_deleteSubscription(self, id, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
214 215 216 217 218 219 220
    """
      delete a subscription
    """
    del self.list_subscriptions[id]
    if RESPONSE is not None:
      RESPONSE.redirect('manageSubscriptions')

221 222
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_resetPublication')
  def manage_resetPublication(self, id, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
223 224 225 226 227 228 229
    """
      reset a publication
    """
    self.list_publications[id].resetAllSubscribers()
    if RESPONSE is not None:
      RESPONSE.redirect('managePublications')

230 231
  security.declareProtected(Permissions.ModifyPortalContent, 'manage_resetSubscription')
  def manage_resetSubscription(self, id, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
232 233 234 235 236 237 238 239
    """
      reset a subscription
    """
    self.list_subscriptions[id].resetAllSignatures()
    self.list_subscriptions[id].resetAnchors()
    if RESPONSE is not None:
      RESPONSE.redirect('manageSubscriptions')

Sebastien Robin's avatar
Sebastien Robin committed
240
  security.declareProtected(Permissions.AccessContentsInformation,'getPublicationList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
241 242 243 244 245 246 247 248 249
  def getPublicationList(self):
    """
      Return a list of publications
    """
    return_list = []
    if type(self.list_publications) is type([]): # For compatibility with old
                                                 # SynchronizationTool, XXX To be removed
      self.list_publications = PersistentMapping()
    for key in self.list_publications.keys():
250
      LOG('getPublicationList',0,'key: %s, pub:%s' % (key,repr(self.list_publications[key])))
251
      return_list += [self.list_publications[key].__of__(self)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
252 253
    return return_list

254 255 256
  security.declareProtected(Permissions.AccessContentsInformation,'getPublication')
  def getPublication(self, id):
    """
257
      Return the  publications with this id
258 259
    """
    #self.list_publications=PersistentMapping()
260 261 262
    if self.list_publications.has_key(id):
      return self.list_publications[id].__of__(self)
    return None
263

Sebastien Robin's avatar
Sebastien Robin committed
264
  security.declareProtected(Permissions.AccessContentsInformation,'getSubscriptionList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
265 266 267 268 269 270 271 272 273
  def getSubscriptionList(self):
    """
      Return a list of publications
    """
    return_list = []
    if type(self.list_subscriptions) is type([]): # For compatibility with old
                                                 # SynchronizationTool, XXX To be removed
      self.list_subscriptions = PersistentMapping()
    for key in self.list_subscriptions.keys():
274
      return_list += [self.list_subscriptions[key].__of__(self)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
275 276
    return return_list

277 278 279 280 281 282 283 284 285 286
  def getSubscription(self, id):
    """
      Returns the subscription with this id
    """
    for subscription in self.getSubscriptionList():
      if subscription.getId()==id:
        return subscription
    return None


Sebastien Robin's avatar
Sebastien Robin committed
287
  security.declareProtected(Permissions.AccessContentsInformation,'getSynchronizationList')
288
  def getSynchronizationList(self):
289 290
    """
      Returns the list of subscriptions and publications
Sebastien Robin's avatar
Sebastien Robin committed
291

292 293 294
    """
    return self.getSubscriptionList() + self.getPublicationList()

Sebastien Robin's avatar
Sebastien Robin committed
295
  security.declareProtected(Permissions.AccessContentsInformation,'getSubscriberList')
296 297 298 299 300 301 302 303 304 305
  def getSubscriberList(self):
    """
      Returns the list of subscribers and subscriptions
    """
    s_list = []
    s_list += self.getSubscriptionList()
    for publication in self.getPublicationList():
      s_list += publication.getSubscriberList()
    return s_list

Sebastien Robin's avatar
Sebastien Robin committed
306
  security.declareProtected(Permissions.AccessContentsInformation,'getConflictList')
307
  def getConflictList(self, context=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
308 309 310 311
    """
    Retrieve the list of all conflicts
    Here the list is as follow :
    [conflict_1,conflict2,...] where conflict_1 is like:
312
    ['publication',publication_id,object.getPath(),property_id,publisher_value,subscriber_value]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
313
    """
314
    path = self.resolveContext(context)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
315 316
    conflict_list = []
    for publication in self.getPublicationList():
Sebastien Robin's avatar
Sebastien Robin committed
317 318 319 320
      for subscriber in publication.getSubscriberList():
        sub_conflict_list = subscriber.getConflictList()
        for conflict in sub_conflict_list:
          #conflict.setDomain('Publication')
321
          conflict.setSubscriber(subscriber)
Sebastien Robin's avatar
Sebastien Robin committed
322 323
          #conflict.setDomainId(subscriber.getId())
          conflict_list += [conflict.__of__(self)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
324 325 326
    for subscription in self.getSubscriptionList():
      sub_conflict_list = subscription.getConflictList()
      for conflict in sub_conflict_list:
327
        #conflict.setDomain('Subscription')
328
        conflict.setSubscriber(subscription)
Sebastien Robin's avatar
Sebastien Robin committed
329 330
        #conflict.setDomainId(subscription.getId())
        conflict_list += [conflict.__of__(self)]
331 332 333 334
    if path is not None: # Retrieve only conflicts for a given path
      new_list = []
      for conflict in conflict_list:
        if conflict.getObjectPath() == path:
Sebastien Robin's avatar
Sebastien Robin committed
335
          new_list += [conflict.__of__(self)]
336
      return new_list
Jean-Paul Smets's avatar
Jean-Paul Smets committed
337 338
    return conflict_list

339 340 341 342 343 344 345 346 347
  security.declareProtected(Permissions.AccessContentsInformation,'getDocumentConflictList')
  def getDocumentConflictList(self, context=None):
    """
    Retrieve the list of all conflicts for a given document
    Well, this is the same thing as getConflictList with a path
    """
    return self.getConflictList(context)


Sebastien Robin's avatar
Sebastien Robin committed
348
  security.declareProtected(Permissions.AccessContentsInformation,'getSynchronizationState')
349
  def getSynchronizationState(self, context):
350
    """
351
    context : the context on which we are looking for state
352

353 354 355
    This functions have to retrieve the synchronization state,
    it will first look in the conflict list, if nothing is found,
    then we have to check on a publication/subscription.
356

357
    This method returns a mapping between subscription and states
Sebastien Robin's avatar
Sebastien Robin committed
358 359 360 361 362

    JPS suggestion:
      path -> object, document, context, etc.
      type -> '/titi/toto' or ('','titi', 'toto') or <Base instance 1562567>
      object = self.resolveContext(context) (method to add)
363
    """
364
    path = self.resolveContext(context)
365 366 367 368 369 370
    conflict_list = self.getConflictList()
    state_list= []
    LOG('getSynchronizationState',0,'path: %s' % str(path))
    for conflict in conflict_list:
      if conflict.getObjectPath() == path:
        LOG('getSynchronizationState',0,'found a conflict: %s' % str(conflict))
371
        state_list += [[conflict.getSubscriber(),self.CONFLICT]]
372
    for domain in self.getSynchronizationList():
373 374 375 376 377 378 379 380 381 382 383 384
      destination = domain.getDestinationPath()
      LOG('getSynchronizationState',0,'destination: %s' % str(destination))
      j_path = '/'.join(path)
      LOG('getSynchronizationState',0,'j_path: %s' % str(j_path))
      if j_path.find(destination)==0:
        o_id = j_path[len(destination)+1:].split('/')[0]
        LOG('getSynchronizationState',0,'o_id: %s' % o_id)
        subscriber_list = []
        if domain.domain_type==self.PUB:
          subscriber_list = domain.getSubscriberList()
        else:
          subscriber_list = [domain]
385
        LOG('getSynchronizationState, subscriber_list:',0,subscriber_list)
386 387 388 389
        for subscriber in subscriber_list:
          signature = subscriber.getSignature(o_id)
          if signature is not None:
            state = signature.getStatus()
390 391
            LOG('getSynchronizationState:',0,'sub.dest :%s, state: %s' % \
                                   (subscriber.getSubscriptionUrl(),str(state)))
392 393 394 395 396 397 398 399
            found = None
            # Make sure there is not already a conflict giving the state
            for state_item in state_list:
              if state_item[0]==subscriber:
                found = 1
            if found is None:
              state_list += [[subscriber,state]]
    return state_list
400

401 402
  security.declareProtected(Permissions.ModifyPortalContent, 'applyPublisherValue')
  def applyPublisherValue(self, conflict):
Sebastien Robin's avatar
Sebastien Robin committed
403 404 405 406 407
    """
      after a conflict resolution, we have decided
      to keep the local version of an object
    """
    object = self.unrestrictedTraverse(conflict.getObjectPath())
408
    subscriber = conflict.getSubscriber()
Sebastien Robin's avatar
Sebastien Robin committed
409
    # get the signature:
Sebastien Robin's avatar
Sebastien Robin committed
410
    LOG('p_sync.applyPublisherValue, subscriber: ',0,subscriber)
Sebastien Robin's avatar
Sebastien Robin committed
411 412 413
    signature = subscriber.getSignature(object.getId()) # XXX may be change for rid
    signature.delConflict(conflict)
    if signature.getConflictList() == []:
Sebastien Robin's avatar
Sebastien Robin committed
414
      LOG('p_sync.applyPublisherValue, conflict_list empty on : ',0,signature)
Sebastien Robin's avatar
Sebastien Robin committed
415 416
      signature.setStatus(self.PUB_CONFLICT_MERGE)

417 418 419 420 421 422
  security.declareProtected(Permissions.ModifyPortalContent, 'applyPublisherDocument')
  def applyPublisherDocument(self, conflict):
    """
    apply the publisher value for all conflict of the given document
    """
    subscriber = conflict.getSubscriber()
Sebastien Robin's avatar
Sebastien Robin committed
423
    LOG('applyPublisherDocument, subscriber: ',0,subscriber)
424 425
    for c in self.getConflictList(conflict.getObjectPath()):
      if c.getSubscriber() == subscriber:
Sebastien Robin's avatar
Sebastien Robin committed
426
        LOG('applyPublisherDocument, applying on conflict: ',0,conflict)
427 428 429 430 431 432 433 434 435 436 437 438 439 440
        c.applyPublisherValue()

  security.declareProtected(Permissions.ModifyPortalContent, 'applySubscriberDocument')
  def applySubscriberDocument(self, conflict):
    """
    apply the subscriber value for all conflict of the given document
    """
    subscriber = conflict.getSubscriber()
    for c in self.getConflictList(conflict.getObjectPath()):
      if c.getSubscriber() == subscriber:
        c.applySubscriberValue()

  security.declareProtected(Permissions.ModifyPortalContent, 'applySubscriberValue')
  def applySubscriberValue(self, conflict):
Sebastien Robin's avatar
Sebastien Robin committed
441 442 443 444 445
    """
      after a conflict resolution, we have decided
      to keep the local version of an object
    """
    object = self.unrestrictedTraverse(conflict.getObjectPath())
446
    subscriber = conflict.getSubscriber()
Sebastien Robin's avatar
Sebastien Robin committed
447 448 449 450 451 452 453 454 455 456 457 458
    # get the signature:
    LOG('p_sync.setRemoteObject, subscriber: ',0,subscriber)
    signature = subscriber.getSignature(object.getId()) # XXX may be change for rid
    conduit = ERP5Conduit()
    for xupdate in conflict.getXupdateList():
      conduit.updateNode(xml=xupdate,object=object,force=1)
    signature.delConflict(conflict)
    if signature.getConflictList() == []:
      signature.setStatus(self.PUB_CONFLICT_MERGE)


  security.declareProtected(Permissions.ModifyPortalContent, 'manageLocalValue')
459
  def managePublisherValue(self, subscription_url, property_id, object_path, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
460 461 462
    """
    Do whatever needed in order to store the local value on
    the remote server
Sebastien Robin's avatar
Sebastien Robin committed
463 464 465 466 467

    Suggestion (API)
      add method to view document with applied xupdate
      of a given subscriber XX (ex. viewSubscriberDocument?path=ddd&subscriber_id=dddd)
      Version=Version CPS
Jean-Paul Smets's avatar
Jean-Paul Smets committed
468 469
    """
    # Retrieve the conflict object
Sebastien Robin's avatar
Sebastien Robin committed
470
    LOG('manageLocalValue',0,'%s %s %s' % (str(subscription_url),
471
                                           str(property_id),
Sebastien Robin's avatar
Sebastien Robin committed
472 473 474
                                           str(object_path)))
    for conflict in self.getConflictList():
      LOG('manageLocalValue, conflict:',0,conflict)
475 476
      if conflict.getPropertyId() == property_id:
        LOG('manageLocalValue',0,'found the property_id')
Sebastien Robin's avatar
Sebastien Robin committed
477
        if '/'.join(conflict.getObjectPath())==object_path:
478
          if conflict.getSubscriber().getSubscriptionUrl()==subscription_url:
479
            conflict.applyPublisherValue()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
480 481 482
    if RESPONSE is not None:
      RESPONSE.redirect('manageConflicts')

Sebastien Robin's avatar
Sebastien Robin committed
483
  security.declareProtected(Permissions.ModifyPortalContent, 'manageRemoteValue')
484
  def manageSubscriberValue(self, subscription_url, property_id, object_path, RESPONSE=None):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
485 486 487 488
    """
    Do whatever needed in order to store the remote value locally
    and confirmed that the remote box should keep it's value
    """
Sebastien Robin's avatar
Sebastien Robin committed
489
    LOG('manageLocalValue',0,'%s %s %s' % (str(subscription_url),
490
                                           str(property_id),
Sebastien Robin's avatar
Sebastien Robin committed
491 492 493
                                           str(object_path)))
    for conflict in self.getConflictList():
      LOG('manageLocalValue, conflict:',0,conflict)
494 495
      if conflict.getPropertyId() == property_id:
        LOG('manageLocalValue',0,'found the property_id')
Sebastien Robin's avatar
Sebastien Robin committed
496
        if '/'.join(conflict.getObjectPath())==object_path:
497
          if conflict.getSubscriber().getSubscriptionUrl()==subscription_url:
498
            conflict.applySubscriberValue()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
499 500 501
    if RESPONSE is not None:
      RESPONSE.redirect('manageConflicts')

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  def resolveContext(self, context):
    """
    We try to return a path (like ('','erp5','foo') from the context.
    Context can be :
      - a path
      - an object
      - a string representing a path
    """
    if context is None:
      return context
    elif type(context) is type(()):
      return context
    elif type(context) is type('a'):
      return tuple(context.split('/'))
    else:
      return context.getPhysicalPath()

519
  security.declarePublic('sendResponse')
520
  def sendResponse(self, to_url=None, from_url=None, sync_id=None,xml=None, domain=None):
521 522 523 524
    """
    We will look at the url and we will see if we need to send mail, http
    response, or just copy to a file.
    """
525 526 527 528
    LOG('sendResponse, to_url: ',0,to_url)
    LOG('sendResponse, from_url: ',0,from_url)
    LOG('sendResponse, sync_id: ',0,sync_id)
    LOG('sendResponse, xml: ',0,xml)
529 530 531 532 533 534 535 536 537 538 539 540 541 542
    if domain is not None:
      gpg_key = domain.getGPGKey()
      if gpg_key not in ('',None):
        filename = str(random.randrange(1,2147483600)) + '.txt'
        decrypted = file('/tmp/%s' % filename,'w')
        decrypted.write(xml)
        decrypted.close()
        (status,output)=commands.getstatusoutput('gpg --yes --homedir /var/lib/zope/Products/ERP5SyncML/gnupg_keys -r "%s" -se /tmp/%s' % (gpg_key,filename))
        LOG('readResponse, gpg output:',0,output)
        encrypted = file('/tmp/%s.gpg' % filename,'r')
        xml = encrypted.read()
        encrypted.close()
        commands.getstatusoutput('rm -f /tmp/%s' % filename)
        commands.getstatusoutput('rm -f /tmp/%s.gpg' % filename)
543 544
    if type(to_url) is type('a'):
      if to_url.find('http://')==0:
545
        # we will send an http response
546 547
        self.activate(activity='RAMQueue').sendHttpResponse(sync_id=sync_id,
                                         to_url=to_url,
548
                                         xml=xml, domain=domain)
549 550 551 552 553 554 555
        return None
      elif to_url.find('file://')==0:
        filename = to_url[len('file:/'):]
        stream = file(filename,'w')
        LOG('sendResponse, filename: ',0,filename)
        stream.write(xml)
        stream.close()
556
        # we have to use local files (unit testing for example
557
      elif to_url.find('mailto:')==0:
558
        # we will send an email
559 560 561 562 563
        to_address = to_url[len('mailto:'):]
        from_address = from_url[len('mailto:'):]
        self.sendMail(from_address,to_address,sync_id,xml)

  security.declarePrivate('sendHttpResponse')
564 565 566 567 568
  def sendHttpResponse(self, to_url=None, sync_id=None, xml=None, domain=None ):
    LOG('sendHttpResponse, starting with domain:',0,domain)
    if domain is not None:
      if domain.domain_type == self.PUB:
        return xml
569 570 571 572
    to_encode = (('text',xml),('sync_id',sync_id))
    encoded = urllib.urlencode(to_encode)
    to_url = to_url + '/portal_synchronizations/readResponse'
    result = urllib.urlopen(to_url, encoded).read()
573 574 575 576 577 578 579 580 581
    LOG('sendHttpResponse, before result, domain:',0,domain)
    LOG('sendHttpResponse, result:',0,result)
    if domain is not None:
      if domain.domain_type == self.SUB:
        if result not in (None,''):
          uf = self.acl_users
          user = UnrestrictedUser('syncml','syncml',['Manager','Member'],'')
          newSecurityManager(None, user)
          self.activate(activity='RAMQueue').SubSync(sync_id,result)
582 583 584 585 586 587 588 589 590

  security.declarePublic('readResponse')
  def readResponse(self, text=None, sync_id=None, to_url=None, from_url=None):
    """
    We will look at the url and we will see if we need to send mail, http
    response, or just copy to a file.
    """
    LOG('readResponse, ',0,'starting')
    LOG('readResponse, sync_id: ',0,sync_id)
591 592 593 594 595
    # Login as a manager to make sure we can create objects
    uf = self.acl_users
    user = UnrestrictedUser('syncml','syncml',['Manager','Member'],'')
    newSecurityManager(None, user)

596
    if text is not None:
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
      # XXX We will look everywhere for a publication/subsription with
      # the id sync_id, this is not so good, but there is no way yet
      # to know if we will call a publication or subscription XXX
      gpg_key = ''
      for publication in self.getPublicationList():
        if publication.getId()==sync_id:
          gpg_key = publication.getGPGKey()
      if gpg_key == '':
        for subscription in self.getSubscriptionList():
          if subscription.getId()==sync_id:
            gpg_key = subscription.getGPGKey()
      # decrypt the message if needed
      if gpg_key not in (None,''):
        filename = str(random.randrange(1,2147483600)) + '.txt'
        encrypted = file('/tmp/%s.gpg' % filename,'w')
        encrypted.write(text)
        encrypted.close()
        (status,output)=commands.getstatusoutput('gpg --homedir /var/lib/zope/Products/ERP5SyncML/gnupg_keys -r "%s"  --decrypt /tmp/%s.gpg > /tmp/%s' % (gpg_key,filename,filename))
        LOG('readResponse, gpg output:',0,output)
        decrypted = file('/tmp/%s' % filename,'r')
        text = decrypted.read()
        decrypted.close()
        commands.getstatusoutput('rm -f /tmp/%s' % filename)
        commands.getstatusoutput('rm -f /tmp/%s.gpg' % filename)
621 622 623 624 625 626 627 628 629 630 631 632 633
      # Get the target and then find the corresponding publication or
      # Subscription
      xml = FromXml(text)
      url = ''
      for subnode in self.getElementNodeList(xml):
        if subnode.nodeName == 'SyncML':
          for subnode1 in self.getElementNodeList(subnode):
            if subnode1.nodeName == 'SyncHdr':
              for subnode2 in self.getElementNodeList(subnode1):
                if subnode2.nodeName == 'Target':
                  url = subnode2.childNodes[0].data 
      for publication in self.getPublicationList():
        if publication.getPublicationUrl()==url:
634 635
          result = self.PubSync(sync_id,xml)
          return result['xml']
636 637
      for subscription in self.getSubscriptionList():
        if subscription.getSubscriptionUrl()==url:
638 639 640
          result = self.SubSync(sync_id,xml)
          if result is not None:
            self.SubSync(sync_id,result)
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

    # we use from only if we have a file 
    elif type(from_url) is type('a'):
      if from_url.find('file://')==0:
        try:
          filename = from_url[len('file:/'):]
          stream = file(filename,'r')
          xml = stream.read()
          #stream.seek(0)
          #LOG('readResponse',0,'Starting... msg: %s' % str(stream.read()))
        except IOError:
          LOG('readResponse, cannot read file: ',0,filename)
          xml = None
        if xml is not None and len(xml)==0:
          xml = None
        return xml
657

Jean-Paul Smets's avatar
Jean-Paul Smets committed
658
InitializeClass( SynchronizationTool )