DataObjects/core.sql
[Pman.Core] / DataObjects / Core_mailing_list_message.php
index 95a8177..026a1cc 100644 (file)
@@ -26,11 +26,13 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
     
     function applyFilters($q, $au, $roo)
     {
+        $tn = $this->tableName();
+        
         if(!empty($q['search']['nameortitle'])){
             $this->whereAdd("
-                name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
+                $tn.name LIKE '%{$this->escape($q['search']['nameortitle'])}%'
                 OR
-                subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
+                $tn.subject LIKE '%{$this->escape($q['search']['nameortitle'])}%'
             ");
         }
     }
@@ -45,25 +47,14 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
             $i->beforeDelete();
             $i->delete();
         }
-        
-        $mlq = DB_DataObject::factory('crm_mailing_list_queue');
-        $mlq->message_id = $this->id;
-        $mlq->find();
-        while ($mlq->fetch()){
-            $mlq->beforeDelete();
-            $mlq->delete();
-        }
-        
-        
     }
+    
     function beforeUpdate($old, $request,$roo)
     {   
         if (!empty($request['_make_copy'])) {
             $this->makeCopy($roo);
             
         }
-         
-       
     }
     
     function makeCopy($roo)
@@ -95,7 +86,6 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
         }
         
         
-        
         libxml_use_internal_errors (true);
         $doc = new DOMDocument('1.0', 'UTF-8');
         $doc->loadHTML('<?xml encoding="UTF-8"><HTML><BODY>'.$this->bodytext.'</BODY></HTML>');
@@ -119,7 +109,8 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
                 }
                 $nid = $map[$oid];
                 $nstr = "/Images/$nid/{$matches[2]}/#image-{$nid}";
-                $img->setAttribute('src',  str_replace($href, $matches[0], $nstr ));
+                
+                $img->setAttribute('src',  str_replace($matches[0], $nstr, $href ));
                     
                  
             }
@@ -131,31 +122,24 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
         
         
         $roo->jok("duplicated");
-        
-        
-        
-        
     }
     
-    
     function onInsert($request,$roo)
     {   
         $i = DB_DataObject::factory('Images');
-        $i->whereAdd('onid = 0');
+        $i->onid = 0;
+        $i->ontable = $this->tableName();
         $i->find();
         while ($i->fetch()){
+            $ii = clone ($i);
             $i->onid = $this->id;
-            $i->update();
+            $i->update($ii);
         }
        
     }
     
-    
     function attachmentIds()
     {
-        
-         $roo = HTML_FlexyFramework::get()->page;
-        
         libxml_use_internal_errors (true);
         $doc = new DOMDocument('1.0', 'UTF-8');
         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
@@ -175,7 +159,7 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
             }
             $ret[] = $cid[1];
         }
-       // print_r($ret);
+        
         return $ret;
     }
     /**
@@ -184,11 +168,7 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
      */
     
     function processRelacements($replace_links = true)
-    {
-        $roo = HTML_FlexyFramework::get()->page;
-        
-        $cfg = HTML_FlexyFramework::get()->Pman_Crm;
-        
+    {   
         libxml_use_internal_errors (true);
         $doc = new DOMDocument('1.0', 'UTF-8');
         $doc->loadHTML('<?xml encoding="UTF-8">'.$this->bodytext);
@@ -202,115 +182,173 @@ class Pman_Core_DataObjects_Core_mailing_list_message extends DB_DataObject
                 $img->setAttribute('src', 'cid:' . $cid[1]);
             }
         }
