]> git.mxchange.org Git - friendica.git/blob - include/delivery.php
saved searches on search page, templates: Invalid argument supplied for foreach(...
[friendica.git] / include / delivery.php
1 <?php
2 require_once("boot.php");
3
4 function delivery_run($argv, $argc){
5         global $a, $db;
6
7         if(is_null($a)){
8                 $a = new App;
9         }
10   
11         if(is_null($db)) {
12                 @include(".htconfig.php");
13                 require_once("dba.php");
14                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
15                         unset($db_host, $db_user, $db_pass, $db_data);
16         }
17
18         require_once("session.php");
19         require_once("datetime.php");
20         require_once('include/items.php');
21         require_once('include/bbcode.php');
22         require_once('include/diaspora.php');
23
24         load_config('config');
25         load_config('system');
26
27         load_hooks();
28
29         if($argc < 3)
30                 return;
31
32         $a->set_baseurl(get_config('system','url'));
33
34         logger('delivery: invoked: ' . print_r($argv,true));
35
36         $cmd        = $argv[1];
37         $item_id    = intval($argv[2]);
38         $contact_id = intval($argv[3]);
39
40         // Some other process may have delivered this item already.
41
42         $r = q("select * from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
43                 dbesc($cmd),
44                 dbesc($item_id),
45                 dbesc($contact_id)
46         );
47         if(! count($r)) {
48                 return;
49         }       
50
51         // It's ours to deliver. Remove it from the queue.
52
53         q("delete from deliverq where cmd = '%s' and item = %d and contact = %d limit 1",
54                 dbesc($cmd),
55                 dbesc($item_id),
56                 dbesc($contact_id)
57         );
58
59         if((! $item_id) || (! $contact_id))
60                 return;
61
62         $expire = false;
63         $top_level = false;
64         $recipients = array();
65         $url_recipients = array();
66
67         $normal_mode = true;
68
69         $recipients[] = $contact_id;
70
71         if($cmd === 'expire') {
72                 $normal_mode = false;
73                 $expire = true;
74                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
75                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP - INTERVAL 30 MINUTE",
76                         intval($item_id)
77                 );
78                 $uid = $item_id;
79                 $item_id = 0;
80                 if(! count($items))
81                         return;
82         }
83         else {
84
85                 // find ancestors
86                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
87                         intval($item_id)
88                 );
89
90                 if((! count($r)) || (! intval($r[0]['parent']))) {
91                         return;
92                 }
93
94                 $target_item = $r[0];
95                 $parent_id = intval($r[0]['parent']);
96                 $uid = $r[0]['uid'];
97                 $updated = $r[0]['edited'];
98
99
100
101                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer` 
102                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC",
103                         intval($parent_id)
104                 );
105
106                 if(! count($items)) {
107                         return;
108                 }
109
110                 $icontacts = q("SELECT * FROM `contact` WHERE `id` IN ( SELECT distinct(`contact-id`) FROM `item` where `parent` = %d ) ",
111                         intval($parent_id)
112                 );
113                 if(! count($icontacts))
114                         return;
115
116
117                 // avoid race condition with deleting entries
118
119                 if($items[0]['deleted']) {
120                         foreach($items as $item)
121                                 $item['deleted'] = 1;
122                 }
123
124                 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
125                         logger('delivery: top level post');
126                         $top_level = true;
127                 }
128         }
129
130         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`, 
131                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, 
132                 `user`.`page-flags`, `user`.`prvnets`
133                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
134                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
135                 intval($uid)
136         );
137
138         if(! count($r))
139                 return;
140
141         $owner = $r[0];
142
143         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
144
145         $public_message = true;
146
147         // fill this in with a single salmon slap if applicable
148         $slap = '';
149
150         require_once('include/group.php');
151
152         $parent = $items[0];
153
154                 // This is IMPORTANT!!!!
155
156                 // We will only send a "notify owner to relay" or followup message if the referenced post
157                 // originated on our system by virtue of having our hostname somewhere
158                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
159                 // if $parent['wall'] == 1 we will already have the parent message in our array
160                 // and we will relay the whole lot.
161  
162                 // expire sends an entire group of expire messages and cannot be forwarded.
163                 // However the conversation owner will be a part of the conversation and will 
164                 // be notified during this run.
165                 // Other DFRN conversation members will be alerted during polled updates.
166
167                 // Diaspora members currently are not notified of expirations, and other networks have
168                 // either limited or no ability to process deletions. We should at least fix Diaspora 
169                 // by stringing togther an array of retractions and sending them onward.
170                  
171         
172         $localhost = $a->get_hostname();
173         if(strpos($localhost,':'))
174                 $localhost = substr($localhost,0,strpos($localhost,':'));
175
176                 /**
177                  *
178                  * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes 
179                  * have been known to cause runaway conditions which affected several servers, along with 
180                  * permissions issues. 
181                  *
182                  */
183  
184         if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
185                 logger('relay denied for delivery agent.');
186
187                 /* no relay allowed for direct contact delivery */
188                 return;
189         }
190
191         if((strlen($parent['allow_cid'])) 
192                 || (strlen($parent['allow_gid'])) 
193                 || (strlen($parent['deny_cid'])) 
194                 || (strlen($parent['deny_gid']))) {
195                 $public_message = false; // private recipients, not public
196         }
197
198         $conversant_str = intval($contact_id);
199
200         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `blocked` = 0 AND `pending` = 0",
201                 intval($contact_id)
202         );
203
204         if(count($r))
205                 $contact = $r[0];
206         
207
208         $feed_template = get_markup_template('atom_feed.tpl');
209         $mail_template = get_markup_template('atom_mail.tpl');
210
211         $atom = '';
212         $slaps = array();
213
214         $hubxml = feed_hublinks();
215
216         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
217
218         if(strlen($birthday))
219                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
220
221         $atom .= replace_macros($feed_template, array(
222                         '$version'      => xmlify(FRIENDIKA_VERSION),
223                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
224                         '$feed_title'   => xmlify($owner['name']),
225                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
226                         '$hub'          => $hubxml,
227                         '$salmon'       => '',  // private feed, we don't use salmon here
228                         '$name'         => xmlify($owner['name']),
229                         '$profile_page' => xmlify($owner['url']),
230                         '$photo'        => xmlify($owner['photo']),
231                         '$thumb'        => xmlify($owner['thumb']),
232                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
233                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
234                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
235                         '$birthday'     => $birthday
236         ));
237
238         foreach($items as $item) {
239                 if(! $item['parent'])
240                         continue;
241
242                 // private emails may be in included in public conversations. Filter them.
243                 if(($public_message) && $item['private'])
244                         continue;
245
246                 $item_contact = get_item_contact($item,$icontacts);
247                 if(! $item_contact)
248                         continue;
249
250                 $atom .= atom_entry($item,'text',$item_contact,$owner,true);
251
252                 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
253                         $slaps[] = atom_entry($item,'html',$item_contact,$owner,true);
254         }
255
256         $atom .= '</feed>' . "\r\n";
257
258         logger('notifier: ' . $atom, LOGGER_DATA);
259
260         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
261
262
263         require_once('include/salmon.php');
264
265         if($contact['self'])
266                 return;
267
268         $deliver_status = 0;
269
270         switch($contact['network']) {
271
272                 case NETWORK_DFRN :
273                         logger('notifier: dfrndelivery: ' . $contact['name']);
274                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
275
276                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
277         
278                         if($deliver_status == (-1)) {
279                                 logger('notifier: delivery failed: queuing message');
280                                 // queue message for redelivery
281                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
282                                         VALUES ( %d, '%s', '%s', '%s') ",
283                                         intval($contact['id']),
284                                         dbesc(datetime_convert()),
285                                         dbesc(datetime_convert()),
286                                         dbesc($atom)
287                                 );
288                         }
289                         break;
290
291                 case NETWORK_OSTATUS :
292
293                         // Do not send to otatus if we are not configured to send to public networks
294                         if($owner['prvnets'])
295                                 break;
296                         if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
297                                 break;
298
299                         // only send salmon if public - e.g. if it's ok to notify
300                         // a public hub, it's ok to send a salmon
301
302                         if((count($slaps)) && ($public_message) && (! $expire)) {
303                                 logger('notifier: slapdelivery: ' . $contact['name']);
304                                 foreach($slaps as $slappy) {
305                                         if($contact['notify']) {
306                                                 $deliver_status = slapper($owner,$contact['notify'],$slappy);
307                                                 if($deliver_status == (-1)) {
308                                                         // queue message for redelivery
309                                                         q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
310                                                                 VALUES ( %d, '%s', '%s', '%s') ",
311                                                                 intval($contact['id']),
312                                                                 dbesc(datetime_convert()),
313                                                                 dbesc(datetime_convert()),
314                                                                 dbesc($slappy)
315                                                         );                                                              
316                                                 }
317                                         }
318                                 }
319                         }
320
321                         break;
322
323                 case NETWORK_MAIL :
324                                                 
325                         if(get_config('system','dfrn_only'))
326                                 break;
327                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
328
329                         $addr = $contact['addr'];
330                         if(! strlen($addr))
331                                 break;
332
333                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
334
335                                 $it = null;
336                                 if($cmd === 'wall-new') 
337                                         $it = $items[0];
338                                 else {
339                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
340                                                 intval($argv[2]),
341                                                 intval($uid)
342                                         );
343                                         if(count($r))
344                                                 $it = $r[0];
345                                 }
346                                 if(! $it)
347                                         break;
348                                         
349
350                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
351                                         intval($uid)
352                                 );
353                                 if(! count($local_user))
354                                         break;
355                                         
356                                 $reply_to = '';
357                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
358                                         intval($uid)
359                                 );
360                                 if($r1 && $r1[0]['reply_to'])
361                                         $reply_to = $r1[0]['reply_to'];
362
363                                 $subject  = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
364                                 $headers  = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
365                                 if($reply_to)
366                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
367                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
368                                 if($it['uri'] !== $it['parent-uri']) {
369                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
370                                         if(! strlen($it['title'])) {
371                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
372                                                         dbesc($it['parent-uri'])
373                                                 );
374                                                 if(count($r)) {
375                                                         $subtitle = $r[0]['title'];
376                                                         if($subtitle) {
377                                                                 if(strncasecmp($subtitle,'RE:',3))
378                                                                         $subject = $subtitle;
379                                                                 else
380                                                                         $subject = 'Re: ' . $subtitle;
381                                                         }
382                                                 }
383                                         }
384                                 }
385                                 $headers .= 'MIME-Version: 1.0' . "\n";
386                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
387                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
388                                 $html    = prepare_body($it);
389                                 $message = '<html><body>' . $html . '</body></html>';
390                                 logger('notifier: email delivery to ' . $addr);
391                                 mail($addr, $subject, $message, $headers);
392                         }
393                         break;
394
395                 case NETWORK_DIASPORA :
396                         logger('delivery: diaspora deliver: ' . $contact['name']);
397
398                         if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
399                                 break;
400
401                         if(! $contact['pubkey'])
402                                 break;
403                                         
404                         if($target_item['verb'] === ACTIVITY_DISLIKE) {
405                                 // unsupported
406                                 break;
407                         }
408                         elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
409                         logger('delivery: diaspora retract: ' . $contact['name']);
410                                 // diaspora delete, 
411                                 diaspora_send_retraction($target_item,$owner,$contact);
412                                 break;
413                         }
414                         elseif($target_item['parent'] != $target_item['id']) {
415
416                         logger('delivery: diaspora relay: ' . $contact['name']);
417
418                                 // we are the relay - send comments, likes and unlikes to our conversants
419                                 diaspora_send_relay($target_item,$owner,$contact);
420                                 break;
421                         }               
422                         elseif(($top_level) && (! $walltowall)) {
423                                 // currently no workable solution for sending walltowall
424                                 logger('delivery: diaspora status: ' . $contact['name']);
425                                 diaspora_send_status($target_item,$owner,$contact);
426                                 break;
427                         }
428
429                         logger('delivery: diaspora unknown mode: ' . $contact['name']);
430
431                         break;
432
433                 case NETWORK_FEED :
434                 case NETWORK_FACEBOOK :
435                         if(get_config('system','dfrn_only'))
436                                 break;
437                 default:
438                         break;
439         }
440
441         return;
442 }
443
444 if (array_search(__file__,get_included_files())===0){
445   delivery_run($argv,$argc);
446   killme();
447 }