-        $unsubscribe = $cfg ['server_baseurl'] . '/Crm/Unsubscribe/' . $this->id . '/{person.id}';
-        
-       
-        foreach ($xpath->query('//a[@href]') as $a) { 
-            
-            $href = $a->getAttribute('href');
-            
-            if(preg_match('/#unsubscribe/', $href)){
-                $a->setAttribute('href', $unsubscribe);
-                continue;
-            }
-            
-            if(!preg_match('/^http(.*)/', $href)){
-                continue;
-            }
-            if (!$replace_links) {
-                continue;
-            }
-            $link = DB_DataObject::factory('crm_mailing_list_link');
-            $link->setFrom(array(
-                'url' => $href
-            ));
-            
-            if(!$link->find(true)){
-                $link->insert();
-            }
-            
-            if(!$link->id){
-                continue;
-            }
-            
-            $l = $cfg ['server_baseurl'] . '/Crm/Link/' .$this->id . '/' . $link->id . '/{person.id}.html';
-            
-            $a->setAttribute('href', $l);
-            
-        }
-        
-        $element = $doc->createElement('img');
-        
-        $element->setAttribute('src', $cfg ['server_baseurl']  . '/Crm/Open/' . $this->id . '/{person.id}.html');
-        $element->setAttribute('width', '1');
-        $element->setAttribute('height', '1');
-        
-        $html = $doc->getElementsByTagName('html');
-        $html->item(0)->appendChild($element);
         
         $this->bodytext = $doc->saveHTML();
         
         libxml_use_internal_errors (false);
         
-        /*
-        $this->bodytext = str_replace("{person.firstname}", htmlspecialchars($person->firstname), $this->bodytext);
-        $this->bodytext = str_replace("{person.lastname}", htmlspecialchars($person->lastname), $this->bodytext);
-        $this->bodytext = str_replace("{person.name}", htmlspecialchars($person->name), $this->bodytext);
-         
-        
-        $this->plaintext = str_replace("{person.firstname}", $person->firstname, $this->plaintext);
-        $this->plaintext = str_replace("{person.lastname}", $person->lastname, $this->plaintext);
-        $this->plaintext = str_replace("{person.name}", $person->name, $this->plaintext);
-        */
-        $this->plaintext = str_replace("{unsubscribe_link}", $unsubscribe, $this->plaintext);
         $this->bodytext = str_replace('%7B', '{', $this->bodytext ); // kludge as template is not interpretated as html.
         $this->bodytext = str_replace('%7D', '}', $this->bodytext ); // kludge as template is not interpretated as html.
-         
-        
         
         return;
     }
+    
     function send($obj)
-    {
-        
-         
+    {    
         $contents = (array)$obj;
         
-        $q = DB_DataObject::factory('crm_mailing_list_queue');
-        $q->id = 'test-message-'. $this->id;
-        $q->message_id = $this->id;
-        $q->message_id_subject = $this->subject;
-        $q->message_id_from_email = $this->from_email;
-        $q->message_id_from_name = $this->from_name;
-        
-        $q->cachedMailWithOutImages(true, false);
+        $this->cachedMailWithOutImages(true, false);
         
         $contents['subject'] = $this->subject;
         
         require_once 'Pman/Core/Mailer.php';
         
-        $templateDir = session_save_path() . '/email-cache-' . get_current_user() ;
+        $templateDir = session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') ;
         $r = new Pman_Core_Mailer(array(
-            'template'=> $q->id,
+            'template'=> $this->tableName() . '-' . $this->id,
             'templateDir' => $templateDir,
-            'page' => $q,
+            'page' => $this,
             'contents' => $contents
-            //array(
-            //    'person' => $person,
-            //    'subject' => $this->message_id_subject,
-           // )
         ));
         
-        
-         
-        ///print_r($r->toData());
         $ret = $r->toData();
-        $images = file_get_contents(session_save_path() . '/email-cache-' . get_current_user() . '/mail/' . $q->id . '-images.txt');
-       // var_dump($images);exit;
+        
+        $images = file_get_contents(session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt');
         
         $ret['body'] = str_replace('%Images%', $images, $ret['body']);
         
         return $r->send($ret);
     }
     
+    function cachedMailWithOutImages($force = false, $replace_links = true)
+    {  
+        $random_hash = md5(date('r', time()));
+        
+        $this->cachedImages($random_hash);
+        
+        $cachePath = session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') . '/mail/' . $this->tableName() . '-' . $this->id . '.txt';
+          
+        if (!$force && $this->isGenerated($cachePath)) {
+            return;
+        }
+        
+        if (!file_exists(dirname($cachePath))) {
+            mkdir(dirname($cachePath), 0700, true);
+        }
+        
+        $this->processRelacements($replace_links);
+        
+        $fh = fopen($cachePath, 'w');
+
+        fwrite($fh, implode("\n", array(
+            "From: {t.messageFrom():h} ",
+            "To: {t.person.getEmailFrom():h} ",
+            "Subject: {t.subject} ",
+            "X-Message-ID: {t.id} "
+        ))."\n");
+        
+        
+// note the extra space to finish the last line..
+        fwrite($fh, " " . "
+Content-Type: multipart/alternative; boundary=alt-{$random_hash}
+
+--alt-{$random_hash}
+Content-Type: text/plain; charset=utf-8; format=flowed
+Content-Transfer-Encoding: 7bit
+
+{$this->plaintext}
+    
+--alt-{$random_hash}
+Content-Type: multipart/related; boundary=rel-{$random_hash}
+
+--rel-{$random_hash}
+Content-Type: text/html; charset=utf-8
+Content-Transfer-Encoding: 7bit
+
+{$this->bodytext}
+
+");  
+
+        fwrite($fh,"%Images%
+--rel-{$random_hash}--
+
+--alt-{$random_hash}--
+");
+        fclose($fh);
+        
+    }
+    
+    function cachedImages($random_hash)
+    {
+        $imageCache = session_save_path() . '/email-cache-' . getenv('APACHE_RUN_USER') . '/mail/' . $this->tableName() . '-' . $this->id . '-images.txt';
+        
+        $ids = $this->attachmentIds();
+        
+        //$this->jerr(print_r($ids,true));
+        
+         
+        $fh = fopen($imageCache, 'w');
+        
+        $i = DB_DataObject::factory('Images');
+        $i->onid = $this->id;
+        $i->ontable = $this->tableName();
+        $i->whereAddIn('id', $ids, 'int');
+        $i->find();
+        while ($i->fetch()){
+            if (!file_exists($i->getStoreName()) || !filesize($i->getStoreName())) {
+                continue;
+            }
+            $out = chunk_split(base64_encode(file_get_contents($i->getStoreName())));
+            if (empty($out)) {
+                continue;
+            }
+            $imgfn = urlencode(preg_replace('/#.*$/i', '' , $i->filename));
+            fwrite($fh, "--rel-{$random_hash}
+Content-Type: {$i->mimetype}; name={$imgfn}
+Content-Transfer-Encoding: base64
+Content-ID: <attachment-{$i->id}>
+Content-Disposition: inline; filename={$imgfn}
+
+" . $out  . "");
+
+            }
+        
+    }
+    
+    function isGenerated($cachePath)
+    {
+        if (!file_exists($cachePath) || !filesize($cachePath)) {
+            return false;
+        }
+        
+        
+        $ctime = filemtime($cachePath);
+        $mtime = array();
+        $mtime[] = $this->updated_dt;
+        $i = DB_DataObject::factory('Images');
+        $i->onid = $this->id;
+        $i->ontable = $this->tableName();
+        $i->selectAdd();
+        $i->selectAdd('max(created) as created');
+        $i->find(true);
+        $mtime[] = $i->created;
+        if($ctime >= strtotime(max($mtime))){
+            return true;
+        }
+        
+        return false;
+    }
+    
+    function messageFrom()
+    {
+        return '"' . addslashes($this->from_name) . '" <' . $this->from_email. '>'  ;
+    }
+    
+    function formatDate($dt, $format = 'd/M/Y')
+    {
+        return date($format, strtotime($dt));
+    } 
+    
+    
+    
 }