From 5360f08f4295f2306d815a7659fbdff94fda01a3 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Sun, 11 Feb 2018 19:00:01 -0500 Subject: [PATCH] Revert to stable version 3.5.4 --- appnet/AppDotNet.php | 1647 +++++++++++++ appnet/DigiCertHighAssuranceEVRootCA.pem | 23 + appnet/README.md | 15 + appnet/appnet.css | 29 + appnet/appnet.php | 1358 +++++++++++ appnet/lang/C/messages.po | 116 + appnet/lang/cs/messages.po | 118 + appnet/lang/cs/strings.php | 29 + appnet/lang/de/messages.po | 118 + appnet/lang/de/strings.php | 29 + appnet/lang/es/messages.po | 118 + appnet/lang/es/strings.php | 29 + appnet/lang/fr/messages.po | 119 + appnet/lang/fr/strings.php | 29 + appnet/lang/it/messages.po | 118 + appnet/lang/it/strings.php | 29 + appnet/lang/nl/messages.po | 118 + appnet/lang/nl/strings.php | 29 + appnet/lang/pt-br/messages.po | 119 + appnet/lang/pt-br/strings.php | 29 + appnet/lang/ro/messages.po | 117 + appnet/lang/ro/strings.php | 29 + appnet/lang/ru/messages.po | 118 + appnet/lang/ru/strings.php | 29 + appnet/templates/admin.tpl | 3 + blackout/blackout.php | 35 +- blockem/blockem.php | 22 +- blogger/blogger.php | 222 +- buffer/buffer.php | 82 +- buffer/bufferapp.php | 24 +- cal/LICENSE | 19 + cal/README.md | 29 + cal/cal.php | 200 ++ cal/lang/C/messages.po | 54 + cal/lang/C/strings.php | 12 + cal/lang/cs/messages.po | 56 + cal/lang/cs/strings.php | 16 + cal/lang/de/messages.po | 56 + cal/lang/de/strings.php | 16 + cal/lang/es/messages.po | 55 + cal/lang/es/strings.php | 16 + cal/lang/fr/messages.po | 56 + cal/lang/fr/strings.php | 16 + cal/lang/it/messages.po | 56 + cal/lang/it/strings.php | 16 + cal/lang/pt-br/messages.po | 57 + cal/lang/pt-br/strings.php | 16 + cal/lang/ro/messages.po | 56 + cal/lang/ro/strings.php | 16 + cal/lang/ru/messages.po | 56 + cal/lang/ru/strings.php | 16 + cal/lang/zh-cn/messages.po | 56 + cal/lang/zh-cn/strings.php | 16 + communityhome/communityhome.php | 121 +- communityhome/templates/directory_item.tpl | 4 +- communityhome/templates/settings.tpl | 9 - convert/convert.php | 92 +- convpath/README | 7 + convpath/convpath.php | 102 + convpath/lang/C/messages.po | 0 curweather/curweather.php | 84 +- curweather/templates/widget.tpl | 2 +- dav/README.md | 14 +- dav/common/wdcal_configuration.php | 4 +- dav/dav.php | 3 +- dav/friendica/calendar.friendica.fnk.php | 22 +- dav/friendica/database-init.inc.php | 16 +- ...v_caldav_backend_virtual_friendica.inc.php | 16 +- ..._carddav_backend_virtual_friendica.inc.php | 12 +- dav/friendica/dav_friendica_auth.inc.php | 54 +- dav/friendica/dav_friendica_principal.inc.php | 18 +- dav/friendica/layout.fnk.php | 24 +- dav/friendica/main.php | 26 +- defaultfeatures/README | 7 + defaultfeatures/defaultfeatures.php | 60 + defaultfeatures/lang/C/messages.po | 34 + defaultfeatures/templates/admin.tpl | 14 + diaspora/Diaspora_Connection.php | 44 +- diaspora/diaspora.php | 65 +- dwpost/dwpost.php | 36 +- editplain/editplain.css | 14 + editplain/editplain.php | 86 + editplain/lang/C/messages.po | 34 + editplain/lang/ca/strings.php | 6 + editplain/lang/cs/messages.po | 36 + editplain/lang/cs/strings.php | 11 + editplain/lang/de/messages.po | 37 + editplain/lang/de/strings.php | 11 + editplain/lang/eo/strings.php | 6 + editplain/lang/es/messages.po | 36 + editplain/lang/es/strings.php | 11 + editplain/lang/fr/messages.po | 36 + editplain/lang/fr/strings.php | 11 + editplain/lang/is/strings.php | 6 + editplain/lang/it/messages.po | 36 + editplain/lang/it/strings.php | 11 + editplain/lang/nb-no/strings.php | 6 + editplain/lang/pl/strings.php | 6 + editplain/lang/pt-br/strings.php | 6 + editplain/lang/ro/messages.po | 36 + editplain/lang/ro/strings.php | 11 + editplain/lang/ru/messages.po | 36 + editplain/lang/ru/strings.php | 11 + editplain/lang/sv/strings.php | 3 + editplain/lang/zh-cn/strings.php | 6 + extcron/extcron.php | 29 + extcron/lang/C/messages.po | 0 facebook/README.md | 19 + facebook/facebook.css | 13 + facebook/facebook.php | 2140 +++++++++++++++++ facebook/lang/C/messages.po | 253 ++ facebook/lang/ca/strings.php | 49 + facebook/lang/cs/strings.php | 49 + facebook/lang/de/strings.php | 49 + facebook/lang/eo/strings.php | 49 + facebook/lang/es/strings.php | 49 + facebook/lang/fr/strings.php | 49 + facebook/lang/is/strings.php | 49 + facebook/lang/it/strings.php | 49 + facebook/lang/nb-no/strings.php | 49 + facebook/lang/pl/strings.php | 49 + facebook/lang/pt-br/strings.php | 49 + facebook/lang/ru/strings.php | 49 + facebook/lang/sv/strings.php | 14 + facebook/lang/zh-cn/strings.php | 49 + facebook_restrict/facebook_restrict.php | 19 + facebook_restrict/lang/C/messages.po | 0 fbpost/README.md | 14 + fbpost/fbpost.css | 13 + fbpost/fbpost.php | 1240 ++++++++++ fbpost/lang/C/messages.po | 156 ++ fbpost/lang/ca/strings.php | 32 + fbpost/lang/cs/strings.php | 31 + fbpost/lang/de/strings.php | 32 + fbpost/lang/eo/strings.php | 28 + fbpost/lang/es/strings.php | 28 + fbpost/lang/fr/strings.php | 28 + fbpost/lang/is/strings.php | 28 + fbpost/lang/it/strings.php | 32 + fbpost/lang/nb-no/strings.php | 28 + fbpost/lang/pl/strings.php | 32 + fbpost/lang/pt-br/strings.php | 28 + fbpost/lang/ru/strings.php | 28 + fbpost/lang/sv/strings.php | 10 + fbpost/lang/zh-cn/strings.php | 32 + fbsync/README.md | 5 + fbsync/fbsync.css | 15 + fbsync/fbsync.php | 1146 +++++++++ fbsync/lang/C/messages.po | 43 + fortunate/cookie.php | 36 +- forumdirectory/forumdirectory.php | 30 +- forumlist/forumlist.css | 22 + forumlist/forumlist.php | 188 ++ forumlist/lang/C/messages.po | 58 + forumlist/lang/ca/strings.php | 12 + forumlist/lang/cs/messages.po | 60 + forumlist/lang/cs/strings.php | 17 + forumlist/lang/de/messages.po | 61 + forumlist/lang/de/strings.php | 17 + forumlist/lang/eo/strings.php | 9 + forumlist/lang/es/messages.po | 60 + forumlist/lang/es/strings.php | 17 + forumlist/lang/fr/strings.php | 12 + forumlist/lang/is/strings.php | 9 + forumlist/lang/it/messages.po | 60 + forumlist/lang/it/strings.php | 17 + forumlist/lang/nb-no/strings.php | 12 + forumlist/lang/pl/strings.php | 12 + forumlist/lang/pt-br/strings.php | 12 + forumlist/lang/ro/messages.po | 60 + forumlist/lang/ro/strings.php | 17 + forumlist/lang/ru/messages.po | 60 + forumlist/lang/ru/strings.php | 17 + forumlist/lang/sv/messages.po | 60 + forumlist/lang/sv/strings.php | 17 + forumlist/lang/zh-cn/strings.php | 12 + fromapp/fromapp.php | 42 +- fromgplus/fromgplus.php | 101 +- geocoordinates/geocoordinates.php | 37 +- geonames/geonames.php | 12 +- gnot/gnot.php | 7 +- googlemaps/googlemaps.php | 25 +- gpluspost/.gitignore | 2 + gpluspost/gpluspost.css | 19 + gpluspost/gpluspost.php | 576 +++++ gpluspost/lang/C/messages.po | 66 + gpluspost/lang/cs/messages.po | 68 + gpluspost/lang/cs/strings.php | 19 + gpluspost/lang/de/messages.po | 68 + gpluspost/lang/de/strings.php | 19 + gpluspost/lang/es/messages.po | 68 + gpluspost/lang/es/strings.php | 19 + gpluspost/lang/it/messages.po | 68 + gpluspost/lang/it/strings.php | 19 + gpluspost/lang/pt-br/messages.po | 68 + gpluspost/lang/pt-br/strings.php | 19 + gpluspost/lang/ro/messages.po | 67 + gpluspost/lang/ro/strings.php | 19 + gpluspost/lang/ru/messages.po | 68 + gpluspost/lang/ru/strings.php | 19 + gravatar/gravatar.php | 32 +- group_text/group_text.php | 5 +- ifttt/ifttt.php | 240 +- ifttt/lang/C/messages.po | 50 - ifttt/lang/de/messages.po | 55 - ifttt/lang/de/strings.php | 14 - ijpost/ijpost.php | 36 +- impressum/impressum.php | 44 +- irc/irc.php | 51 +- jappixmini.tgz | Bin 0 -> 1234436 bytes jappixmini/jappixmini.php | 771 +++--- jappixmini/proxy.php | 22 +- js_upload/js_upload.php | 112 +- krynn/krynn.php | 15 +- langfilter/langfilter.php | 199 +- ldapauth/ldapauth.php | 268 +-- leistungsschutzrecht/leistungsschutzrecht.php | 16 +- libertree/libertree.php | 57 +- libravatar/libravatar.php | 20 +- ljpost/ljpost.php | 40 +- mailstream/mailstream.php | 110 +- mathjax/mathjax.php | 29 +- morepokes/morepokes.php | 36 +- newmemberwidget/newmemberwidget.php | 30 +- notifyall/lang/fr/messages.po | 57 - notifyall/lang/fr/strings.php | 16 - notifyall/notifyall.php | 24 +- notimeline/notimeline.php | 15 +- nsfw/README | 89 - nsfw/nsfw.php | 36 +- numfriends/lang/fr/messages.po | 36 - numfriends/lang/fr/strings.php | 17 +- numfriends/numfriends.php | 15 +- openstreetmap/openstreetmap.php | 127 +- pageheader/pageheader.css | 2 +- pageheader/pageheader.php | 8 +- piwik/piwik.php | 30 +- planets/planets.php | 15 +- pledgie/pledgie.css | 2 +- pledgie/pledgie.php | 14 +- poormancron/lang/C/messages.po | 0 poormancron/poormancron.php | 69 + posterous/lang/C/messages.po | 58 + posterous/lang/ca/strings.php | 12 + posterous/lang/cs/strings.php | 12 + posterous/lang/de/strings.php | 12 + posterous/lang/eo/strings.php | 12 + posterous/lang/es/strings.php | 12 + posterous/lang/fr/strings.php | 12 + posterous/lang/is/strings.php | 12 + posterous/lang/it/strings.php | 12 + posterous/lang/nb-no/strings.php | 12 + posterous/lang/pl/strings.php | 12 + posterous/lang/pt-br/strings.php | 12 + posterous/lang/ru/strings.php | 12 + posterous/lang/sv/strings.php | 3 + posterous/lang/zh-cn/strings.php | 12 + posterous/posterous.css | 16 + posterous/posterous.php | 215 ++ procrunner/lang/C/messages.po | 0 procrunner/procrunner.php | 55 + public_server/public_server.php | 60 +- pumpio/pumpio.php | 340 ++- qcomment/qcomment.php | 34 +- randplace/randplace.php | 23 +- remote_permissions/remote_permissions.php | 44 +- rendertime/lang/fr/messages.po | 27 - rendertime/lang/fr/strings.php | 10 +- rendertime/rendertime.php | 6 +- retriever/README | 5 + retriever/database.sql | 36 + retriever/lang/C/messages.po | 102 + retriever/retriever.php | 839 +++++++ retriever/templates/extract.tpl | 31 + retriever/templates/fix-urls.tpl | 26 + retriever/templates/help.tpl | 148 ++ retriever/templates/rule-config.tpl | 112 + retriever/templates/settings.tpl | 9 + securemail/securemail.php | 38 +- showmore/showmore.php | 16 +- smileybutton/smileybutton.php | 60 +- snautofollow/lang/C/messages.po | 34 + snautofollow/lang/ca/strings.php | 6 + snautofollow/lang/cs/messages.po | 36 + snautofollow/lang/cs/strings.php | 11 + snautofollow/lang/de/messages.po | 36 + snautofollow/lang/de/strings.php | 11 + snautofollow/lang/eo/strings.php | 6 + snautofollow/lang/es/messages.po | 36 + snautofollow/lang/es/strings.php | 11 + snautofollow/lang/fr/strings.php | 6 + snautofollow/lang/is/strings.php | 6 + snautofollow/lang/it/messages.po | 36 + snautofollow/lang/it/strings.php | 11 + snautofollow/lang/nb-no/strings.php | 6 + snautofollow/lang/pl/strings.php | 6 + snautofollow/lang/pt-br/strings.php | 6 + snautofollow/lang/ro/messages.po | 35 + snautofollow/lang/ro/strings.php | 11 + snautofollow/lang/ru/strings.php | 6 + snautofollow/lang/sv/strings.php | 3 + snautofollow/lang/zh-cn/strings.php | 6 + snautofollow/snautofollow.css | 14 + snautofollow/snautofollow.php | 71 + startpage/startpage.php | 16 +- statistics_json/README.md | 14 + statistics_json/lang/C/messages.po | 0 statistics_json/statistics_json.php | 148 ++ statusnet/statusnet.php | 1568 ++++++------ superblock/lang/es/messages.po | 12 +- superblock/lang/es/strings.php | 6 +- superblock/superblock.php | 14 +- testdrive/testdrive.php | 19 +- tictac/tictac.php | 232 +- tumblr/tumblr.php | 91 +- twitter/README.md | 2 +- twitter/twitter.php | 1370 +++++------ uhremotestorage/lang/C/messages.po | 42 + uhremotestorage/lang/ca/strings.php | 7 + uhremotestorage/lang/cs/messages.po | 45 + uhremotestorage/lang/cs/strings.php | 12 + uhremotestorage/lang/de/messages.po | 45 + uhremotestorage/lang/de/strings.php | 12 + uhremotestorage/lang/eo/strings.php | 7 + uhremotestorage/lang/es/messages.po | 45 + uhremotestorage/lang/es/strings.php | 12 + uhremotestorage/lang/fr/strings.php | 7 + uhremotestorage/lang/is/strings.php | 7 + uhremotestorage/lang/it/messages.po | 45 + uhremotestorage/lang/it/strings.php | 12 + uhremotestorage/lang/nb-no/strings.php | 7 + uhremotestorage/lang/pl/strings.php | 7 + uhremotestorage/lang/pt-br/strings.php | 7 + uhremotestorage/lang/ro/messages.po | 44 + uhremotestorage/lang/ro/strings.php | 12 + uhremotestorage/lang/ru/strings.php | 7 + uhremotestorage/lang/sv/strings.php | 3 + uhremotestorage/lang/zh-cn/strings.php | 7 + uhremotestorage/templates/settings.tpl | 9 + uhremotestorage/uhremotestorage.php | 93 + unicode_smilies/unicode_smilies.php | 2 +- viewsrc/viewsrc.php | 4 +- webrtc/webrtc.php | 12 +- widgets/widget_friendheader.php | 10 +- widgets/widget_friends.php | 8 +- widgets/widget_like.php | 42 +- widgets/widgets.php | 85 +- windowsphonepush/windowsphonepush.php | 395 +-- wppost/wppost.php | 71 +- xmpp/lang/C/messages.po | 57 - xmpp/lang/de/messages.po | 61 - xmpp/lang/de/strings.php | 16 - xmpp/xmpp.php | 127 +- yourls/yourls.css | 2 +- yourls/yourls.php | 28 +- 355 files changed, 21487 insertions(+), 4995 deletions(-) create mode 100644 appnet/AppDotNet.php create mode 100644 appnet/DigiCertHighAssuranceEVRootCA.pem create mode 100644 appnet/README.md create mode 100644 appnet/appnet.css create mode 100644 appnet/appnet.php create mode 100644 appnet/lang/C/messages.po create mode 100644 appnet/lang/cs/messages.po create mode 100644 appnet/lang/cs/strings.php create mode 100644 appnet/lang/de/messages.po create mode 100644 appnet/lang/de/strings.php create mode 100644 appnet/lang/es/messages.po create mode 100644 appnet/lang/es/strings.php create mode 100644 appnet/lang/fr/messages.po create mode 100644 appnet/lang/fr/strings.php create mode 100644 appnet/lang/it/messages.po create mode 100644 appnet/lang/it/strings.php create mode 100644 appnet/lang/nl/messages.po create mode 100644 appnet/lang/nl/strings.php create mode 100644 appnet/lang/pt-br/messages.po create mode 100644 appnet/lang/pt-br/strings.php create mode 100644 appnet/lang/ro/messages.po create mode 100644 appnet/lang/ro/strings.php create mode 100644 appnet/lang/ru/messages.po create mode 100644 appnet/lang/ru/strings.php create mode 100644 appnet/templates/admin.tpl create mode 100644 cal/LICENSE create mode 100644 cal/README.md create mode 100644 cal/cal.php create mode 100644 cal/lang/C/messages.po create mode 100644 cal/lang/C/strings.php create mode 100644 cal/lang/cs/messages.po create mode 100644 cal/lang/cs/strings.php create mode 100644 cal/lang/de/messages.po create mode 100644 cal/lang/de/strings.php create mode 100644 cal/lang/es/messages.po create mode 100644 cal/lang/es/strings.php create mode 100644 cal/lang/fr/messages.po create mode 100644 cal/lang/fr/strings.php create mode 100644 cal/lang/it/messages.po create mode 100644 cal/lang/it/strings.php create mode 100644 cal/lang/pt-br/messages.po create mode 100644 cal/lang/pt-br/strings.php create mode 100644 cal/lang/ro/messages.po create mode 100644 cal/lang/ro/strings.php create mode 100644 cal/lang/ru/messages.po create mode 100644 cal/lang/ru/strings.php create mode 100644 cal/lang/zh-cn/messages.po create mode 100644 cal/lang/zh-cn/strings.php delete mode 100644 communityhome/templates/settings.tpl create mode 100644 convpath/README create mode 100644 convpath/convpath.php create mode 100644 convpath/lang/C/messages.po create mode 100644 defaultfeatures/README create mode 100644 defaultfeatures/defaultfeatures.php create mode 100644 defaultfeatures/lang/C/messages.po create mode 100644 defaultfeatures/templates/admin.tpl create mode 100644 editplain/editplain.css create mode 100644 editplain/editplain.php create mode 100644 editplain/lang/C/messages.po create mode 100644 editplain/lang/ca/strings.php create mode 100644 editplain/lang/cs/messages.po create mode 100644 editplain/lang/cs/strings.php create mode 100644 editplain/lang/de/messages.po create mode 100644 editplain/lang/de/strings.php create mode 100644 editplain/lang/eo/strings.php create mode 100644 editplain/lang/es/messages.po create mode 100644 editplain/lang/es/strings.php create mode 100644 editplain/lang/fr/messages.po create mode 100644 editplain/lang/fr/strings.php create mode 100644 editplain/lang/is/strings.php create mode 100644 editplain/lang/it/messages.po create mode 100644 editplain/lang/it/strings.php create mode 100644 editplain/lang/nb-no/strings.php create mode 100644 editplain/lang/pl/strings.php create mode 100644 editplain/lang/pt-br/strings.php create mode 100644 editplain/lang/ro/messages.po create mode 100644 editplain/lang/ro/strings.php create mode 100644 editplain/lang/ru/messages.po create mode 100644 editplain/lang/ru/strings.php create mode 100644 editplain/lang/sv/strings.php create mode 100644 editplain/lang/zh-cn/strings.php create mode 100644 extcron/extcron.php create mode 100644 extcron/lang/C/messages.po create mode 100644 facebook/README.md create mode 100644 facebook/facebook.css create mode 100644 facebook/facebook.php create mode 100644 facebook/lang/C/messages.po create mode 100644 facebook/lang/ca/strings.php create mode 100644 facebook/lang/cs/strings.php create mode 100644 facebook/lang/de/strings.php create mode 100644 facebook/lang/eo/strings.php create mode 100644 facebook/lang/es/strings.php create mode 100644 facebook/lang/fr/strings.php create mode 100644 facebook/lang/is/strings.php create mode 100644 facebook/lang/it/strings.php create mode 100644 facebook/lang/nb-no/strings.php create mode 100644 facebook/lang/pl/strings.php create mode 100644 facebook/lang/pt-br/strings.php create mode 100644 facebook/lang/ru/strings.php create mode 100644 facebook/lang/sv/strings.php create mode 100644 facebook/lang/zh-cn/strings.php create mode 100644 facebook_restrict/facebook_restrict.php create mode 100644 facebook_restrict/lang/C/messages.po create mode 100644 fbpost/README.md create mode 100644 fbpost/fbpost.css create mode 100644 fbpost/fbpost.php create mode 100644 fbpost/lang/C/messages.po create mode 100644 fbpost/lang/ca/strings.php create mode 100644 fbpost/lang/cs/strings.php create mode 100644 fbpost/lang/de/strings.php create mode 100644 fbpost/lang/eo/strings.php create mode 100644 fbpost/lang/es/strings.php create mode 100644 fbpost/lang/fr/strings.php create mode 100644 fbpost/lang/is/strings.php create mode 100644 fbpost/lang/it/strings.php create mode 100644 fbpost/lang/nb-no/strings.php create mode 100644 fbpost/lang/pl/strings.php create mode 100644 fbpost/lang/pt-br/strings.php create mode 100644 fbpost/lang/ru/strings.php create mode 100644 fbpost/lang/sv/strings.php create mode 100644 fbpost/lang/zh-cn/strings.php create mode 100644 fbsync/README.md create mode 100644 fbsync/fbsync.css create mode 100644 fbsync/fbsync.php create mode 100644 fbsync/lang/C/messages.po create mode 100644 forumlist/forumlist.css create mode 100644 forumlist/forumlist.php create mode 100644 forumlist/lang/C/messages.po create mode 100644 forumlist/lang/ca/strings.php create mode 100644 forumlist/lang/cs/messages.po create mode 100644 forumlist/lang/cs/strings.php create mode 100644 forumlist/lang/de/messages.po create mode 100644 forumlist/lang/de/strings.php create mode 100644 forumlist/lang/eo/strings.php create mode 100644 forumlist/lang/es/messages.po create mode 100644 forumlist/lang/es/strings.php create mode 100644 forumlist/lang/fr/strings.php create mode 100644 forumlist/lang/is/strings.php create mode 100644 forumlist/lang/it/messages.po create mode 100644 forumlist/lang/it/strings.php create mode 100644 forumlist/lang/nb-no/strings.php create mode 100644 forumlist/lang/pl/strings.php create mode 100644 forumlist/lang/pt-br/strings.php create mode 100644 forumlist/lang/ro/messages.po create mode 100644 forumlist/lang/ro/strings.php create mode 100644 forumlist/lang/ru/messages.po create mode 100644 forumlist/lang/ru/strings.php create mode 100644 forumlist/lang/sv/messages.po create mode 100644 forumlist/lang/sv/strings.php create mode 100644 forumlist/lang/zh-cn/strings.php create mode 100644 gpluspost/.gitignore create mode 100644 gpluspost/gpluspost.css create mode 100644 gpluspost/gpluspost.php create mode 100644 gpluspost/lang/C/messages.po create mode 100644 gpluspost/lang/cs/messages.po create mode 100644 gpluspost/lang/cs/strings.php create mode 100644 gpluspost/lang/de/messages.po create mode 100644 gpluspost/lang/de/strings.php create mode 100644 gpluspost/lang/es/messages.po create mode 100644 gpluspost/lang/es/strings.php create mode 100644 gpluspost/lang/it/messages.po create mode 100644 gpluspost/lang/it/strings.php create mode 100644 gpluspost/lang/pt-br/messages.po create mode 100644 gpluspost/lang/pt-br/strings.php create mode 100644 gpluspost/lang/ro/messages.po create mode 100644 gpluspost/lang/ro/strings.php create mode 100644 gpluspost/lang/ru/messages.po create mode 100644 gpluspost/lang/ru/strings.php delete mode 100644 ifttt/lang/C/messages.po delete mode 100644 ifttt/lang/de/messages.po delete mode 100644 ifttt/lang/de/strings.php create mode 100644 jappixmini.tgz delete mode 100644 notifyall/lang/fr/messages.po delete mode 100644 notifyall/lang/fr/strings.php delete mode 100644 numfriends/lang/fr/messages.po create mode 100644 poormancron/lang/C/messages.po create mode 100644 poormancron/poormancron.php create mode 100644 posterous/lang/C/messages.po create mode 100644 posterous/lang/ca/strings.php create mode 100644 posterous/lang/cs/strings.php create mode 100644 posterous/lang/de/strings.php create mode 100644 posterous/lang/eo/strings.php create mode 100644 posterous/lang/es/strings.php create mode 100644 posterous/lang/fr/strings.php create mode 100644 posterous/lang/is/strings.php create mode 100644 posterous/lang/it/strings.php create mode 100644 posterous/lang/nb-no/strings.php create mode 100644 posterous/lang/pl/strings.php create mode 100644 posterous/lang/pt-br/strings.php create mode 100644 posterous/lang/ru/strings.php create mode 100644 posterous/lang/sv/strings.php create mode 100644 posterous/lang/zh-cn/strings.php create mode 100644 posterous/posterous.css create mode 100644 posterous/posterous.php create mode 100644 procrunner/lang/C/messages.po create mode 100644 procrunner/procrunner.php delete mode 100644 rendertime/lang/fr/messages.po create mode 100644 retriever/README create mode 100644 retriever/database.sql create mode 100644 retriever/lang/C/messages.po create mode 100644 retriever/retriever.php create mode 100644 retriever/templates/extract.tpl create mode 100644 retriever/templates/fix-urls.tpl create mode 100644 retriever/templates/help.tpl create mode 100644 retriever/templates/rule-config.tpl create mode 100644 retriever/templates/settings.tpl create mode 100644 snautofollow/lang/C/messages.po create mode 100644 snautofollow/lang/ca/strings.php create mode 100644 snautofollow/lang/cs/messages.po create mode 100644 snautofollow/lang/cs/strings.php create mode 100644 snautofollow/lang/de/messages.po create mode 100644 snautofollow/lang/de/strings.php create mode 100644 snautofollow/lang/eo/strings.php create mode 100644 snautofollow/lang/es/messages.po create mode 100644 snautofollow/lang/es/strings.php create mode 100644 snautofollow/lang/fr/strings.php create mode 100644 snautofollow/lang/is/strings.php create mode 100644 snautofollow/lang/it/messages.po create mode 100644 snautofollow/lang/it/strings.php create mode 100644 snautofollow/lang/nb-no/strings.php create mode 100644 snautofollow/lang/pl/strings.php create mode 100644 snautofollow/lang/pt-br/strings.php create mode 100644 snautofollow/lang/ro/messages.po create mode 100644 snautofollow/lang/ro/strings.php create mode 100644 snautofollow/lang/ru/strings.php create mode 100644 snautofollow/lang/sv/strings.php create mode 100644 snautofollow/lang/zh-cn/strings.php create mode 100644 snautofollow/snautofollow.css create mode 100644 snautofollow/snautofollow.php create mode 100644 statistics_json/README.md create mode 100644 statistics_json/lang/C/messages.po create mode 100644 statistics_json/statistics_json.php create mode 100644 uhremotestorage/lang/C/messages.po create mode 100644 uhremotestorage/lang/ca/strings.php create mode 100644 uhremotestorage/lang/cs/messages.po create mode 100644 uhremotestorage/lang/cs/strings.php create mode 100644 uhremotestorage/lang/de/messages.po create mode 100644 uhremotestorage/lang/de/strings.php create mode 100644 uhremotestorage/lang/eo/strings.php create mode 100644 uhremotestorage/lang/es/messages.po create mode 100644 uhremotestorage/lang/es/strings.php create mode 100644 uhremotestorage/lang/fr/strings.php create mode 100644 uhremotestorage/lang/is/strings.php create mode 100644 uhremotestorage/lang/it/messages.po create mode 100644 uhremotestorage/lang/it/strings.php create mode 100644 uhremotestorage/lang/nb-no/strings.php create mode 100644 uhremotestorage/lang/pl/strings.php create mode 100644 uhremotestorage/lang/pt-br/strings.php create mode 100644 uhremotestorage/lang/ro/messages.po create mode 100644 uhremotestorage/lang/ro/strings.php create mode 100644 uhremotestorage/lang/ru/strings.php create mode 100644 uhremotestorage/lang/sv/strings.php create mode 100644 uhremotestorage/lang/zh-cn/strings.php create mode 100644 uhremotestorage/templates/settings.tpl create mode 100644 uhremotestorage/uhremotestorage.php delete mode 100644 xmpp/lang/C/messages.po delete mode 100644 xmpp/lang/de/messages.po delete mode 100644 xmpp/lang/de/strings.php diff --git a/appnet/AppDotNet.php b/appnet/AppDotNet.php new file mode 100644 index 00000000..32361314 --- /dev/null +++ b/appnet/AppDotNet.php @@ -0,0 +1,1647 @@ +_clientId = $client_id; + $this->_clientSecret = $client_secret; + + // if the digicert certificate exists in the same folder as this file, + // remember that fact for later + if (file_exists(dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem')) { + $this->_sslCA = dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem'; + } + } + + /** + * Set whether or not to strip Envelope Response (meta) information + * This option will be deprecated in the future. Is it to allow + * a stepped migration path between code expecting the old behavior + * and new behavior. When not stripped, you still can use the proper + * method to pull the meta information. Please start converting your code ASAP + */ + public function includeResponseEnvelope() { + $this->_stripResponseEnvelope=false; + } + + /** + * Construct the proper Auth URL for the user to visit and either grant + * or not access to your app. Usually you would place this as a link for + * the user to client, or a redirect to send them to the auth URL. + * Also can be called after authentication for additional scopes + * @param string $callbackUri Where you want the user to be directed + * after authenticating with App.net. This must be one of the URIs + * allowed by your App.net application settings. + * @param array $scope An array of scopes (permissions) you wish to obtain + * from the user. Currently options are stream, email, write_post, follow, + * messages, and export. If you don't specify anything, you'll only receive + * access to the user's basic profile (the default). + */ + public function getAuthUrl($callback_uri,$scope=null) { + + // construct an authorization url based on our client id and other data + $data = array( + 'client_id'=>$this->_clientId, + 'response_type'=>'code', + 'redirect_uri'=>$callback_uri, + ); + + $url = $this->_authUrl; + if ($this->_accessToken) { + $url .= 'authorize?'; + } else { + $url .= 'authenticate?'; + } + $url .= $this->buildQueryString($data); + + if ($scope) { + $url .= '&scope='.implode('+',$scope); + } + + // return the constructed url + return $url; + } + + /** + * Call this after they return from the auth page, or anytime you need the + * token. For example, you could store it in a database and use + * setAccessToken() later on to return on behalf of the user. + */ + public function getAccessToken($callback_uri) { + // if there's no access token set, and they're returning from + // the auth page with a code, use the code to get a token + if (!$this->_accessToken && isset($_GET['code']) && $_GET['code']) { + + // construct the necessary elements to get a token + $data = array( + 'client_id'=>$this->_clientId, + 'client_secret'=>$this->_clientSecret, + 'grant_type'=>'authorization_code', + 'redirect_uri'=>$callback_uri, + 'code'=>$_GET['code'] + ); + + // try and fetch the token with the above data + $res = $this->httpReq('post',$this->_authUrl.'access_token', $data); + + // store it for later + $this->_accessToken = $res['access_token']; + $this->_username = $res['username']; + $this->_user_id = $res['user_id']; + } + + // return what we have (this may be a token, or it may be nothing) + return $this->_accessToken; + } + + /** + * Check the scope of current token to see if it has required scopes + * has to be done after a check + */ + public function checkScopes($app_scopes) { + if (!count($this->_scopes)) { + return -1; // _scope is empty + } + $missing=array(); + foreach($app_scopes as $scope) { + if (!in_array($scope,$this->_scopes)) { + if ($scope=='public_messages') { + // messages works for public_messages + if (in_array('messages',$this->_scopes)) { + // if we have messages in our scopes + continue; + } + } + $missing[]=$scope; + } + } + // identify the ones missing + if (count($missing)) { + // do something + return $missing; + } + return 0; // 0 missing + } + + /** + * Set the access token (eg: after retrieving it from offline storage) + * @param string $token A valid access token you're previously received + * from calling getAccessToken(). + */ + public function setAccessToken($token) { + $this->_accessToken = $token; + } + + /** + * Deauthorize the current token (delete your authorization from the API) + * Generally this is useful for logging users out from a web app, so they + * don't get automatically logged back in the next time you redirect them + * to the authorization URL. + */ + public function deauthorizeToken() { + return $this->httpReq('delete',$this->_baseUrl.'token'); + } + + /** + * Retrieve an app access token from the app.net API. This allows you + * to access the API without going through the user access flow if you + * just want to (eg) consume global. App access tokens are required for + * some actions (like streaming global). DO NOT share the return value + * of this function with any user (or save it in a cookie, etc). This + * is considered secret info for your app only. + * @return string The app access token + */ + public function getAppAccessToken() { + + // construct the necessary elements to get a token + $data = array( + 'client_id'=>$this->_clientId, + 'client_secret'=>$this->_clientSecret, + 'grant_type'=>'client_credentials', + ); + + // try and fetch the token with the above data + $res = $this->httpReq('post',$this->_authUrl.'access_token', $data); + + // store it for later + $this->_appAccessToken = $res['access_token']; + $this->_accessToken = $res['access_token']; + $this->_username = null; + $this->_user_id = null; + + return $this->_accessToken; + } + + /** + * Returns the total number of requests you're allowed within the + * alloted time period. + * @see getRateLimitReset() + */ + public function getRateLimit() { + return $this->_rateLimit; + } + + /** + * The number of requests you have remaining within the alloted time period + * @see getRateLimitReset() + */ + public function getRateLimitRemaining() { + return $this->_rateLimitRemaining; + } + + /** + * The number of seconds remaining in the alloted time period. + * When this time is up you'll have getRateLimit() available again. + */ + public function getRateLimitReset() { + return $this->_rateLimitReset; + } + + /** + * The scope the user has + */ + public function getScope() { + return $this->_scope; + } + + /** + * Internal function, parses out important information App.net adds + * to the headers. + */ + protected function parseHeaders($response) { + // take out the headers + // set internal variables + // return the body/content + $this->_rateLimit = null; + $this->_rateLimitRemaining = null; + $this->_rateLimitReset = null; + $this->_scope = null; + + $response = explode("\r\n\r\n",$response,2); + $headers = $response[0]; + + if($headers == 'HTTP/1.1 100 Continue') { + $response = explode("\r\n\r\n",$response[1],2); + $headers = $response[0]; + } + + if (isset($response[1])) { + $content = $response[1]; + } + else { + $content = null; + } + + // this is not a good way to parse http headers + // it will not (for example) take into account multiline headers + // but what we're looking for is pretty basic, so we can ignore those shortcomings + $headers = explode("\r\n",$headers); + foreach ($headers as $header) { + $header = explode(': ',$header,2); + if (count($header)<2) { + continue; + } + list($k,$v) = $header; + switch ($k) { + case 'X-RateLimit-Remaining': + $this->_rateLimitRemaining = $v; + break; + case 'X-RateLimit-Limit': + $this->_rateLimit = $v; + break; + case 'X-RateLimit-Reset': + $this->_rateLimitReset = $v; + break; + case 'X-OAuth-Scopes': + $this->_scope = $v; + $this->_scopes=explode(',',$v); + break; + } + } + return $content; + } + + /** + * Internal function. Used to turn things like TRUE into 1, and then + * calls http_build_query. + */ + protected function buildQueryString($array) { + foreach ($array as $k=>&$v) { + if ($v===true) { + $v = '1'; + } + elseif ($v===false) { + $v = '0'; + } + unset($v); + } + return http_build_query($array); + } + + + /** + * Internal function to handle all + * HTTP requests (POST,PUT,GET,DELETE) + */ + protected function httpReq($act, $req, $params=array(),$contentType='application/x-www-form-urlencoded') { + $ch = curl_init($req); + $headers = array(); + if($act != 'get') { + curl_setopt($ch, CURLOPT_POST, true); + // if they passed an array, build a list of parameters from it + if (is_array($params) && $act != 'post-raw') { + $params = $this->buildQueryString($params); + } + curl_setopt($ch, CURLOPT_POSTFIELDS, $params); + $headers[] = "Content-Type: ".$contentType; + } + if($act != 'post' && $act != 'post-raw') { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($act)); + } + if($act == 'get' && isset($params['access_token'])) { + $headers[] = 'Authorization: Bearer '.$params['access_token']; + } + else if ($this->_accessToken) { + $headers[] = 'Authorization: Bearer '.$this->_accessToken; + } + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLINFO_HEADER_OUT, true); + curl_setopt($ch, CURLOPT_HEADER, true); + if ($this->_sslCA) { + curl_setopt($ch, CURLOPT_CAINFO, $this->_sslCA); + } + $this->_last_response = curl_exec($ch); + $this->_last_request = curl_getinfo($ch,CURLINFO_HEADER_OUT); + $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + if ($http_status==0) { + throw new AppDotNetException('Unable to connect to '.$req); + } + if ($http_status<200 || $http_status>=300) { + throw new AppDotNetException('HTTP error '.$this->_last_response); + } + if ($this->_last_request===false) { + if (!curl_getinfo($ch,CURLINFO_SSL_VERIFYRESULT)) { + throw new AppDotNetException('SSL verification failed, connection terminated.'); + } + } + $response = $this->parseHeaders($this->_last_response); + $response = json_decode($response,true); + + if (isset($response['meta'])) { + if (isset($response['meta']['max_id'])) { + $this->_maxid=$response['meta']['max_id']; + $this->_minid=$response['meta']['min_id']; + } + if (isset($response['meta']['more'])) { + $this->_more=$response['meta']['more']; + } + if (isset($response['meta']['marker'])) { + $this->_last_marker=$response['meta']['marker']; + } + } + + // look for errors + if (isset($response['error'])) { + if (is_array($response['error'])) { + throw new AppDotNetException($response['error']['message'], + $response['error']['code']); + } + else { + throw new AppDotNetException($response['error']); + } + } + + // look for response migration errors + elseif (isset($response['meta']) && isset($response['meta']['error_message'])) { + throw new AppDotNetException($response['meta']['error_message'],$response['meta']['code']); + } + + // if we've received a migration response, handle it and return data only + elseif ($this->_stripResponseEnvelope && isset($response['meta']) && isset($response['data'])) { + return $response['data']; + } + + // else non response migration response, just return it + else { + return $response; + } + } + + + /** + * Get max_id from last meta response data envelope + */ + public function getResponseMaxID() { + return $this->_maxid; + } + + /** + * Get min_id from last meta response data envelope + */ + public function getResponseMinID() { + return $this->_minid; + } + + /** + * Get more from last meta response data envelope + */ + public function getResponseMore() { + return $this->_more; + } + + /** + * Get marker from last meta response data envelope + */ + public function getResponseMarker() { + return $this->_last_marker; + } + + /** + * Fetch API configuration object + */ + public function getConfig() { + return $this->httpReq('get',$this->_baseUrl.'config'); + } + + /** + * Return the Filters for the current user. + */ + public function getAllFilters() { + return $this->httpReq('get',$this->_baseUrl.'filters'); + } + + /** + * Create a Filter for the current user. + * @param string $name The name of the new filter + * @param array $filters An associative array of filters to be applied. + * This may change as the API evolves, as of this writing possible + * values are: user_ids, hashtags, link_domains, and mention_user_ids. + * You will need to provide at least one filter name=>value pair. + */ + public function createFilter($name='New filter', $filters=array()) { + $filters['name'] = $name; + return $this->httpReq('post',$this->_baseUrl.'filters',$filters); + } + + /** + * Returns a specific Filter object. + * @param integer $filter_id The ID of the filter you wish to retrieve. + */ + public function getFilter($filter_id=null) { + return $this->httpReq('get',$this->_baseUrl.'filters/'.urlencode($filter_id)); + } + + /** + * Delete a Filter. The Filter must belong to the current User. + * @return object Returns the deleted Filter on success. + */ + public function deleteFilter($filter_id=null) { + return $this->httpReq('delete',$this->_baseUrl.'filters/'.urlencode($filter_id)); + } + + /** + * Process user description, message or post text. + * Mentions and hashtags will be parsed out of the + * text, as will bare URLs. To create a link in the text without using a + * bare URL, include the anchor text in the object text and include a link + * entity in the function call. + * @param string $text The text of the description/message/post + * @param array $data An associative array of optional post data. This + * will likely change as the API evolves, as of this writing allowed keys are: + * reply_to, and annotations. "annotations" may be a complex object represented + * by an associative array. + * @param array $params An associative array of optional data to be included + * in the URL (such as 'include_annotations' and 'include_machine') + * @return array An associative array representing the post. + */ + public function processText($text=null, $data = array(), $params = array()) { + $data['text'] = $text; + $json = json_encode($data); + $qs = ''; + if (!empty($params)) { + $qs = '?'.$this->buildQueryString($params); + } + return $this->httpReq('post',$this->_baseUrl.'text/process'.$qs, $json, 'application/json'); + } + + /** + * Create a new Post object. Mentions and hashtags will be parsed out of the + * post text, as will bare URLs. To create a link in a post without using a + * bare URL, include the anchor text in the post's text and include a link + * entity in the post creation call. + * @param string $text The text of the post + * @param array $data An associative array of optional post data. This + * will likely change as the API evolves, as of this writing allowed keys are: + * reply_to, and annotations. "annotations" may be a complex object represented + * by an associative array. + * @param array $params An associative array of optional data to be included + * in the URL (such as 'include_annotations' and 'include_machine') + * @return array An associative array representing the post. + */ + public function createPost($text=null, $data = array(), $params = array()) { + $data['text'] = $text; + + $json = json_encode($data); + $qs = ''; + if (!empty($params)) { + $qs = '?'.$this->buildQueryString($params); + } + return $this->httpReq('post',$this->_baseUrl.'posts'.$qs, $json, 'application/json'); + } + + /** + * Returns a specific Post. + * @param integer $post_id The ID of the post to retrieve + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations. + * @return array An associative array representing the post + */ + public function getPost($post_id=null,$params = array()) { + return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id) + .'?'.$this->buildQueryString($params)); + } + + /** + * Delete a Post. The current user must be the same user who created the Post. + * It returns the deleted Post on success. + * @param integer $post_id The ID of the post to delete + * @param array An associative array representing the post that was deleted + */ + public function deletePost($post_id=null) { + return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id)); + } + + /** + * Retrieve the Posts that are 'in reply to' a specific Post. + * @param integer $post_id The ID of the post you want to retrieve replies for. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getPostReplies($post_id=null,$params = array()) { + return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id) + .'/replies?'.$this->buildQueryString($params)); + } + + /** + * Get the most recent Posts created by a specific User in reverse + * chronological order (most recent first). + * @param mixed $user_id Either the ID of the user you wish to retrieve posts by, + * or the string "me", which will retrieve posts for the user you're authenticated + * as. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getUserPosts($user_id='me', $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id) + .'/posts?'.$this->buildQueryString($params)); + } + + /** + * Get the most recent Posts mentioning by a specific User in reverse + * chronological order (newest first). + * @param mixed $user_id Either the ID of the user who is being mentioned, or + * the string "me", which will retrieve posts for the user you're authenticated + * as. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getUserMentions($user_id='me',$params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users/' + .urlencode($user_id).'/mentions?'.$this->buildQueryString($params)); + } + + /** + * Return the 20 most recent posts from the current User and + * the Users they follow. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getUserStream($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params)); + } + + /** + * Returns a specific user object. + * @param mixed $user_id The ID of the user you want to retrieve, or the string + * "me" to retrieve data for the users you're currently authenticated as. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_user_annotations. + * @return array An associative array representing the user data. + */ + public function getUser($user_id='me', $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id) + .'?'.$this->buildQueryString($params)); + } + + /** + * Returns multiple users request by an array of user ids + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_user_annotations. + * @return array An associative array representing the users data. + */ + public function getUsers($user_arr, $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users?ids='.join(',',$user_arr) + .'&'.$this->buildQueryString($params)); + } + + /** + * Add the specified user ID to the list of users followed. + * Returns the User object of the user being followed. + * @param integer $user_id The user ID of the user to follow. + * @return array An associative array representing the user you just followed. + */ + public function followUser($user_id=null) { + return $this->httpReq('post',$this->_baseUrl.'users/'.urlencode($user_id).'/follow'); + } + + /** + * Removes the specified user ID to the list of users followed. + * Returns the User object of the user being unfollowed. + * @param integer $user_id The user ID of the user to unfollow. + * @return array An associative array representing the user you just unfollowed. + */ + public function unfollowUser($user_id=null) { + return $this->httpReq('delete',$this->_baseUrl.'users/'.urlencode($user_id).'/follow'); + } + + /** + * Returns an array of User objects the specified user is following. + * @param mixed $user_id Either the ID of the user being followed, or + * the string "me", which will retrieve posts for the user you're authenticated + * as. + * @return array An array of associative arrays, each representing a single + * user following $user_id + */ + public function getFollowing($user_id='me') { + return $this->httpReq('get',$this->_baseUrl.'users/'.$user_id.'/following'); + } + + /** + * Returns an array of User objects for users following the specified user. + * @param mixed $user_id Either the ID of the user being followed, or + * the string "me", which will retrieve posts for the user you're authenticated + * as. + * @return array An array of associative arrays, each representing a single + * user following $user_id + */ + public function getFollowers($user_id='me') { + return $this->httpReq('get',$this->_baseUrl.'users/'.$user_id.'/followers'); + } + + /** + * Return Posts matching a specific #hashtag. + * @param string $hashtag The hashtag you're looking for. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function searchHashtags($hashtag=null, $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'posts/tag/' + .urlencode($hashtag).'?'.$this->buildQueryString($params)); + } + + /** + * Retrieve a list of all public Posts on App.net, often referred to as the + * global stream. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getPublicPosts($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'posts/stream/global?'.$this->buildQueryString($params)); + } + + /** + * List User interactions + */ + public function getMyInteractions($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users/me/interactions?'.$this->buildQueryString($params)); + } + + /** + * Retrieve a user's user ID by specifying their username. + * Now supported by the API. We use the API if we have a token + * Otherwise we scrape the alpha.app.net site for the info. + * @param string $username The username of the user you want the ID of, without + * an @ symbol at the beginning. + * @return integer The user's user ID + */ + public function getIdByUsername($username=null) { + if ($this->_accessToken) { + $res=$this->httpReq('get',$this->_baseUrl.'users/@'.$username); + $user_id=$res['data']['id']; + } else { + $ch = curl_init('https://alpha.app.net/'.urlencode(strtolower($username))); + curl_setopt($ch, CURLOPT_POST, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch,CURLOPT_USERAGENT, + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'); + $response = curl_exec($ch); + curl_close($ch); + $temp = explode('title="User Id ',$response); + $temp2 = explode('"',$temp[1]); + $user_id = $temp2[0]; + } + return $user_id; + } + + /** + * Mute a user + * @param integer $user_id The user ID to mute + */ + public function muteUser($user_id=null) { + return $this->httpReq('post',$this->_baseUrl.'users/'.urlencode($user_id).'/mute'); + } + + /** + * Unmute a user + * @param integer $user_id The user ID to unmute + */ + public function unmuteUser($user_id=null) { + return $this->httpReq('delete',$this->_baseUrl.'users/'.urlencode($user_id).'/mute'); + } + + /** + * List the users muted by the current user + * @return array An array of associative arrays, each representing one muted user. + */ + public function getMuted() { + return $this->httpReq('get',$this->_baseUrl.'users/me/muted'); + } + + /** + * Star a post + * @param integer $post_id The post ID to star + */ + public function starPost($post_id=null) { + return $this->httpReq('post',$this->_baseUrl.'posts/'.urlencode($post_id).'/star'); + } + + /** + * Unstar a post + * @param integer $post_id The post ID to unstar + */ + public function unstarPost($post_id=null) { + return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id).'/star'); + } + + /** + * List the posts starred by the current user + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * See https://github.com/appdotnet/api-spec/blob/master/resources/posts.md#general-parameters + * @return array An array of associative arrays, each representing a single + * user who has starred a post + */ + public function getStarred($user_id='me', $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id).'/stars' + .'?'.$this->buildQueryString($params)); + } + + /** + * List the users who have starred a post + * @param integer $post_id the post ID to get stars from + * @return array An array of associative arrays, each representing one user. + */ + public function getStars($post_id=null) { + return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id).'/stars'); + } + + /** + * Returns an array of User objects of users who reposted the specified post. + * @param integer $post_id the post ID to + * @return array An array of associative arrays, each representing a single + * user who reposted $post_id + */ + public function getReposters($post_id){ + return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id).'/reposters'); + } + + /** + * Repost an existing Post object. + * @param integer $post_id The id of the post + * @return not a clue + */ + public function repost($post_id){ + return $this->httpReq('post',$this->_baseUrl.'posts/'.urlencode($post_id).'/repost'); + } + + /** + * Delete a post that the user has reposted. + * @param integer $post_id The id of the post + * @return not a clue + */ + public function deleteRepost($post_id){ + return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id).'/repost'); + } + + /** + * List the posts who match a specific search term + * @param array $params a list of filter, search query, and general Post parameters + * see: https://developers.app.net/reference/resources/post/search/ + * @param string $query The search query. Supports + * normal search terms. Searches post text. + * @return array An array of associative arrays, each representing one post. + * or false on error + */ + public function searchPosts($params = array(), $query='', $order='default') { + if (!is_array($params)) { + return false; + } + if (!empty($query)) { + $params['query']=$query; + } + if ($order=='default') { + if (!empty($query)) { + $params['order']='score'; + } else { + $params['order']='id'; + } + } + return $this->httpReq('get',$this->_baseUrl.'posts/search?'.$this->buildQueryString($params)); + } + + + /** + * List the users who match a specific search term + * @param string $search The search query. Supports @username or #tag searches as + * well as normal search terms. Searches username, display name, bio information. + * Does not search posts. + * @return array An array of associative arrays, each representing one user. + */ + public function searchUsers($search="") { + return $this->httpReq('get',$this->_baseUrl.'users/search?q='.urlencode($search)); + } + + /** + * Return the 20 most recent posts for a stream using a valid Token + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getTokenStream($params = array()) { + if ($params['access_token']) { + return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params),$params); + } else { + return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params)); + } + } + + /** + * Get a user object by username + * @param string $name the @name to get + * @return array representing one user + */ + public function getUserByName($name=null) { + return $this->httpReq('get',$this->_baseUrl.'users/@'.$name); + } + + /** + * Return the 20 most recent Posts from the current User's personalized stream + * and mentions stream merged into one stream. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * @return An array of associative arrays, each representing a single post. + */ + public function getUserUnifiedStream($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'posts/stream/unified?'.$this->buildQueryString($params)); + } + + /** + * Update Profile Data via JSON + * @data array containing user descriptors + */ + public function updateUserData($data = array(), $params = array()) { + $json = json_encode($data); + return $this->httpReq('put',$this->_baseUrl.'users/me'.'?'. + $this->buildQueryString($params), $json, 'application/json'); + } + + /** + * Update a user image + * @which avatar|cover + * @image path reference to image + */ + protected function updateUserImage($which = 'avatar', $image = null) { + $data = array($which=>"@$image"); + return $this->httpReq('post-raw',$this->_baseUrl.'users/me/'.$which, $data, 'multipart/form-data'); + } + + public function updateUserAvatar($avatar = null) { + if($avatar != null) + return $this->updateUserImage('avatar', $avatar); + } + + public function updateUserCover($cover = null) { + if($cover != null) + return $this->updateUserImage('cover', $cover); + } + + /** + * update stream marker + */ + public function updateStreamMarker($data = array()) { + $json = json_encode($data); + return $this->httpReq('post',$this->_baseUrl.'posts/marker', $json, 'application/json'); + } + + /** + * get a page of current user subscribed channels + */ + public function getUserSubscriptions($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'channels?'.$this->buildQueryString($params)); + } + + /** + * get user channels + */ + public function getMyChannels($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'channels/me?'.$this->buildQueryString($params)); + } + + /** + * create a channel + * note: you cannot create a channel with type=net.app.core.pm (see createMessage) + */ + public function createChannel($data = array()) { + $json = json_encode($data); + return $this->httpReq('post',$this->_baseUrl.'channels'.($pm?'/pm/messsages':''), $json, 'application/json'); + } + + /** + * get channelid info + */ + public function getChannel($channelid, $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'?'.$this->buildQueryString($params)); + } + + /** + * get multiple channels' info by an array of channelids + */ + public function getChannels($channels, $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'channels?ids='.join(',',$channels).'&'.$this->buildQueryString($params)); + } + + /** + * update channelid + */ + public function updateChannel($channelid, $data = array()) { + $json = json_encode($data); + return $this->httpReq('put',$this->_baseUrl.'channels/'.$channelid, $json, 'application/json'); + } + + /** + * subscribe from channelid + */ + public function channelSubscribe($channelid) { + return $this->httpReq('post',$this->_baseUrl.'channels/'.$channelid.'/subscribe'); + } + + /** + * unsubscribe from channelid + */ + public function channelUnsubscribe($channelid) { + return $this->httpReq('delete',$this->_baseUrl.'channels/'.$channelid.'/subscribe'); + } + + /** + * get all user objects subscribed to channelid + */ + public function getChannelSubscriptions($channelid, $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'channel/'.$channelid.'/subscribers?'.$this->buildQueryString($params)); + } + + /** + * get all user IDs subscribed to channelid + */ + public function getChannelSubscriptionsById($channelid) { + return $this->httpReq('get',$this->_baseUrl.'channel/'.$channelid.'/subscribers/ids'); + } + + + /** + * get a page of messages in channelid + */ + public function getMessages($channelid, $params = array()) { + return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'/messages?'.$this->buildQueryString($params)); + } + + /** + * create message + * @param $channelid numeric or "pm" for auto-chanenl (type=net.app.core.pm) + * @param $data array('text'=>'YOUR_MESSAGE') If a type=net.app.core.pm, then "destinations" key can be set to address as an array of people to send this PM too + */ + public function createMessage($channelid,$data) { + $json = json_encode($data); + return $this->httpReq('post',$this->_baseUrl.'channels/'.$channelid.'/messages', $json, 'application/json'); + } + + /** + * get message + */ + public function getMessage($channelid,$messageid) { + return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid); + } + + /** + * delete messsage + */ + public function deleteMessage($channelid,$messageid) { + return $this->httpReq('delete',$this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid); + } + + + /** + * Get Application Information + */ + public function getAppTokenInfo() { + // requires appAccessToken + if (!$this->_appAccessToken) { + $this->getAppAccessToken(); + } + // ensure request is made with our appAccessToken + $params['access_token']=$this->_appAccessToken; + return $this->httpReq('get',$this->_baseUrl.'token',$params); + } + + /** + * Get User Information + */ + public function getUserTokenInfo() { + return $this->httpReq('get',$this->_baseUrl.'token'); + } + + /** + * Get Application Authorized User IDs + */ + public function getAppUserIDs() { + // requires appAccessToken + if (!$this->_appAccessToken) { + $this->getAppAccessToken(); + } + // ensure request is made with our appAccessToken + $params['access_token']=$this->_appAccessToken; + return $this->httpReq('get',$this->_baseUrl.'apps/me/tokens/user_ids',$params); + } + + /** + * Get Application Authorized User Tokens + */ + public function getAppUserTokens() { + // requires appAccessToken + if (!$this->_appAccessToken) { + $this->getAppAccessToken(); + } + // ensure request is made with our appAccessToken + $params['access_token']=$this->_appAccessToken; + return $this->httpReq('get',$this->_baseUrl.'apps/me/tokens',$params); + } + + public function getLastRequest() { + return $this->_last_request; + } + public function getLastResponse() { + return $this->_last_response; + } + + /** + * Registers your function (or an array of object and method) to be called + * whenever an event is received via an open app.net stream. Your function + * will receive a single parameter, which is the object wrapper containing + * the meta and data. + * @param mixed A PHP callback (either a string containing the function name, + * or an array where the first element is the class/object and the second + * is the method). + */ + public function registerStreamFunction($function) { + $this->_streamCallback = $function; + } + + /** + * Opens a stream that's been created for this user/app and starts sending + * events/objects to your defined callback functions. You must define at + * least one callback function before opening a stream. + * @param mixed $stream Either a stream ID or the endpoint of a stream + * you've already created. This stream must exist and must be valid for + * your current access token. If you pass a stream ID, the library will + * make an API call to get the endpoint. + * + * This function will return immediately, but your callback functions + * will continue to receive events until you call closeStream() or until + * App.net terminates the stream from their end with an error. + * + * If you're disconnected due to a network error, the library will + * automatically attempt to reconnect you to the same stream, no action + * on your part is necessary for this. However if the app.net API returns + * an error, a reconnection attempt will not be made. + * + * Note there is no closeStream, because once you open a stream you + * can't stop it (unless you exit() or die() or throw an uncaught + * exception, or something else that terminates the script). + * @return boolean True + * @see createStream() + */ + public function openStream($stream) { + // if there's already a stream running, don't allow another + if ($this->_currentStream) { + throw new AppDotNetException('There is already a stream being consumed, only one stream can be consumed per AppDotNetStream instance'); + } + // must register a callback (or the exercise is pointless) + if (!$this->_streamCallback) { + throw new AppDotNetException('You must define your callback function using registerStreamFunction() before calling openStream'); + } + // if the stream is a numeric value, get the stream info from the api + if (is_numeric($stream)) { + $stream = $this->getStream($stream); + $this->_streamUrl = $stream['endpoint']; + } + else { + $this->_streamUrl = $stream; + } + // continue doing this until we get an error back or something...? + $this->httpStream('get',$this->_streamUrl); + + return true; + } + + /** + * Close the currently open stream. + * @return true; + */ + public function closeStream() { + if (!$this->_lastStreamActivity) { + // never opened + return; + } + if (!$this->_multiStream) { + throw new AppDotNetException('You must open a stream before calling closeStream()'); + } + curl_close($this->_currentStream); + curl_multi_remove_handle($this->_multiStream,$this->_currentStream); + curl_multi_close($this->_multiStream); + $this->_currentStream = null; + $this->_multiStream = null; + } + + /** + * Retrieve all streams for the current access token. + * @return array An array of stream definitions. + */ + public function getAllStreams() { + return $this->httpReq('get',$this->_baseUrl.'streams'); + } + + /** + * Returns a single stream specified by a stream ID. The stream must have been + * created with the current access token. + * @return array A stream definition + */ + public function getStream($streamId) { + return $this->httpReq('get',$this->_baseUrl.'streams/'.urlencode($streamId)); + } + + /** + * Creates a stream for the current app access token. + * + * @param array $objectTypes The objects you want to retrieve data for from the + * stream. At time of writing these can be 'post', 'star', and/or 'user_follow'. + * If you don't specify, all events will be retrieved. + */ + public function createStream($objectTypes=null) { + // default object types to everything + if (is_null($objectTypes)) { + $objectTypes = array('post','star','user_follow'); + } + $data = array( + 'object_types'=>$objectTypes, + 'type'=>'long_poll', + ); + $data = json_encode($data); + $response = $this->httpReq('post',$this->_baseUrl.'streams',$data,'application/json'); + return $response; + } + + /** + * Update stream for the current app access token + * + * @param integer $streamId The stream ID to update. This stream must have been + * created by the current access token. + * @param array $data allows object_types, type, filter_id and key to be updated. filter_id/key can be omitted + */ + public function updateStream($streamId,$data) { + // objectTypes is likely required + if (is_null($data['object_types'])) { + $data['object_types'] = array('post','star','user_follow'); + } + // type can still only be long_poll + if (is_null($data['type'])) { + $data['type']='long_poll'; + } + $data = json_encode($data); + $response = $this->httpReq('put',$this->_baseUrl.'streams/'.urlencode($streamId),$data,'application/json'); + return $response; + } + + /** + * Deletes a stream if you no longer need it. + * + * @param integer $streamId The stream ID to delete. This stream must have been + * created by the current access token. + */ + public function deleteStream($streamId) { + return $this->httpReq('delete',$this->_baseUrl.'streams/'.urlencode($streamId)); + } + + /** + * Deletes all streams created by the current access token. + */ + public function deleteAllStreams() { + return $this->httpReq('delete',$this->_baseUrl.'streams'); + } + + /** + * Internal function used to process incoming chunks from the stream. This is only + * public because it needs to be accessed by CURL. Do not call or use this function + * in your own code. + * @ignore + */ + public function httpStreamReceive($ch,$data) { + $this->_lastStreamActivity = time(); + $this->_streamBuffer .= $data; + if (!$this->_streamHeaders) { + $pos = strpos($this->_streamBuffer,"\r\n\r\n"); + if ($pos!==false) { + $this->_streamHeaders = substr($this->_streamBuffer,0,$pos); + $this->_streamBuffer = substr($this->_streamBuffer,$pos+4); + } + } + else { + $pos = strpos($this->_streamBuffer,"\r\n"); + while ($pos!==false) { + $command = substr($this->_streamBuffer,0,$pos); + $this->_streamBuffer = substr($this->_streamBuffer,$pos+2); + $command = json_decode($command,true); + if ($command) { + call_user_func($this->_streamCallback,$command); + } + $pos = strpos($this->_streamBuffer,"\r\n"); + } + } + return strlen($data); + } + + /** + * Opens a long lived HTTP connection to the app.net servers, and sends data + * received to the httpStreamReceive function. As a general rule you should not + * directly call this method, it's used by openStream(). + */ + protected function httpStream($act, $req, $params=array(),$contentType='application/x-www-form-urlencoded') { + if ($this->_currentStream) { + throw new AppDotNetException('There is already an open stream, you must close the existing one before opening a new one'); + } + $headers = array(); + $this->_streamBuffer = ''; + if ($this->_accessToken) { + $headers[] = 'Authorization: Bearer '.$this->_accessToken; + } + $this->_currentStream = curl_init($req); + curl_setopt($this->_currentStream, CURLOPT_HTTPHEADER, $headers); + curl_setopt($this->_currentStream, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->_currentStream, CURLINFO_HEADER_OUT, true); + curl_setopt($this->_currentStream, CURLOPT_HEADER, true); + if ($this->_sslCA) { + curl_setopt($this->_currentStream, CURLOPT_CAINFO, $this->_sslCA); + } + // every time we receive a chunk of data, forward it to httpStreamReceive + curl_setopt($this->_currentStream, CURLOPT_WRITEFUNCTION, array($this, "httpStreamReceive")); + + // curl_exec($ch); + // return; + + $this->_multiStream = curl_multi_init(); + $this->_lastStreamActivity = time(); + curl_multi_add_handle($this->_multiStream,$this->_currentStream); + } + + public function reconnectStream() { + $this->closeStream(); + $this->_connectFailCounter++; + // if we've failed a few times, back off + if ($this->_connectFailCounter>1) { + $sleepTime = pow(2,$this->_connectFailCounter); + // don't sleep more than 60 seconds + if ($sleepTime>60) { + $sleepTime = 60; + } + sleep($sleepTime); + } + $this->httpStream('get',$this->_streamUrl); + } + + /** + * Process an open stream for x microseconds, then return. This is useful if you want + * to be doing other things while processing the stream. If you just want to + * consume the stream without other actions, you can call processForever() instead. + * @param float @microseconds The number of microseconds to process for before + * returning. There are 1,000,000 microseconds in a second. + * + * @return void + */ + public function processStream($microseconds=null) { + if (!$this->_multiStream) { + throw new AppDotNetException('You must open a stream before calling processStream()'); + } + $start = microtime(true); + $active = null; + $inQueue = null; + $sleepFor = 0; + do { + // if we haven't received anything within 5.5 minutes, reconnect + // keepalives are sent every 5 minutes (measured on 2013-3-12 by @ryantharp) + if (time()-$this->_lastStreamActivity>=330) { + $this->reconnectStream(); + } + curl_multi_exec($this->_multiStream, $active); + if (!$active) { + $httpCode = curl_getinfo($this->_currentStream,CURLINFO_HTTP_CODE); + // don't reconnect on 400 errors + if ($httpCode>=400 && $httpCode<=499) { + throw new AppDotNetException('Received HTTP error '.$httpCode.' check your URL and credentials before reconnecting'); + } + $this->reconnectStream(); + } + // sleep for a max of 2/10 of a second + $timeSoFar = (microtime(true)-$start)*1000000; + $sleepFor = $this->streamingSleepFor; + if ($timeSoFar+$sleepFor>$microseconds) { + $sleepFor = $microseconds - $timeSoFar; + } + + if ($sleepFor>0) { + usleep($sleepFor); + } + } while ($timeSoFar+$sleepFor<$microseconds); + } + + /** + * Process an open stream forever. This function will never return, if you + * want to perform other actions while consuming the stream, you should use + * processFor() instead. + * @return void This function will never return + * @see processFor(); + */ + public function processStreamForever() { + while (true) { + $this->processStream(600); + } + } + + + /** + * Upload a file to a user's file store + * @param string $file A string containing the path of the file to upload. + * @param array $data Additional data about the file you're uploading. At the + * moment accepted keys are: mime-type, kind, type, name, public and annotations. + * - If you don't specify mime-type, ADNPHP will attempt to guess the mime type + * based on the file, however this isn't always reliable. + * - If you don't specify kind ADNPHP will attempt to determine if the file is + * an image or not. + * - If you don't specify name, ADNPHP will use the filename of the first + * parameter. + * - If you don't specify public, your file will be uploaded as a private file. + * - Type is REQUIRED. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations. + * @return array An associative array representing the file + */ + public function createFile($file, $data, $params=array()) { + if (!$file) { + throw new AppDotNetException('You must specify a path to a file'); + } + if (!file_exists($file)) { + throw new AppDotNetException('File path specified does not exist'); + } + if (!is_readable($file)) { + throw new AppDotNetException('File path specified is not readable'); + } + + if (!$data) { + $data = array(); + } + + if (!array_key_exists('type',$data) || !$data['type']) { + throw new AppDotNetException('Type is required when creating a file'); + } + + if (!array_key_exists('name',$data)) { + $data['name'] = basename($file); + } + + if (array_key_exists('mime-type',$data)) { + $mimeType = $data['mime-type']; + unset($data['mime-type']); + } + else { + $mimeType = null; + } + if (!array_key_exists('kind',$data)) { + $test = @getimagesize($path); + if ($test && array_key_exists('mime',$test)) { + $data['kind'] = 'image'; + if (!$mimeType) { + $mimeType = $test['mime']; + } + } + else { + $data['kind'] = 'other'; + } + } + if (!$mimeType) { + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $mimeType = finfo_file($finfo, $file); + finfo_close($finfo); + } + if (!$mimeType) { + throw new AppDotNetException('Unable to determine mime type of file, try specifying it explicitly'); + } + if (!array_key_exists('public',$data) || !$data['public']) { + $public = false; + } + else { + $public = true; + } + + $data['content'] = "@$file;type=$mimeType"; + return $this->httpReq('post-raw',$this->_baseUrl.'files', $data, 'multipart/form-data'); + } + + + public function createFilePlaceholder($file = null, $params=array()) { + $name = basename($file); + $data = array('annotations' => $params['annotations'], 'kind' => $params['kind'], + 'name' => $name, 'type' => $params['metadata']); + $json = json_encode($data); + return $this->httpReq('post',$this->_baseUrl.'files', $json, 'application/json'); + } + + public function updateFileContent($fileid, $file) { + + $data = file_get_contents($file); + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $mime = finfo_file($finfo, $file); + finfo_close($finfo); + + return $this->httpReq('put',$this->_baseUrl.'files/' . $fileid + .'/content', $data, $mime); + } + + /** + * Allows for file rename and annotation changes. + * @param integer $file_id The ID of the file to update + * @param array $params An associative array of file parameters. + * @return array An associative array representing the updated file + */ + public function updateFile($file_id=null, $params=array()) { + $data = array('annotations' => $params['annotations'] , 'name' => $params['name']); + $json = json_encode($data); + return $this->httpReq('put',$this->_baseUrl.'files/'.urlencode($file_id), $json, 'application/json'); + } + + /** + * Returns a specific File. + * @param integer $file_id The ID of the file to retrieve + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations. + * @return array An associative array representing the file + */ + public function getFile($file_id=null,$params = array()) { + return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id) + .'?'.$this->buildQueryString($params)); + } + + public function getFileContent($file_id=null,$params = array()) { + return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id) + .'/content?'.$this->buildQueryString($params)); + } + + /** $file_key : derived_file_key */ + public function getDerivedFileContent($file_id=null,$file_key=null,$params = array()) { + return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id) + .'/content/'.urlencode($file_key) + .'?'.$this->buildQueryString($params)); + } + + /** + * Returns file objects. + * @param array $file_ids The IDs of the files to retrieve + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations. + * @return array An associative array representing the file data. + */ + public function getFiles($file_ids=array(), $params = array()) { + $ids = ''; + foreach($file_ids as $id) { + $ids .= $id . ','; + } + $params['ids'] = substr($ids, 0, -1); + return $this->httpReq('get',$this->_baseUrl.'files' + .'?'.$this->buildQueryString($params)); + } + + /** + * Returns a user's file objects. + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations|include_user_annotations. + * @return array An associative array representing the file data. + */ + public function getUserFiles($params = array()) { + return $this->httpReq('get',$this->_baseUrl.'users/me/files' + .'?'.$this->buildQueryString($params)); + } + + /** + * Delete a File. The current user must be the same user who created the File. + * It returns the deleted File on success. + * @param integer $file_id The ID of the file to delete + * @return array An associative array representing the file that was deleted + */ + public function deleteFile($file_id=null) { + return $this->httpReq('delete',$this->_baseUrl.'files/'.urlencode($file_id)); + } + +} + +class AppDotNetException extends Exception {} diff --git a/appnet/DigiCertHighAssuranceEVRootCA.pem b/appnet/DigiCertHighAssuranceEVRootCA.pem new file mode 100644 index 00000000..9e6810ab --- /dev/null +++ b/appnet/DigiCertHighAssuranceEVRootCA.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs +MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j +ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL +MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3 +LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug +RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm ++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW +PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM +xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB +Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3 +hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg +EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF +MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA +FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec +nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z +eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF +hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2 +Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep ++OkuE6N36B9K +-----END CERTIFICATE----- diff --git a/appnet/README.md b/appnet/README.md new file mode 100644 index 00000000..ec24753c --- /dev/null +++ b/appnet/README.md @@ -0,0 +1,15 @@ +App.net Plugin +============== + +With this addon to friendica you can give your users the possibility to post their *public* messages to App.net and +to import their timeline. The messages will be strapped their rich context and shortened to 256 characters length if +necessary. + +Installation +------------ + +If you have an developer account you can create an Application for all of your users at +[https://account.app.net/developer/apps/](https://account.app.net/developer/apps/). Add the redirect uri +"https://your.server.name/appnet/connect" (Replace "your.server.name" with the hostname of your server) + +If you can't create an application (because you only have a free account) this addon still works, but your users have to create individual applications on their own. diff --git a/appnet/appnet.css b/appnet/appnet.css new file mode 100644 index 00000000..b1d8d27e --- /dev/null +++ b/appnet/appnet.css @@ -0,0 +1,29 @@ +#appnet-import-label, #appnet-disconnect-label, #appnet-token-label, +#appnet-enable-label, #appnet-bydefault-label, +#appnet-clientid-label, #appnet-clientsecret-label { + float: left; + width: 200px; + margin-top: 10px; +} + +#appnet-import, #appnet-disconnect, #appnet-token, +#appnet-checkbox, #appnet-bydefault, +#appnet-clientid, #appnet-clientsecret { + float: left; + margin-top: 10px; +} + +#appnet-submit { + margin-top: 15px; +} + +#appnet-avatar { + float: left; + width: 48px; + height: 48px; + padding: 2px; +} +#appnet-info-block { + height: 52px; + vertical-align: middle; +} diff --git a/appnet/appnet.php b/appnet/appnet.php new file mode 100644 index 00000000..151a81ee --- /dev/null +++ b/appnet/appnet.php @@ -0,0 +1,1358 @@ + + * Status: Unsupported + */ + +/* + To-Do: + - Use embedded pictures for the attachment information (large attachment) + - Sound links must be handled + - https://alpha.app.net/sr_rolando/post/32365203 - double pictures + - https://alpha.app.net/opendev/post/34396399 - location data +*/ + +require_once('include/enotify.php'); +require_once("include/socgraph.php"); + +define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes + +function appnet_install() { + register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local'); + register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send'); + register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets'); + register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron'); + register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings'); + register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post'); + register_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body'); + register_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification'); +} + + +function appnet_uninstall() { + unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local'); + unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send'); + unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets'); + unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron'); + unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings'); + unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post'); + unregister_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body'); + unregister_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification'); +} + +function appnet_module() {} + +function appnet_content(&$a) { + if(! local_user()) { + notice( t('Permission denied.') . EOL); + return ''; + } + + require_once("mod/settings.php"); + settings_init($a); + + if (isset($a->argv[1])) + switch ($a->argv[1]) { + case "connect": + $o = appnet_connect($a); + break; + default: + $o = print_r($a->argv, true); + break; + } + else + $o = appnet_connect($a); + + return $o; +} + +function appnet_check_item_notification($a, &$notification_data) { + $own_id = get_pconfig($notification_data["uid"], 'appnet', 'ownid'); + + $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", + intval($notification_data["uid"]), + dbesc("adn::".$own_id) + ); + + if ($own_user) + $notification_data["profiles"][] = $own_user[0]["url"]; +} + +function appnet_plugin_admin(&$a, &$o){ + $t = get_markup_template( "admin.tpl", "addon/appnet/" ); + + $o = replace_macros($t, array( + '$submit' => t('Save Settings'), + // name, label, value, help, [extra values] + '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid' ), ''), + '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret' ), ''), + )); +} + +function appnet_plugin_admin_post(&$a){ + $clientid = ((x($_POST,'clientid')) ? notags(trim($_POST['clientid'])) : ''); + $clientsecret = ((x($_POST,'clientsecret')) ? notags(trim($_POST['clientsecret'])): ''); + set_config('appnet','clientid',$clientid); + set_config('appnet','clientsecret',$clientsecret); + info( t('Settings updated.'). EOL ); +} + +function appnet_connect(&$a) { + require_once 'addon/appnet/AppDotNet.php'; + + $clientId = get_config('appnet','clientid'); + $clientSecret = get_config('appnet','clientsecret'); + + if (($clientId == "") || ($clientSecret == "")) { + $clientId = get_pconfig(local_user(),'appnet','clientid'); + $clientSecret = get_pconfig(local_user(),'appnet','clientsecret'); + } + + $app = new AppDotNet($clientId, $clientSecret); + + try { + $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect'); + + logger("appnet_connect: authenticated"); + $o .= t("You are now authenticated to app.net. "); + set_pconfig(local_user(),'appnet','token', $token); + } + catch (AppDotNetException $e) { + $o .= t("

Error fetching token. Please try again.

"); + } + + $o .= '
'.t("return to the connector page").''; + + return($o); +} + +function appnet_jot_nets(&$a,&$b) { + if(! local_user()) + return; + + $post = get_pconfig(local_user(),'appnet','post'); + if(intval($post) == 1) { + $defpost = get_pconfig(local_user(),'appnet','post_by_default'); + $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : ''); + $b .= '
' + . t('Post to app.net') . '
'; + } +} + +function appnet_settings(&$a,&$s) { + require_once 'addon/appnet/AppDotNet.php'; + + if(! local_user()) + return; + + $token = get_pconfig(local_user(),'appnet','token'); + + $app_clientId = get_config('appnet','clientid'); + $app_clientSecret = get_config('appnet','clientsecret'); + + if (($app_clientId == "") || ($app_clientSecret == "")) { + $app_clientId = get_pconfig(local_user(),'appnet','clientid'); + $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret'); + } + + /* Add our stylesheet to the page so we can make our settings look nice */ + $a->page['htmlhead'] .= '' . "\r\n"; + + $enabled = get_pconfig(local_user(),'appnet','post'); + $checked = (($enabled) ? ' checked="checked" ' : ''); + + $css = (($enabled) ? '' : '-disabled'); + + $def_enabled = get_pconfig(local_user(),'appnet','post_by_default'); + $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); + + $importenabled = get_pconfig(local_user(),'appnet','import'); + $importchecked = (($importenabled) ? ' checked="checked" ' : ''); + + $ownid = get_pconfig(local_user(),'appnet','ownid'); + + $s .= ''; + $s .= '

'. t('App.net Import/Export').'

'; + $s .= '
'; + $s .= ''; +} + +function appnet_settings_post(&$a,&$b) { + + if(x($_POST,'appnet-submit')) { + + if (isset($_POST['appnet-disconnect'])) { + del_pconfig(local_user(), 'appnet', 'clientsecret'); + del_pconfig(local_user(), 'appnet', 'clientid'); + del_pconfig(local_user(), 'appnet', 'token'); + del_pconfig(local_user(), 'appnet', 'post'); + del_pconfig(local_user(), 'appnet', 'post_by_default'); + del_pconfig(local_user(), 'appnet', 'import'); + } + + if (isset($_POST["clientsecret"])) + set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']); + + if (isset($_POST["clientid"])) + set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']); + + if (isset($_POST["token"]) && ($_POST["token"] != "")) + set_pconfig(local_user(),'appnet','token', $_POST['token']); + + set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet'])); + set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault'])); + set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import'])); + } +} + +function appnet_post_local(&$a,&$b) { + if($b['edit']) + return; + + if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) { + $appnet_post = intval(get_pconfig(local_user(),'appnet','post')); + $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0); + + // if API is used, default to the chosen settings + if($b['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default'))) + $appnet_enable = 1; + + if(! $appnet_enable) + return; + + if(strlen($b['postopts'])) + $b['postopts'] .= ','; + + $b['postopts'] .= 'appnet'; + } +} + +function appnet_create_entities($a, $b, $postdata) { + require_once("include/bbcode.php"); + require_once("include/plaintext.php"); + + $bbcode = $b["body"]; + $bbcode = bb_remove_share_information($bbcode, false, true); + + // Change pure links in text to bbcode uris + $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode); + + $URLSearchString = "^\[\]"; + + $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode); + $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode); + $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode); + $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode); + $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode); + $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", + '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode); + $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode); + $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", + '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode); + //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode); + + $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode); + + + preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER); + + $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode); + + $b["body"] = $bbcode; + + // To-Do: + // Bilder + // https://alpha.app.net/heluecht/post/32424376 + // https://alpha.app.net/heluecht/post/32424307 + + $plaintext = plaintext($a, $b, 0, false, 6); + + $text = $plaintext["text"]; + + $start = 0; + $entities = array(); + + foreach ($urls AS $url) { + $lenurl = iconv_strlen($url[1], "UTF-8"); + $len = iconv_strlen($url[2], "UTF-8"); + $pos = iconv_strpos($text, $url[1], $start, "UTF-8"); + $pre = iconv_substr($text, 0, $pos, "UTF-8"); + $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8"); + + $mid = $url[2]; + $html = bbcode($mid, false, false, 6); + $mid = html2plain($html, 0, true); + + $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8')); + + $text = $pre.$mid.$post; + + if ($mid != "") + $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid); + + $start = $pos + 1; + } + + if (isset($postdata["url"]) && isset($postdata["title"]) && ($postdata["type"] != "photo")) { + $postdata["title"] = shortenmsg($postdata["title"], 90); + $max = 256 - strlen($postdata["title"]); + $text = shortenmsg($text, $max); + $text .= "\n[".$postdata["title"]."](".$postdata["url"].")"; + } elseif (isset($postdata["url"]) && ($postdata["type"] != "photo")) { + $postdata["url"] = short_link($postdata["url"]); + $max = 240; + $text = shortenmsg($text, $max); + $text .= " [".$postdata["url"]."](".$postdata["url"].")"; + } else { + $max = 256; + $text = shortenmsg($text, $max); + } + + if (iconv_strlen($text, "UTF-8") < $max) + $max = iconv_strlen($text, "UTF-8"); + + krsort($entities); + foreach ($entities AS $entity) { + //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) { + if (($entity["pos"] + $entity["len"]) <= $max) { + $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8"); + $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8"); + + $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post; + } + } + + + return($text); +} + +function appnet_send(&$a,&$b) { + + logger('appnet_send: invoked for post '.$b['id']." ".$b['app']); + + if (!get_pconfig($b["uid"],'appnet','import')) { + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) + return; + } + + if($b['parent'] != $b['id']) { + logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA); + + // Looking if its a reply to an app.net post + if ((substr($b["parent-uri"], 0, 5) != "adn::") && (substr($b["extid"], 0, 5) != "adn::") && (substr($b["thr-parent"], 0, 5) != "adn::")) { + logger("appnet_send: no app.net post ".$b["parent"]); + return; + } + + $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", + dbesc($b["thr-parent"]), + intval($b["uid"])); + + if(!count($r)) { + logger("appnet_send: no parent found ".$b["thr-parent"]); + return; + } else { + $iscomment = true; + $orig_post = $r[0]; + } + + $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]); + $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]"; + $nicknameplain = "@".$nicknameplain; + + logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG); + if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) + $b["body"] = $nickname." ".$b["body"]; + + logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA); + } else { + $iscomment = false; + + if($b['private'] || !strstr($b['postopts'],'appnet')) + return; + } + + if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) + appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete"); + + if($b['verb'] == ACTIVITY_LIKE) { + logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG); + logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG); + if ($b['deleted']) + appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike"); + else + appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like"); + return; + } + + if($b['deleted'] || ($b['created'] !== $b['edited'])) + return; + + $token = get_pconfig($b['uid'],'appnet','token'); + + if($token) { + + // If it's a repeated message from app.net then do a native repost and exit + if (appnet_is_repost($a, $b['uid'], $b['body'])) + return; + + + require_once 'addon/appnet/AppDotNet.php'; + + $clientId = get_pconfig($b["uid"],'appnet','clientid'); + $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + $data = array(); + + require_once("include/plaintext.php"); + require_once("include/network.php"); + + $post = plaintext($a, $b, 256, false, 6); + logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG); + + if (isset($post["image"])) { + $img_str = fetch_url($post['image'],true, $redirects, 10); + $tempfile = tempnam(get_temppath(), "cache"); + file_put_contents($tempfile, $img_str); + + try { + $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo")); + + $data["annotations"][] = array( + "type" => "net.app.core.oembed", + "value" => array( + "+net.app.core.file" => array( + "file_id" => $photoFile["id"], + "file_token" => $photoFile["file_token"], + "format" => "oembed") + ) + ); + } + catch (AppDotNetException $e) { + logger("appnet_send: Error creating file ".appnet_error($e->getMessage())); + } + + unlink($tempfile); + } + + // Adding a link to the original post, if it is a root post + if($b['parent'] == $b['id']) + $data["annotations"][] = array( + "type" => "net.app.core.crosspost", + "value" => array("canonical_url" => $b["plink"]) + ); + + // Adding the original post + $attached_data = get_attached_data($b["body"]); + $attached_data["post-uri"] = $b["uri"]; + $attached_data["post-title"] = $b["title"]; + $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening + $attached_data["post-tag"] = $b["tag"]; + $attached_data["author-name"] = $b["author-name"]; + $attached_data["author-link"] = $b["author-link"]; + $attached_data["author-avatar"] = $b["author-avatar"]; + + $data["annotations"][] = array( + "type" => "com.friendica.post", + "value" => $attached_data + ); + + if (isset($post["url"]) && !isset($post["title"]) && ($post["type"] != "photo")) { + $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]); + $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url); + + if (strlen($display_url) > 26) + $display_url = substr($display_url, 0, 25)."…"; + + $post["title"] = $display_url; + } + + $text = appnet_create_entities($a, $b, $post); + + $data["entities"]["parse_markdown_links"] = true; + + if ($iscomment) + $data["reply_to"] = substr($orig_post["uri"], 5); + + try { + logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG); + $ret = $app->createPost($text, $data); + logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG); + if ($iscomment) { + logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']); + q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d", + dbesc("adn::".$ret["id"]), + intval($b['id']) + ); + } + } + catch (AppDotNetException $e) { + logger("appnet_send: Error sending message ".$b["id"]." ".appnet_error($e->getMessage())); + } + } +} + +function appnet_action($a, $uid, $pid, $action) { + require_once 'addon/appnet/AppDotNet.php'; + + $token = get_pconfig($uid,'appnet','token'); + $clientId = get_pconfig($uid,'appnet','clientid'); + $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA); + + try { + switch ($action) { + case "delete": + $result = $app->deletePost($pid); + break; + case "like": + $result = $app->starPost($pid); + break; + case "unlike": + $result = $app->unstarPost($pid); + break; + } + logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG); + } + catch (AppDotNetException $e) { + logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG); + } +} + +function appnet_is_repost($a, $uid, $body) { + $body = trim($body); + + // Skip if it isn't a pure repeated messages + // Does it start with a share? + if (strpos($body, "[share") > 0) + return(false); + + // Does it end with a share? + if (strlen($body) > (strrpos($body, "[/share]") + 8)) + return(false); + + $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body); + // Skip if there is no shared message in there + if ($body == $attributes) + return(false); + + $link = ""; + preg_match("/link='(.*?)'/ism", $attributes, $matches); + if ($matches[1] != "") + $link = $matches[1]; + + preg_match('/link="(.*?)"/ism', $attributes, $matches); + if ($matches[1] != "") + $link = $matches[1]; + + $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link); + if ($id == $link) + return(false); + + logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG); + + require_once 'addon/appnet/AppDotNet.php'; + + $token = get_pconfig($uid,'appnet','token'); + $clientId = get_pconfig($uid,'appnet','clientid'); + $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + try { + $result = $app->repost($id); + logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG); + return true; + } + catch (AppDotNetException $e) { + logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG); + return false; + } +} + +function appnet_fetchstream($a, $uid) { + require_once("addon/appnet/AppDotNet.php"); + require_once('include/items.php'); + + $token = get_pconfig($uid,'appnet','token'); + $clientId = get_pconfig($uid,'appnet','clientid'); + $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", + intval($uid)); + + if(count($r)) + $me = $r[0]; + else { + logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG); + return; + } + + $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1", + intval($uid) + ); + + if(count($user)) + $user = $user[0]; + else { + logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG); + return; + } + + $ownid = get_pconfig($uid,'appnet','ownid'); + + // Fetch stream + $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, + "include_html" => false, "include_post_annotations" => true); + + $lastid = get_pconfig($uid, 'appnet', 'laststreamid'); + + if ($lastid <> "") + $param["since_id"] = $lastid; + + try { + $stream = $app->getUserStream($param); + } + catch (AppDotNetException $e) { + logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage())); + return; + } + + if (!is_array($stream)) + $stream = array(); + + $stream = array_reverse($stream); + foreach ($stream AS $post) { + $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true); + + $item = item_store($postarray); + $postarray["id"] = $item; + + logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item); + + $lastid = $post["id"]; + + if (($item != 0) && ($postarray['contact-id'] != $me["id"]) && !function_exists("check_item_notification")) { + $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread` + INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid` + WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item)); + + if (count($r)) { + require_once('include/enotify.php'); + notification(array( + 'type' => NOTIFY_COMMENT, + 'notify_flags' => $user['notify-flags'], + 'language' => $user['language'], + 'to_name' => $user['username'], + 'to_email' => $user['email'], + 'uid' => $user['uid'], + 'item' => $postarray, + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), + 'source_name' => $postarray['author-name'], + 'source_link' => $postarray['author-link'], + 'source_photo' => $postarray['author-avatar'], + 'verb' => ACTIVITY_POST, + 'otype' => 'item', + 'parent' => $r[0]["parent"], + )); + } + } + } + + set_pconfig($uid, 'appnet', 'laststreamid', $lastid); + + // Fetch mentions + $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, + "include_html" => false, "include_post_annotations" => true); + + $lastid = get_pconfig($uid, 'appnet', 'lastmentionid'); + + if ($lastid <> "") + $param["since_id"] = $lastid; + + try { + $mentions = $app->getUserMentions("me", $param); + } + catch (AppDotNetException $e) { + logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage())); + return; + } + + if (!is_array($mentions)) + $mentions = array(); + + $mentions = array_reverse($mentions); + foreach ($mentions AS $post) { + $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false); + + if (isset($postarray["id"])) { + $item = $postarray["id"]; + $parent_id = $postarray['parent']; + } elseif (isset($postarray["body"])) { + $item = item_store($postarray); + $postarray["id"] = $item; + + $parent_id = 0; + logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item); + + if ($item && function_exists("check_item_notification")) + check_item_notification($item, $uid, NOTIFY_TAGSELF); + + } else { + $item = 0; + $parent_id = 0; + } + + // Fetch the parent and id + if (($parent_id == 0) && ($postarray['uri'] != "")) { + $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", + dbesc($postarray['uri']), + intval($uid) + ); + + if (count($r)) { + $item = $r[0]['id']; + $parent_id = $r[0]['parent']; + } + } + + $lastid = $post["id"]; + + //if (($item != 0) && ($postarray['contact-id'] != $me["id"])) { + if (($item != 0) && !function_exists("check_item_notification")) { + require_once('include/enotify.php'); + notification(array( + 'type' => NOTIFY_TAGSELF, + 'notify_flags' => $user['notify-flags'], + 'language' => $user['language'], + 'to_name' => $user['username'], + 'to_email' => $user['email'], + 'uid' => $user['uid'], + 'item' => $postarray, + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), + 'source_name' => $postarray['author-name'], + 'source_link' => $postarray['author-link'], + 'source_photo' => $postarray['author-avatar'], + 'verb' => ACTIVITY_TAG, + 'otype' => 'item', + 'parent' => $parent_id, + )); + } + } + + set_pconfig($uid, 'appnet', 'lastmentionid', $lastid); + + +/* To-Do + $param = array("interaction_actions" => "star"); + $interactions = $app->getMyInteractions($param); + foreach ($interactions AS $interaction) + appnet_dolike($a, $uid, $interaction); +*/ +} + +function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) { + require_once('include/items.php'); + + if ($post["machine_only"]) + return; + + if ($post["is_deleted"]) + return; + + $postarray = array(); + $postarray['gravity'] = 0; + $postarray['uid'] = $uid; + $postarray['wall'] = 0; + $postarray['verb'] = ACTIVITY_POST; + $postarray['network'] = dbesc(NETWORK_APPNET); + if (is_array($post["repost_of"])) { + // You can't reply to reposts. So use the original id and thread-id + $postarray['uri'] = "adn::".$post["repost_of"]["id"]; + $postarray['parent-uri'] = "adn::".$post["repost_of"]["thread_id"]; + } else { + $postarray['uri'] = "adn::".$post["id"]; + $postarray['parent-uri'] = "adn::".$post["thread_id"]; + } + + if (!$nodupcheck) { + $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", + dbesc($postarray['uri']), + intval($uid) + ); + + if (count($r)) + return($r[0]); + + $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", + dbesc($postarray['uri']), + intval($uid) + ); + + if (count($r)) + return($r[0]); + } + + if (isset($post["reply_to"]) && ($post["reply_to"] != "")) { + $postarray['thr-parent'] = "adn::".$post["reply_to"]; + + // Complete the thread (if the parent doesn't exists) + if ($threadcompletion) { + //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", + // dbesc($postarray['thr-parent']), + // intval($uid) + // ); + //if (!count($r)) { + logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG); + + require_once("addon/appnet/AppDotNet.php"); + + $token = get_pconfig($uid,'appnet','token'); + $clientId = get_pconfig($uid,'appnet','clientid'); + $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, + "include_html" => false, "include_post_annotations" => true); + try { + $thread = $app->getPostReplies($post["thread_id"], $param); + } + catch (AppDotNetException $e) { + logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage())); + } + $thread = array_reverse($thread); + + logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG); + + foreach ($thread AS $tpost) { + $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false); + $item = item_store($threadpost); + $threadpost["id"] = $item; + + logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG); + } + //} + } + // Don't create accounts of people who just comment something + $createuser = false; + + $postarray['object-type'] = ACTIVITY_OBJ_COMMENT; + } else { + $postarray['thr-parent'] = $postarray['uri']; + $postarray['object-type'] = ACTIVITY_OBJ_NOTE; + } + + if (($post["user"]["id"] != $ownid) || ($postarray['thr-parent'] == $postarray['uri'])) { + $postarray['owner-name'] = $post["user"]["name"]; + $postarray['owner-link'] = $post["user"]["canonical_url"]; + $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"]; + $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser); + } else { + $postarray['owner-name'] = $me["name"]; + $postarray['owner-link'] = $me["url"]; + $postarray['owner-avatar'] = $me["thumb"]; + $postarray['contact-id'] = $me["id"]; + } + + $links = array(); + + if (is_array($post["repost_of"])) { + $postarray['author-name'] = $post["repost_of"]["user"]["name"]; + $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"]; + $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"]; + + $content = $post["repost_of"]; + } else { + $postarray['author-name'] = $postarray['owner-name']; + $postarray['author-link'] = $postarray['owner-link']; + $postarray['author-avatar'] = $postarray['owner-avatar']; + + $content = $post; + } + + $postarray['plink'] = $content["canonical_url"]; + + if (is_array($content["entities"])) { + $converted = appnet_expand_entities($a, $content["text"], $content["entities"]); + $postarray['body'] = $converted["body"]; + $postarray['tag'] = $converted["tags"]; + } else + $postarray['body'] = $content["text"]; + + if (sizeof($content["entities"]["links"])) + foreach($content["entities"]["links"] AS $link) { + $url = normalise_link($link["url"]); + $links[$url] = $link["url"]; + } + + /* if (sizeof($content["annotations"])) + foreach($content["annotations"] AS $annotation) { + if ($annotation[type] == "net.app.core.oembed") { + if (isset($annotation["value"]["embeddable_url"])) { + $url = normalise_link($annotation["value"]["embeddable_url"]); + if (isset($links[$url])) + unset($links[$url]); + } + } elseif ($annotation[type] == "com.friendica.post") { + //$links = array(); + //if (isset($annotation["value"]["post-title"])) + // $postarray['title'] = $annotation["value"]["post-title"]; + + //if (isset($annotation["value"]["post-body"])) + // $postarray['body'] = $annotation["value"]["post-body"]; + + //if (isset($annotation["value"]["post-tag"])) + // $postarray['tag'] = $annotation["value"]["post-tag"]; + + if (isset($annotation["value"]["author-name"])) + $postarray['author-name'] = $annotation["value"]["author-name"]; + + if (isset($annotation["value"]["author-link"])) + $postarray['author-link'] = $annotation["value"]["author-link"]; + + if (isset($annotation["value"]["author-avatar"])) + $postarray['author-avatar'] = $annotation["value"]["author-avatar"]; + } + + } */ + + $page_info = ""; + + if (is_array($content["annotations"])) { + $photo = appnet_expand_annotations($a, $content["annotations"]); + if (($photo["large"] != "") && ($photo["url"] != "")) + $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]"; + elseif ($photo["url"] != "") + $page_info = "\n[img]".$photo["url"]."[/img]"; + + if ($photo["url"] != "") + $postarray['object-type'] = ACTIVITY_OBJ_IMAGE; + + } else + $photo = array("url" => "", "large" => ""); + + if (sizeof($links)) { + $link = array_pop($links); + $url = str_replace(array('/', '.'), array('\/', '\.'), $link); + + $page_info = add_page_info($link, false, $photo["url"]); + + if (trim($page_info) != "") { + $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']); + if (($removedlink == "") || strstr($postarray['body'], $removedlink)) + $postarray['body'] = $removedlink; + } + } + + $postarray['body'] .= $page_info; + + $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]); + $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]); + + $postarray['app'] = $post["source"]["name"]; + + return($postarray); +} + +function appnet_expand_entities($a, $body, $entities) { + + if (!function_exists('substr_unicode')) { + function substr_unicode($str, $s, $l = null) { + return join("", array_slice( + preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l)); + } + } + + $tags_arr = array(); + $replace = array(); + + foreach ($entities["mentions"] AS $mention) { + $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]"; + $tags_arr["@".$mention["name"]] = $url; + $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url); + } + + foreach ($entities["hashtags"] AS $hashtag) { + $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]"; + $tags_arr["#".$hashtag["name"]] = $url; + $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url); + } + + foreach ($entities["links"] AS $links) { + $url = "[url=".$links["url"]."]".$links["text"]."[/url]"; + if (isset($links["amended_len"]) && ($links["amended_len"] > $links["len"])) + $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url); + else + $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url); + } + + + if (sizeof($replace)) { + krsort($replace); + foreach ($replace AS $entity) { + $pre = substr_unicode($body, 0, $entity["pos"]); + $post = substr_unicode($body, $entity["pos"] + $entity["len"]); + //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8"); + //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8"); + + $body = $pre.$entity["replace"].$post; + } + } + + return(array("body" => $body, "tags" => implode($tags_arr, ","))); +} + +function appnet_expand_annotations($a, $annotations) { + $photo = array("url" => "", "large" => ""); + foreach ($annotations AS $annotation) { + if (($annotation[type] == "net.app.core.oembed") && + ($annotation["value"]["type"] == "photo")) { + if ($annotation["value"]["url"] != "") + $photo["url"] = $annotation["value"]["url"]; + + if ($annotation["value"]["thumbnail_large_url"] != "") + $photo["large"] = $annotation["value"]["thumbnail_large_url"]; + + //if (($annotation["value"]["thumbnail_large_url"] != "") && ($annotation["value"]["url"] != "")) + // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]"; + //elseif ($annotation["value"]["url"] != "") + // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]"; + } + } + return $photo; +} + +function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) { + + update_gcontact(array("url" => $contact["canonical_url"], "generation" => 2, + "network" => NETWORK_APPNET, "photo" => $contact["avatar_image"]["url"], + "name" => $contact["name"], "nick" => $contact["username"], + "about" => $contact["description"]["text"], "hide" => true, + "addr" => $contact["username"]."@app.net")); + + $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", + intval($uid), dbesc("adn::".$contact["id"])); + + if(!count($r) && !$create_user) + return($me["id"]); + + if ($contact["canonical_url"] == "") + return($me["id"]); + + if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) { + logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG); + return(-1); + } + + if(!count($r)) { + + if ($contact["name"] == "") + $contact["name"] = $contact["username"]; + + if ($contact["username"] == "") + $contact["username"] = $contact["name"]; + + // create contact record + q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`, + `name`, `nick`, `photo`, `network`, `rel`, `priority`, + `about`, `writable`, `blocked`, `readonly`, `pending` ) + VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, 0, 0, 0 ) ", + intval($uid), + dbesc(datetime_convert()), + dbesc($contact["canonical_url"]), + dbesc(normalise_link($contact["canonical_url"])), + dbesc($contact["username"]."@app.net"), + dbesc("adn::".$contact["id"]), + dbesc(''), + dbesc("adn::".$contact["id"]), + dbesc($contact["name"]), + dbesc($contact["username"]), + dbesc($contact["avatar_image"]["url"]), + dbesc(NETWORK_APPNET), + intval(CONTACT_IS_FRIEND), + intval(1), + dbesc($contact["description"]["text"]), + intval(1) + ); + + $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1", + dbesc("adn::".$contact["id"]), + intval($uid) + ); + + if(! count($r)) + return(false); + + $contact_id = $r[0]['id']; + + $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1", + intval($uid) + ); + + if($g && intval($g[0]['def_gid'])) { + require_once('include/group.php'); + group_add_member($uid,'',$contact_id,$g[0]['def_gid']); + } + + require_once("Photo.php"); + + $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id); + + q("UPDATE `contact` SET `photo` = '%s', + `thumb` = '%s', + `micro` = '%s', + `name-date` = '%s', + `uri-date` = '%s', + `avatar-date` = '%s' + WHERE `id` = %d", + dbesc($photos[0]), + dbesc($photos[1]), + dbesc($photos[2]), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + intval($contact_id) + ); + } else { + // update profile photos once every two weeks as we have no notification of when they change. + + //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false); + $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours')); + + // check that we have all the photos, this has been known to fail on occasion + + if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) { + + logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG); + + require_once("Photo.php"); + + $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']); + + q("UPDATE `contact` SET `photo` = '%s', + `thumb` = '%s', + `micro` = '%s', + `name-date` = '%s', + `uri-date` = '%s', + `avatar-date` = '%s', + `url` = '%s', + `nurl` = '%s', + `addr` = '%s', + `name` = '%s', + `nick` = '%s', + `about` = '%s' + WHERE `id` = %d", + dbesc($photos[0]), + dbesc($photos[1]), + dbesc($photos[2]), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc($contact["canonical_url"]), + dbesc(normalise_link($contact["canonical_url"])), + dbesc($contact["username"]."@app.net"), + dbesc($contact["name"]), + dbesc($contact["username"]), + dbesc($contact["description"]["text"]), + intval($r[0]['id']) + ); + } + } + + return($r[0]["id"]); +} + +function appnet_prepare_body(&$a,&$b) { + if ($b["item"]["network"] != NETWORK_APPNET) + return; + + if ($b["preview"]) { + $max_char = 256; + require_once("include/plaintext.php"); + $item = $b["item"]; + $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"]; + + $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", + dbesc($item["thr-parent"]), + intval(local_user())); + + if(count($r)) { + $orig_post = $r[0]; + + $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]); + $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]"; + $nicknameplain = "@".$nicknameplain; + + if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) + $item["body"] = $nickname." ".$item["body"]; + } + + + + $msgarr = plaintext($a, $item, $max_char, true); + $msg = appnet_create_entities($a, $item, $msgarr); + + require_once("library/markdown.php"); + $msg = Markdown($msg); + + $b['html'] = $msg; + } +} + +function appnet_cron($a,$b) { + $last = get_config('appnet','last_poll'); + + $poll_interval = intval(get_config('appnet','poll_interval')); + if(! $poll_interval) + $poll_interval = APPNET_DEFAULT_POLL_INTERVAL; + + if($last) { + $next = $last + ($poll_interval * 60); + if($next > time()) { + logger('appnet_cron: poll intervall not reached'); + return; + } + } + logger('appnet_cron: cron_start'); + + $abandon_days = intval(get_config('system','account_abandon_days')); + if ($abandon_days < 1) + $abandon_days = 0; + + $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400); + + $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()"); + if(count($r)) { + foreach($r as $rr) { + if ($abandon_days != 0) { + $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit); + if (!count($user)) { + logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported'); + continue; + } + } + + logger('appnet_cron: importing timeline from user '.$rr['uid']); + appnet_fetchstream($a, $rr["uid"]); + } + } + + logger('appnet_cron: cron_end'); + + set_config('appnet','last_poll', time()); +} + +function appnet_error($msg) { + $msg = trim($msg); + $pos = strrpos($msg, "\r\n\r\n"); + + if (!$pos) + return($msg); + + $msg = substr($msg, $pos + 4); + + $error = json_decode($msg); + + if ($error == NULL) + return($msg); + + if (isset($error->meta->error_message)) + return($error->meta->error_message); + else + return(print_r($error)); +} diff --git a/appnet/lang/C/messages.po b/appnet/lang/C/messages.po new file mode 100644 index 00000000..a6617de9 --- /dev/null +++ b/appnet/lang/C/messages.po @@ -0,0 +1,116 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "" + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "" + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try again." +"

" +msgstr "" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/ and enter " +"Client ID and Client Secret. " +msgstr "" + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "" + +#: appnet.php:169 +msgid "Client ID" +msgstr "" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "" + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "" + +#: appnet.php:180 +msgid "Token" +msgstr "" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "" diff --git a/appnet/lang/cs/messages.po b/appnet/lang/cs/messages.po new file mode 100644 index 00000000..b6527459 --- /dev/null +++ b/appnet/lang/cs/messages.po @@ -0,0 +1,118 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# Michal Šupler , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2014-07-02 15:24+0000\n" +"Last-Translator: Michal Šupler \n" +"Language-Team: Czech (http://www.transifex.com/projects/p/friendica/language/cs/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: cs\n" +"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Přístup odmítnut." + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Nyní jste přihlášen k app.net." + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Chyba v přenesení tokenu. Prosím zkuste to znovu.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "návrat ke stránce konektor" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Poslat příspěvek na app.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "App.net Export" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "V současné době připojen k:" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Aktivovat App.net Post Plugin" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Defaultně poslat na App.net" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importovat vzdálenou časovou osu" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Chyba v přenesení uživatelského profilu. Prosím zkuste smazat konfiguraci a zkusit to znovu.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Máte nyní dvě možnosti jak se připojit k App.net.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

První možnost: Registrovat svou žádost na https://account.app.net/developer/apps/ a zadat Client ID and Client Secret. " + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Použít '%s' jako URI pro přesměrování

" + +#: appnet.php:169 +msgid "Client ID" +msgstr "Client ID" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Client Secret" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

Druhá možnost: vložit token do http://dev-lite.jonathonduerig.com/. " + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Nastavte tyto rámce: 'Základní', 'Stream', 'Psaní příspěvků, 'Veřejné zprávy', 'Zprávy'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Token" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Přihlásit se s použitím App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Vymazat konfiguraci OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Uložit Nastavení" diff --git a/appnet/lang/cs/strings.php b/appnet/lang/cs/strings.php new file mode 100644 index 00000000..4bc45427 --- /dev/null +++ b/appnet/lang/cs/strings.php @@ -0,0 +1,29 @@ +=2 && $n<=4) ? 1 : 2;; +}} +; +$a->strings["Permission denied."] = "Přístup odmítnut."; +$a->strings["You are now authenticated to app.net. "] = "Nyní jste přihlášen k app.net."; +$a->strings["

Error fetching token. Please try again.

"] = "

Chyba v přenesení tokenu. Prosím zkuste to znovu.

"; +$a->strings["return to the connector page"] = "návrat ke stránce konektor"; +$a->strings["Post to app.net"] = "Poslat příspěvek na app.net"; +$a->strings["App.net Export"] = "App.net Export"; +$a->strings["Currently connected to: "] = "V současné době připojen k:"; +$a->strings["Enable App.net Post Plugin"] = "Aktivovat App.net Post Plugin"; +$a->strings["Post to App.net by default"] = "Defaultně poslat na App.net"; +$a->strings["Import the remote timeline"] = "Importovat vzdálenou časovou osu"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Chyba v přenesení uživatelského profilu. Prosím zkuste smazat konfiguraci a zkusit to znovu.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Máte nyní dvě možnosti jak se připojit k App.net.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

První možnost: Registrovat svou žádost na https://account.app.net/developer/apps/ a zadat Client ID and Client Secret. "; +$a->strings["Use '%s' as Redirect URI

"] = "Použít '%s' jako URI pro přesměrování

"; +$a->strings["Client ID"] = "Client ID"; +$a->strings["Client Secret"] = "Client Secret"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Druhá možnost: vložit token do http://dev-lite.jonathonduerig.com/. "; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Nastavte tyto rámce: 'Základní', 'Stream', 'Psaní příspěvků, 'Veřejné zprávy', 'Zprávy'.

"; +$a->strings["Token"] = "Token"; +$a->strings["Sign in using App.net"] = "Přihlásit se s použitím App.net"; +$a->strings["Clear OAuth configuration"] = "Vymazat konfiguraci OAuth"; +$a->strings["Save Settings"] = "Uložit Nastavení"; diff --git a/appnet/lang/de/messages.po b/appnet/lang/de/messages.po new file mode 100644 index 00000000..6e8f7c88 --- /dev/null +++ b/appnet/lang/de/messages.po @@ -0,0 +1,118 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# bavatar , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2014-06-25 04:31+0000\n" +"Last-Translator: bavatar \n" +"Language-Team: German (http://www.transifex.com/projects/p/friendica/language/de/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: de\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Zugriff verweigert." + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Du bist nun auf app.net authentifiziert." + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Fehler beim Holen des Tokens, bitte versuche es später noch einmal.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "zurück zur Connector Seite" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Nach app.net senden" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "App.net Export" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Momentan verbunden mit: " + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Veröffentlichungen bei App.net erlauben" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Standardmäßig bei App.net veröffentlichen" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importiere die entfernte Zeitleiste" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Beim Laden des Nutzerprofils ist ein Fehler aufgetreten. Bitte versuche es später noch einmal.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Du hast zwei Wege deinen friendica Account mit App.net zu verbinden.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

Erster Weg: Registriere eine Anwendung unter https://account.app.net/developer/apps/ und wähle eine Client ID und ein Client Secret." + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Verwende '%s' als Redirect URI

" + +#: appnet.php:169 +msgid "Client ID" +msgstr "Client ID" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Client Secret" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

Zweiter Weg: Beantrage ein Token unter http://dev-lite.jonathonduerig.com/. " + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Verwende folgende Scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Token" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Per App.net anmelden" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "OAuth Konfiguration löschen" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Einstellungen speichern" diff --git a/appnet/lang/de/strings.php b/appnet/lang/de/strings.php new file mode 100644 index 00000000..da80cf7c --- /dev/null +++ b/appnet/lang/de/strings.php @@ -0,0 +1,29 @@ +strings["Permission denied."] = "Zugriff verweigert."; +$a->strings["You are now authenticated to app.net. "] = "Du bist nun auf app.net authentifiziert."; +$a->strings["

Error fetching token. Please try again.

"] = "

Fehler beim Holen des Tokens, bitte versuche es später noch einmal.

"; +$a->strings["return to the connector page"] = "zurück zur Connector Seite"; +$a->strings["Post to app.net"] = "Nach app.net senden"; +$a->strings["App.net Export"] = "App.net Export"; +$a->strings["Currently connected to: "] = "Momentan verbunden mit: "; +$a->strings["Enable App.net Post Plugin"] = "Veröffentlichungen bei App.net erlauben"; +$a->strings["Post to App.net by default"] = "Standardmäßig bei App.net veröffentlichen"; +$a->strings["Import the remote timeline"] = "Importiere die entfernte Zeitleiste"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Beim Laden des Nutzerprofils ist ein Fehler aufgetreten. Bitte versuche es später noch einmal.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Du hast zwei Wege deinen friendica Account mit App.net zu verbinden.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Erster Weg: Registriere eine Anwendung unter https://account.app.net/developer/apps/ und wähle eine Client ID und ein Client Secret."; +$a->strings["Use '%s' as Redirect URI

"] = "Verwende '%s' als Redirect URI

"; +$a->strings["Client ID"] = "Client ID"; +$a->strings["Client Secret"] = "Client Secret"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Zweiter Weg: Beantrage ein Token unter http://dev-lite.jonathonduerig.com/. "; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Verwende folgende Scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"; +$a->strings["Token"] = "Token"; +$a->strings["Sign in using App.net"] = "Per App.net anmelden"; +$a->strings["Clear OAuth configuration"] = "OAuth Konfiguration löschen"; +$a->strings["Save Settings"] = "Einstellungen speichern"; diff --git a/appnet/lang/es/messages.po b/appnet/lang/es/messages.po new file mode 100644 index 00000000..a44089d7 --- /dev/null +++ b/appnet/lang/es/messages.po @@ -0,0 +1,118 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# Alberto Díaz Tormo , 2016 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2016-10-13 21:25+0000\n" +"Last-Translator: Alberto Díaz Tormo \n" +"Language-Team: Spanish (http://www.transifex.com/Friendica/friendica/language/es/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: es\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Permiso denegado" + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Ahora está autenticado en app.net." + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Advertencia de error. Por favor inténtelo de nuevo.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "vuelva a pa página de conexón" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Publique en app.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "Exportar a app.net" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Actualmente conectado a:" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Habilitar el plugin de publicación de App.net" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Publicar en App.net por defecto" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importar la línea de tiempo remota" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Advertencia de error de perfil. Por favor borre la configuración e inténtelo de nuevo.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Tiene dos formas de conectar a App.net.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

Primera forma: Registrar una aplicación en https://account.app.net/developer/apps/ y seleccionar Client ID y Client Secret. " + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Use '%s' como Redirigir URI" + +#: appnet.php:169 +msgid "Client ID" +msgstr "ID de cliente" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Secreto de cliente" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

Segunda manera: traiga un símbolo a http://dev-lite.jonathonduerig.com/" + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Seleccione estas posibilidades: 'Básico', 'Continuo', 'Escribir entrada', 'Mensajes públicos', 'Mensajes'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Símbolo" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Regístrese usando App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Borre la configuración OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Guardar los ajustes" diff --git a/appnet/lang/es/strings.php b/appnet/lang/es/strings.php new file mode 100644 index 00000000..020c6f35 --- /dev/null +++ b/appnet/lang/es/strings.php @@ -0,0 +1,29 @@ +strings["Permission denied."] = "Permiso denegado"; +$a->strings["You are now authenticated to app.net. "] = "Ahora está autenticado en app.net."; +$a->strings["

Error fetching token. Please try again.

"] = "

Advertencia de error. Por favor inténtelo de nuevo.

"; +$a->strings["return to the connector page"] = "vuelva a pa página de conexón"; +$a->strings["Post to app.net"] = "Publique en app.net"; +$a->strings["App.net Export"] = "Exportar a app.net"; +$a->strings["Currently connected to: "] = "Actualmente conectado a:"; +$a->strings["Enable App.net Post Plugin"] = "Habilitar el plugin de publicación de App.net"; +$a->strings["Post to App.net by default"] = "Publicar en App.net por defecto"; +$a->strings["Import the remote timeline"] = "Importar la línea de tiempo remota"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Advertencia de error de perfil. Por favor borre la configuración e inténtelo de nuevo.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Tiene dos formas de conectar a App.net.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Primera forma: Registrar una aplicación en https://account.app.net/developer/apps/ y seleccionar Client ID y Client Secret. "; +$a->strings["Use '%s' as Redirect URI

"] = "Use '%s' como Redirigir URI"; +$a->strings["Client ID"] = "ID de cliente"; +$a->strings["Client Secret"] = "Secreto de cliente"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Segunda manera: traiga un símbolo a http://dev-lite.jonathonduerig.com/"; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Seleccione estas posibilidades: 'Básico', 'Continuo', 'Escribir entrada', 'Mensajes públicos', 'Mensajes'.

"; +$a->strings["Token"] = "Símbolo"; +$a->strings["Sign in using App.net"] = "Regístrese usando App.net"; +$a->strings["Clear OAuth configuration"] = "Borre la configuración OAuth"; +$a->strings["Save Settings"] = "Guardar los ajustes"; diff --git a/appnet/lang/fr/messages.po b/appnet/lang/fr/messages.po new file mode 100644 index 00000000..6f5f2997 --- /dev/null +++ b/appnet/lang/fr/messages.po @@ -0,0 +1,119 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# Hypolite Petovan , 2016 +# Jak , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2016-09-24 02:12+0000\n" +"Last-Translator: Hypolite Petovan \n" +"Language-Team: French (http://www.transifex.com/Friendica/friendica/language/fr/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: fr\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Autorisation refusée" + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Vous êtes maintenant authentifié sur app.net" + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Impossible d'obtenir le jeton, merci de réessayer.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "revenir à la page du connecteur" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Publier sur app.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "Export App.net" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Actuellement connecté à :" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Activer le plugin de publication app.net" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Publier sur App.net par défaut" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importer la timeline distante" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Impossible d'obtenir le profil utilisateur. Merci de réinitialiser la configuration et de réessayer.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Vous avez deux possibilités pour vous connecter à App.net.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

Première méthode: Enregistrer une application sur App.net [en] et entrez l'ID Client et le Secret Client. " + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Utilisez '%s' pour l'URI de Redirection" + +#: appnet.php:169 +msgid "Client ID" +msgstr "ID Client" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Secret Client" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

Deuxième méthode: obtenez un jeton ur http://dev-lite.jonathonduerig.com/ [en]. " + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Cochez les \"scopes\" suivant: \"Basic\", \"Stream\", \"Write Post\", \"Public Messages\", \"Messages\".

" + +#: appnet.php:180 +msgid "Token" +msgstr "Jeton" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Se connecter avec App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Effacer la configuration OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Sauvegarder les paramètres" diff --git a/appnet/lang/fr/strings.php b/appnet/lang/fr/strings.php new file mode 100644 index 00000000..ef9fc9e2 --- /dev/null +++ b/appnet/lang/fr/strings.php @@ -0,0 +1,29 @@ + 1);; +}} +; +$a->strings["Permission denied."] = "Autorisation refusée"; +$a->strings["You are now authenticated to app.net. "] = "Vous êtes maintenant authentifié sur app.net"; +$a->strings["

Error fetching token. Please try again.

"] = "

Impossible d'obtenir le jeton, merci de réessayer.

"; +$a->strings["return to the connector page"] = "revenir à la page du connecteur"; +$a->strings["Post to app.net"] = "Publier sur app.net"; +$a->strings["App.net Export"] = "Export App.net"; +$a->strings["Currently connected to: "] = "Actuellement connecté à :"; +$a->strings["Enable App.net Post Plugin"] = "Activer le plugin de publication app.net"; +$a->strings["Post to App.net by default"] = "Publier sur App.net par défaut"; +$a->strings["Import the remote timeline"] = "Importer la timeline distante"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Impossible d'obtenir le profil utilisateur. Merci de réinitialiser la configuration et de réessayer.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Vous avez deux possibilités pour vous connecter à App.net.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Première méthode: Enregistrer une application sur App.net [en] et entrez l'ID Client et le Secret Client. "; +$a->strings["Use '%s' as Redirect URI

"] = "Utilisez '%s' pour l'URI de Redirection"; +$a->strings["Client ID"] = "ID Client"; +$a->strings["Client Secret"] = "Secret Client"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Deuxième méthode: obtenez un jeton ur http://dev-lite.jonathonduerig.com/ [en]. "; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Cochez les \"scopes\" suivant: \"Basic\", \"Stream\", \"Write Post\", \"Public Messages\", \"Messages\".

"; +$a->strings["Token"] = "Jeton"; +$a->strings["Sign in using App.net"] = "Se connecter avec App.net"; +$a->strings["Clear OAuth configuration"] = "Effacer la configuration OAuth"; +$a->strings["Save Settings"] = "Sauvegarder les paramètres"; diff --git a/appnet/lang/it/messages.po b/appnet/lang/it/messages.po new file mode 100644 index 00000000..17b933fe --- /dev/null +++ b/appnet/lang/it/messages.po @@ -0,0 +1,118 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# fabrixxm , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2014-09-10 10:18+0000\n" +"Last-Translator: fabrixxm \n" +"Language-Team: Italian (http://www.transifex.com/Friendica/friendica/language/it/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: it\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Permesso negato." + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Sei autenticato su app.net" + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Errore recuperando il token. Prova di nuovo

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "ritorna alla pagina del connettore" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Invia ad app.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "Esporta App.net" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Al momento connesso con:" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Abilita il plugin di invio ad App.net" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Invia sempre ad App.net" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importa la timeline remota" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Errore recuperando il profilo utente. Svuota la configurazione e prova di nuovo.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Puoi collegarti ad App.net in due modi.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

Registrare un'applicazione su https://account.app.net/developer/apps/ e inserire Client ID e Client Secret." + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Usa '%s' come Redirect URI

" + +#: appnet.php:169 +msgid "Client ID" +msgstr "Client ID" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Client Secret" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

Oppure puoi recuperare un token su http://dev-lite.jonathonduerig.com/." + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Imposta gli ambiti 'Basic', 'Stream', 'Scrivi Post', 'Messaggi Pubblici', 'Messaggi'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Token" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Autenticati con App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Pulisci configurazione OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Salva Impostazioni" diff --git a/appnet/lang/it/strings.php b/appnet/lang/it/strings.php new file mode 100644 index 00000000..01c56524 --- /dev/null +++ b/appnet/lang/it/strings.php @@ -0,0 +1,29 @@ +strings["Permission denied."] = "Permesso negato."; +$a->strings["You are now authenticated to app.net. "] = "Sei autenticato su app.net"; +$a->strings["

Error fetching token. Please try again.

"] = "

Errore recuperando il token. Prova di nuovo

"; +$a->strings["return to the connector page"] = "ritorna alla pagina del connettore"; +$a->strings["Post to app.net"] = "Invia ad app.net"; +$a->strings["App.net Export"] = "Esporta App.net"; +$a->strings["Currently connected to: "] = "Al momento connesso con:"; +$a->strings["Enable App.net Post Plugin"] = "Abilita il plugin di invio ad App.net"; +$a->strings["Post to App.net by default"] = "Invia sempre ad App.net"; +$a->strings["Import the remote timeline"] = "Importa la timeline remota"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Errore recuperando il profilo utente. Svuota la configurazione e prova di nuovo.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Puoi collegarti ad App.net in due modi.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Registrare un'applicazione su https://account.app.net/developer/apps/ e inserire Client ID e Client Secret."; +$a->strings["Use '%s' as Redirect URI

"] = "Usa '%s' come Redirect URI

"; +$a->strings["Client ID"] = "Client ID"; +$a->strings["Client Secret"] = "Client Secret"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Oppure puoi recuperare un token su http://dev-lite.jonathonduerig.com/."; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Imposta gli ambiti 'Basic', 'Stream', 'Scrivi Post', 'Messaggi Pubblici', 'Messaggi'.

"; +$a->strings["Token"] = "Token"; +$a->strings["Sign in using App.net"] = "Autenticati con App.net"; +$a->strings["Clear OAuth configuration"] = "Pulisci configurazione OAuth"; +$a->strings["Save Settings"] = "Salva Impostazioni"; diff --git a/appnet/lang/nl/messages.po b/appnet/lang/nl/messages.po new file mode 100644 index 00000000..74653c76 --- /dev/null +++ b/appnet/lang/nl/messages.po @@ -0,0 +1,118 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# Jeroen S , 2016 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2016-06-23 19:52+0000\n" +"Last-Translator: Jeroen S \n" +"Language-Team: Dutch (http://www.transifex.com/Friendica/friendica/language/nl/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: nl\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Toegang geweigerd" + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Je bent nu aangemeld bij app.net." + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Fout tijdens token fetching. Probeer het nogmaals.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "ga terug naar de connector pagina" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Post naar app.net." + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "App.net Export" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Momenteel verbonden met:" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "App.net Post Plugin inschakelen" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Naar App.net posten als standaard instellen" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "The tijdlijn op afstand importeren" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Fout tijdens het ophalen van gebruikersprofiel. Leeg de configuratie en probeer het opnieuw.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Er zijn twee manieren om met App.net te verbinden.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "" + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "" + +#: appnet.php:169 +msgid "Client ID" +msgstr "" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "" + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "" + +#: appnet.php:180 +msgid "Token" +msgstr "" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "" diff --git a/appnet/lang/nl/strings.php b/appnet/lang/nl/strings.php new file mode 100644 index 00000000..ba72e364 --- /dev/null +++ b/appnet/lang/nl/strings.php @@ -0,0 +1,29 @@ +strings["Permission denied."] = "Toegang geweigerd"; +$a->strings["You are now authenticated to app.net. "] = "Je bent nu aangemeld bij app.net."; +$a->strings["

Error fetching token. Please try again.

"] = "

Fout tijdens token fetching. Probeer het nogmaals.

"; +$a->strings["return to the connector page"] = "ga terug naar de connector pagina"; +$a->strings["Post to app.net"] = "Post naar app.net."; +$a->strings["App.net Export"] = "App.net Export"; +$a->strings["Currently connected to: "] = "Momenteel verbonden met:"; +$a->strings["Enable App.net Post Plugin"] = "App.net Post Plugin inschakelen"; +$a->strings["Post to App.net by default"] = "Naar App.net posten als standaard instellen"; +$a->strings["Import the remote timeline"] = "The tijdlijn op afstand importeren"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Fout tijdens het ophalen van gebruikersprofiel. Leeg de configuratie en probeer het opnieuw.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Er zijn twee manieren om met App.net te verbinden.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = ""; +$a->strings["Use '%s' as Redirect URI

"] = ""; +$a->strings["Client ID"] = ""; +$a->strings["Client Secret"] = ""; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = ""; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = ""; +$a->strings["Token"] = ""; +$a->strings["Sign in using App.net"] = ""; +$a->strings["Clear OAuth configuration"] = ""; +$a->strings["Save Settings"] = ""; diff --git a/appnet/lang/pt-br/messages.po b/appnet/lang/pt-br/messages.po new file mode 100644 index 00000000..c279c7dd --- /dev/null +++ b/appnet/lang/pt-br/messages.po @@ -0,0 +1,119 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# Beatriz Vital , 2016 +# Calango Jr , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2016-08-19 20:37+0000\n" +"Last-Translator: Beatriz Vital \n" +"Language-Team: Portuguese (Brazil) (http://www.transifex.com/Friendica/friendica/language/pt_BR/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: pt_BR\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Permissão negada." + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Você está autenticado no app.net." + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "Erro ocorrido na obtenção do token. Tente novamente." + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "Volte a página de conectores." + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Publicar no App.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "App.net exportar" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Atualmente conectado em: " + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Habilitar plug-in para publicar no App.net" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Publicar em App.net por padrão" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importar a linha do tempo remota" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "Erro na obtenção do perfil do usuário. Confira as configurações e tente novamente." + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Você possui duas formas de conectar ao App.net

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

1º Método: Registre uma aplicação em https://account.app.net/developer/apps/ e entre o Client ID e Client Secret" + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Use '%s' como URI redirecionador

" + +#: appnet.php:169 +msgid "Client ID" +msgstr "Client ID" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Client Secret" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

2º Método: obtenha um token em http://dev-lite.jonathonduerig.com/. " + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Adicione valor as estas saídas: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Token" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Entre usando o App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Limpar configuração OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Salvar Configurações" diff --git a/appnet/lang/pt-br/strings.php b/appnet/lang/pt-br/strings.php new file mode 100644 index 00000000..b8e1112c --- /dev/null +++ b/appnet/lang/pt-br/strings.php @@ -0,0 +1,29 @@ + 1);; +}} +; +$a->strings["Permission denied."] = "Permissão negada."; +$a->strings["You are now authenticated to app.net. "] = "Você está autenticado no app.net."; +$a->strings["

Error fetching token. Please try again.

"] = "Erro ocorrido na obtenção do token. Tente novamente."; +$a->strings["return to the connector page"] = "Volte a página de conectores."; +$a->strings["Post to app.net"] = "Publicar no App.net"; +$a->strings["App.net Export"] = "App.net exportar"; +$a->strings["Currently connected to: "] = "Atualmente conectado em: "; +$a->strings["Enable App.net Post Plugin"] = "Habilitar plug-in para publicar no App.net"; +$a->strings["Post to App.net by default"] = "Publicar em App.net por padrão"; +$a->strings["Import the remote timeline"] = "Importar a linha do tempo remota"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "Erro na obtenção do perfil do usuário. Confira as configurações e tente novamente."; +$a->strings["

You have two ways to connect to App.net.

"] = "

Você possui duas formas de conectar ao App.net

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

1º Método: Registre uma aplicação em https://account.app.net/developer/apps/ e entre o Client ID e Client Secret"; +$a->strings["Use '%s' as Redirect URI

"] = "Use '%s' como URI redirecionador

"; +$a->strings["Client ID"] = "Client ID"; +$a->strings["Client Secret"] = "Client Secret"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

2º Método: obtenha um token em http://dev-lite.jonathonduerig.com/. "; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Adicione valor as estas saídas: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"; +$a->strings["Token"] = "Token"; +$a->strings["Sign in using App.net"] = "Entre usando o App.net"; +$a->strings["Clear OAuth configuration"] = "Limpar configuração OAuth"; +$a->strings["Save Settings"] = "Salvar Configurações"; diff --git a/appnet/lang/ro/messages.po b/appnet/lang/ro/messages.po new file mode 100644 index 00000000..a9c5242f --- /dev/null +++ b/appnet/lang/ro/messages.po @@ -0,0 +1,117 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2014-07-08 11:40+0000\n" +"Last-Translator: Arian - Cazare Muncitori \n" +"Language-Team: Romanian (Romania) (http://www.transifex.com/projects/p/friendica/language/ro_RO/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: ro_RO\n" +"Plural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1));\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Permisiune refuzată." + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Acum sunteți autentificat pe App.net." + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Eroare la procesarea token-ului. Vă rugăm să reîncercați.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "revenire la pagina de conectare" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Postați pe App.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "Exportare pe App.net" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "Conectat curent la:" + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Activare Modul Postare pe App.net" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Postați implicit pe App.net" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Importare cronologie la distanță" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Eroare la procesarea profilului de utilizator. Vă rugăm să ștergeți configurarea şi apoi reîncercați.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

Aveți două modalități de a vă conecta la App.net.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

Prima modalitate: Înregistrați o cerere pe https://account.app.net/developer/apps/ şi introduceți ID Client şi Cheia Secretă Client." + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Utilizați '%s' ca URI de Redirecţionare

" + +#: appnet.php:169 +msgid "Client ID" +msgstr "ID Client" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Cheia Secretă Client" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

A doua cale: autorizați un indicativ de acces token de pe http://dev-lite.jonathonduerig.com/ ." + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Stabiliți aceste scopuri: 'De Bază', 'Flux', 'Scriere Postare', 'Mesaje Publice', 'Mesaje'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Token" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Autentificați-vă utilizând App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Ștergeți configurările OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Salvare Configurări" diff --git a/appnet/lang/ro/strings.php b/appnet/lang/ro/strings.php new file mode 100644 index 00000000..fa8d139d --- /dev/null +++ b/appnet/lang/ro/strings.php @@ -0,0 +1,29 @@ +19)||(($n%100==0)&&($n!=0)))?2:1));; +}} +; +$a->strings["Permission denied."] = "Permisiune refuzată."; +$a->strings["You are now authenticated to app.net. "] = "Acum sunteți autentificat pe App.net."; +$a->strings["

Error fetching token. Please try again.

"] = "

Eroare la procesarea token-ului. Vă rugăm să reîncercați.

"; +$a->strings["return to the connector page"] = "revenire la pagina de conectare"; +$a->strings["Post to app.net"] = "Postați pe App.net"; +$a->strings["App.net Export"] = "Exportare pe App.net"; +$a->strings["Currently connected to: "] = "Conectat curent la:"; +$a->strings["Enable App.net Post Plugin"] = "Activare Modul Postare pe App.net"; +$a->strings["Post to App.net by default"] = "Postați implicit pe App.net"; +$a->strings["Import the remote timeline"] = "Importare cronologie la distanță"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Eroare la procesarea profilului de utilizator. Vă rugăm să ștergeți configurarea şi apoi reîncercați.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

Aveți două modalități de a vă conecta la App.net.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Prima modalitate: Înregistrați o cerere pe https://account.app.net/developer/apps/ şi introduceți ID Client şi Cheia Secretă Client."; +$a->strings["Use '%s' as Redirect URI

"] = "Utilizați '%s' ca URI de Redirecţionare

"; +$a->strings["Client ID"] = "ID Client"; +$a->strings["Client Secret"] = "Cheia Secretă Client"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

A doua cale: autorizați un indicativ de acces token de pe http://dev-lite.jonathonduerig.com/ ."; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Stabiliți aceste scopuri: 'De Bază', 'Flux', 'Scriere Postare', 'Mesaje Publice', 'Mesaje'.

"; +$a->strings["Token"] = "Token"; +$a->strings["Sign in using App.net"] = "Autentificați-vă utilizând App.net"; +$a->strings["Clear OAuth configuration"] = "Ștergeți configurările OAuth"; +$a->strings["Save Settings"] = "Salvare Configurări"; diff --git a/appnet/lang/ru/messages.po b/appnet/lang/ru/messages.po new file mode 100644 index 00000000..a5755caa --- /dev/null +++ b/appnet/lang/ru/messages.po @@ -0,0 +1,118 @@ +# ADDON appnet +# Copyright (C) +# This file is distributed under the same license as the Friendica appnet addon package. +# +# +# Translators: +# Stanislav N. , 2017 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 11:47+0200\n" +"PO-Revision-Date: 2017-04-08 05:32+0000\n" +"Last-Translator: Stanislav N. \n" +"Language-Team: Russian (http://www.transifex.com/Friendica/friendica/language/ru/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: ru\n" +"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n" + +#: appnet.php:39 +msgid "Permission denied." +msgstr "Доступ запрещен." + +#: appnet.php:73 +msgid "You are now authenticated to app.net. " +msgstr "Вы аутентифицированы на app.net" + +#: appnet.php:77 +msgid "

Error fetching token. Please try again.

" +msgstr "

Ошибка получения токена. Попробуйте еще раз.

" + +#: appnet.php:80 +msgid "return to the connector page" +msgstr "вернуться на страницу коннектора" + +#: appnet.php:94 +msgid "Post to app.net" +msgstr "Отправить на app.net" + +#: appnet.php:125 appnet.php:129 +msgid "App.net Export" +msgstr "Экспорт app.net" + +#: appnet.php:142 +msgid "Currently connected to: " +msgstr "В настоящее время соединены с: " + +#: appnet.php:144 +msgid "Enable App.net Post Plugin" +msgstr "Включить плагин App.net" + +#: appnet.php:149 +msgid "Post to App.net by default" +msgstr "Отправлять сообщения на App.net по-умолчанию" + +#: appnet.php:153 +msgid "Import the remote timeline" +msgstr "Импортировать удаленные сообщения" + +#: appnet.php:159 +msgid "" +"

Error fetching user profile. Please clear the configuration and try " +"again.

" +msgstr "

Ошибка при получении профиля пользователя. Сбросьте конфигурацию и попробуйте еще раз.

" + +#: appnet.php:164 +msgid "

You have two ways to connect to App.net.

" +msgstr "

У вас есть два способа соединения с App.net.

" + +#: appnet.php:166 +msgid "" +"

First way: Register an application at https://account.app.net/developer/apps/" +" and enter Client ID and Client Secret. " +msgstr "

Первый способ: зарегистрируйте приложение на https://account.app.net/developer/apps/ и введите Client ID и Client Secret" + +#: appnet.php:167 +#, php-format +msgid "Use '%s' as Redirect URI

" +msgstr "Используйте '%s' как Redirect URI

" + +#: appnet.php:169 +msgid "Client ID" +msgstr "Client ID" + +#: appnet.php:173 +msgid "Client Secret" +msgstr "Client Secret" + +#: appnet.php:177 +msgid "" +"

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. " +msgstr "

Второй путь: получите токен на http://dev-lite.jonathonduerig.com/. " + +#: appnet.php:178 +msgid "" +"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', " +"'Messages'.

" +msgstr "Выберите области: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

" + +#: appnet.php:180 +msgid "Token" +msgstr "Токен" + +#: appnet.php:192 +msgid "Sign in using App.net" +msgstr "Войти через App.net" + +#: appnet.php:197 +msgid "Clear OAuth configuration" +msgstr "Удалить конфигурацию OAuth" + +#: appnet.php:204 +msgid "Save Settings" +msgstr "Сохранить настройки" diff --git a/appnet/lang/ru/strings.php b/appnet/lang/ru/strings.php new file mode 100644 index 00000000..c2d9b440 --- /dev/null +++ b/appnet/lang/ru/strings.php @@ -0,0 +1,29 @@ +=2 && $n%10<=4 && ($n%100<12 || $n%100>14) ? 1 : $n%10==0 || ($n%10>=5 && $n%10<=9) || ($n%100>=11 && $n%100<=14)? 2 : 3);; +}} +; +$a->strings["Permission denied."] = "Доступ запрещен."; +$a->strings["You are now authenticated to app.net. "] = "Вы аутентифицированы на app.net"; +$a->strings["

Error fetching token. Please try again.

"] = "

Ошибка получения токена. Попробуйте еще раз.

"; +$a->strings["return to the connector page"] = "вернуться на страницу коннектора"; +$a->strings["Post to app.net"] = "Отправить на app.net"; +$a->strings["App.net Export"] = "Экспорт app.net"; +$a->strings["Currently connected to: "] = "В настоящее время соединены с: "; +$a->strings["Enable App.net Post Plugin"] = "Включить плагин App.net"; +$a->strings["Post to App.net by default"] = "Отправлять сообщения на App.net по-умолчанию"; +$a->strings["Import the remote timeline"] = "Импортировать удаленные сообщения"; +$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Ошибка при получении профиля пользователя. Сбросьте конфигурацию и попробуйте еще раз.

"; +$a->strings["

You have two ways to connect to App.net.

"] = "

У вас есть два способа соединения с App.net.

"; +$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Первый способ: зарегистрируйте приложение на https://account.app.net/developer/apps/ и введите Client ID и Client Secret"; +$a->strings["Use '%s' as Redirect URI

"] = "Используйте '%s' как Redirect URI

"; +$a->strings["Client ID"] = "Client ID"; +$a->strings["Client Secret"] = "Client Secret"; +$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Второй путь: получите токен на http://dev-lite.jonathonduerig.com/. "; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Выберите области: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"; +$a->strings["Token"] = "Токен"; +$a->strings["Sign in using App.net"] = "Войти через App.net"; +$a->strings["Clear OAuth configuration"] = "Удалить конфигурацию OAuth"; +$a->strings["Save Settings"] = "Сохранить настройки"; diff --git a/appnet/templates/admin.tpl b/appnet/templates/admin.tpl new file mode 100644 index 00000000..a933f3d3 --- /dev/null +++ b/appnet/templates/admin.tpl @@ -0,0 +1,3 @@ +{{include file="field_input.tpl" field=$clientid}} +{{include file="field_input.tpl" field=$clientsecret}} +
diff --git a/blackout/blackout.php b/blackout/blackout.php index 2693db5a..3678969e 100644 --- a/blackout/blackout.php +++ b/blackout/blackout.php @@ -36,10 +36,10 @@ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -49,7 +49,6 @@ * THE SOFTWARE. */ -use Friendica\Core\Config; function blackout_install() { register_hook('page_header', 'addon/blackout/blackout.php', 'blackout_redirect'); @@ -68,9 +67,9 @@ function blackout_redirect ($a, $b) { return true; // else... - $mystart = Config::get('blackout','begindate'); - $myend = Config::get('blackout','enddate'); - $myurl = Config::get('blackout','url'); + $mystart = get_config('blackout','begindate'); + $myend = get_config('blackout','enddate'); + $myurl = get_config('blackout','url'); $now = time(); $date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart); $date2 = DateTime::createFromFormat('Y-m-d G:i', $myend); @@ -88,21 +87,21 @@ function blackout_redirect ($a, $b) { } function blackout_plugin_admin(&$a, &$o) { - $mystart = Config::get('blackout','begindate'); + $mystart = get_config('blackout','begindate'); if (! is_string($mystart)) { $mystart = "YYYY-MM-DD:hhmm"; } - $myend = Config::get('blackout','enddate'); + $myend = get_config('blackout','enddate'); if (! is_string($myend)) { $myend = "YYYY-MM-DD:hhmm"; } - $myurl = Config::get('blackout','url'); + $myurl = get_config('blackout','url'); if (! is_string($myurl)) { $myurl = "http://www.example.com"; } $t = get_markup_template( "admin.tpl", "addon/blackout/" ); - - $o = replace_macros($t, [ + + $o = replace_macros($t, array( '$submit' => t('Save Settings'), - '$rurl' => ["rurl", "Redirect URL", $myurl, "all your visitors from the web will be redirected to this URL"], - '$startdate' => ["startdate", "Begin of the Blackout
(YYYY-MM-DD hh:mm)", $mystart, "format is YYYY year, MM month, DD day, hh hour and mm minute"], - '$enddate' => ["enddate", "End of the Blackout
(YYYY-MM-DD hh:mm)", $myend, ""], + '$rurl' => array("rurl", "Redirect URL", $myurl, "all your visitors from the web will be redirected to this URL"), + '$startdate' => array("startdate", "Begin of the Blackout
(YYYY-MM-DD hh:mm)", $mystart, "format is YYYY year, MM month, DD day, hh hour and mm minute"), + '$enddate' => array("enddate", "End of the Blackout
(YYYY-MM-DD hh:mm)", $myend, ""), - ]); + )); $date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart); $date2 = DateTime::createFromFormat('Y-m-d G:i', $myend); if ($date2 < $date1) { @@ -115,7 +114,7 @@ function blackout_plugin_admin_post (&$a) { $begindate = trim($_POST['startdate']); $enddate = trim($_POST['enddate']); $url = trim($_POST['rurl']); - Config::set('blackout','begindate',$begindate); - Config::set('blackout','enddate',$enddate); - Config::set('blackout','url',$url); + set_config('blackout','begindate',$begindate); + set_config('blackout','enddate',$enddate); + set_config('blackout','url',$url); } diff --git a/blockem/blockem.php b/blockem/blockem.php index 2c91373f..223a1990 100644 --- a/blockem/blockem.php +++ b/blockem/blockem.php @@ -6,11 +6,9 @@ * Description: block people * Version: 1.0 * Author: Mike Macgirvin - * + * */ -use Friendica\Core\PConfig; - function blockem_install() { register_hook('prepare_body', 'addon/blockem/blockem.php', 'blockem_prepare_body'); register_hook('display_item', 'addon/blockem/blockem.php', 'blockem_display_item'); @@ -47,7 +45,7 @@ function blockem_addon_settings(&$a,&$s) { $a->page['htmlhead'] .= '' . "\r\n"; - $words = PConfig::get(local_user(),'blockem','words'); + $words = get_pconfig(local_user(),'blockem','words'); if(! $words) $words = ''; @@ -76,7 +74,7 @@ function blockem_addon_settings_post(&$a,&$b) { return; if($_POST['blockem-submit']) { - PConfig::set(local_user(),'blockem','words',trim($_POST['blockem-words'])); + set_pconfig(local_user(),'blockem','words',trim($_POST['blockem-words'])); info( t('BLOCKEM Settings saved.') . EOL); } } @@ -84,7 +82,7 @@ function blockem_addon_settings_post(&$a,&$b) { function blockem_enotify_store(&$a,&$b) { - $words = PConfig::get($b['uid'],'blockem','words'); + $words = get_pconfig($b['uid'],'blockem','words'); if($words) { $arr = explode(',',$words); } @@ -117,7 +115,7 @@ function blockem_prepare_body(&$a,&$b) { $words = null; if(local_user()) { - $words = PConfig::get(local_user(),'blockem','words'); + $words = get_pconfig(local_user(),'blockem','words'); } if($words) { $arr = explode(',',$words); @@ -141,7 +139,7 @@ function blockem_prepare_body(&$a,&$b) { } if($found) { $rnd = random_string(8); - $b['html'] = ''; + $b['html'] = ''; } } @@ -157,7 +155,7 @@ function blockem_conversation_start(&$a,&$b) { if(! local_user()) return; - $words = PConfig::get(local_user(),'blockem','words'); + $words = get_pconfig(local_user(),'blockem','words'); if($words) { $a->data['blockem'] = explode(',',$words); } @@ -209,7 +207,7 @@ function blockem_init(&$a) { if(! local_user()) return; - $words = PConfig::get(local_user(),'blockem','words'); + $words = get_pconfig(local_user(),'blockem','words'); if(array_key_exists('block',$_GET) && $_GET['block']) { if(strlen($words)) @@ -218,7 +216,7 @@ function blockem_init(&$a) { } if(array_key_exists('unblock',$_GET) && $_GET['unblock']) { $arr = explode(',',$words); - $newarr = []; + $newarr = array(); if(count($arr)) { foreach($arr as $x) { @@ -229,7 +227,7 @@ function blockem_init(&$a) { $words = implode(',',$newarr); } - PConfig::set(local_user(),'blockem','words',$words); + set_pconfig(local_user(),'blockem','words',$words); info( t('blockem settings updated') . EOL ); killme(); } diff --git a/blogger/blogger.php b/blogger/blogger.php index 093d9049..892e8a45 100644 --- a/blogger/blogger.php +++ b/blogger/blogger.php @@ -4,176 +4,174 @@ * Name: Blogger Post Connector * Description: Post to Blogger (or anything else which uses blogger XMLRPC API) * Version: 1.0 - * + * */ -use Friendica\Core\PConfig; - function blogger_install() { - register_hook('post_local', 'addon/blogger/blogger.php', 'blogger_post_local'); - register_hook('notifier_normal', 'addon/blogger/blogger.php', 'blogger_send'); - register_hook('jot_networks', 'addon/blogger/blogger.php', 'blogger_jot_nets'); - register_hook('connector_settings', 'addon/blogger/blogger.php', 'blogger_settings'); - register_hook('connector_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); -} + register_hook('post_local', 'addon/blogger/blogger.php', 'blogger_post_local'); + register_hook('notifier_normal', 'addon/blogger/blogger.php', 'blogger_send'); + register_hook('jot_networks', 'addon/blogger/blogger.php', 'blogger_jot_nets'); + register_hook('connector_settings', 'addon/blogger/blogger.php', 'blogger_settings'); + register_hook('connector_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); +} function blogger_uninstall() { - unregister_hook('post_local', 'addon/blogger/blogger.php', 'blogger_post_local'); - unregister_hook('notifier_normal', 'addon/blogger/blogger.php', 'blogger_send'); - unregister_hook('jot_networks', 'addon/blogger/blogger.php', 'blogger_jot_nets'); - unregister_hook('connector_settings', 'addon/blogger/blogger.php', 'blogger_settings'); - unregister_hook('connector_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); + unregister_hook('post_local', 'addon/blogger/blogger.php', 'blogger_post_local'); + unregister_hook('notifier_normal', 'addon/blogger/blogger.php', 'blogger_send'); + unregister_hook('jot_networks', 'addon/blogger/blogger.php', 'blogger_jot_nets'); + unregister_hook('connector_settings', 'addon/blogger/blogger.php', 'blogger_settings'); + unregister_hook('connector_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); // obsolete - remove - unregister_hook('post_local_end', 'addon/blogger/blogger.php', 'blogger_send'); - unregister_hook('plugin_settings', 'addon/blogger/blogger.php', 'blogger_settings'); - unregister_hook('plugin_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); + unregister_hook('post_local_end', 'addon/blogger/blogger.php', 'blogger_send'); + unregister_hook('plugin_settings', 'addon/blogger/blogger.php', 'blogger_settings'); + unregister_hook('plugin_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); + } function blogger_jot_nets(&$a,&$b) { - if (!local_user()) { - return; - } - - $bl_post = PConfig::get(local_user(),'blogger','post'); - if (intval($bl_post) == 1) { - $bl_defpost = PConfig::get(local_user(),'blogger','post_by_default'); - $selected = ((intval($bl_defpost) == 1) ? ' checked="checked" ' : ''); - $b .= '
' - . t('Post to blogger') . '
'; - } + if(! local_user()) + return; + + $bl_post = get_pconfig(local_user(),'blogger','post'); + if(intval($bl_post) == 1) { + $bl_defpost = get_pconfig(local_user(),'blogger','post_by_default'); + $selected = ((intval($bl_defpost) == 1) ? ' checked="checked" ' : ''); + $b .= '
' + . t('Post to blogger') . '
'; + } } function blogger_settings(&$a,&$s) { - if (! local_user()) { - return; - } + if(! local_user()) + return; - /* Add our stylesheet to the page so we can make our settings look nice */ + /* Add our stylesheet to the page so we can make our settings look nice */ - $a->page['htmlhead'] .= '' . "\r\n"; + $a->page['htmlhead'] .= '' . "\r\n"; - /* Get the current state of our config variables */ + /* Get the current state of our config variables */ - $enabled = PConfig::get(local_user(),'blogger','post'); - $checked = (($enabled) ? ' checked="checked" ' : ''); - $css = (($enabled) ? '' : '-disabled'); + $enabled = get_pconfig(local_user(),'blogger','post'); + $checked = (($enabled) ? ' checked="checked" ' : ''); + $css = (($enabled) ? '' : '-disabled'); - $def_enabled = PConfig::get(local_user(),'blogger','post_by_default'); + $def_enabled = get_pconfig(local_user(),'blogger','post_by_default'); - $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); + $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); - $bl_username = PConfig::get(local_user(), 'blogger', 'bl_username'); - $bl_password = PConfig::get(local_user(), 'blogger', 'bl_password'); - $bl_blog = PConfig::get(local_user(), 'blogger', 'bl_blog'); + $bl_username = get_pconfig(local_user(), 'blogger', 'bl_username'); + $bl_password = get_pconfig(local_user(), 'blogger', 'bl_password'); + $bl_blog = get_pconfig(local_user(), 'blogger', 'bl_blog'); - /* Add some HTML to the existing form */ - $s .= ''; - $s .= '

'. t('Blogger Export').'

'; - $s .= '
'; - $s .= ''; } function blogger_settings_post(&$a,&$b) { - if (x($_POST,'blogger-submit')) { - PConfig::set(local_user(),'blogger','post',intval($_POST['blogger'])); - PConfig::set(local_user(),'blogger','post_by_default',intval($_POST['bl_bydefault'])); - PConfig::set(local_user(),'blogger','bl_username',trim($_POST['bl_username'])); - PConfig::set(local_user(),'blogger','bl_password',trim($_POST['bl_password'])); - PConfig::set(local_user(),'blogger','bl_blog',trim($_POST['bl_blog'])); + + if(x($_POST,'blogger-submit')) { + + set_pconfig(local_user(),'blogger','post',intval($_POST['blogger'])); + set_pconfig(local_user(),'blogger','post_by_default',intval($_POST['bl_bydefault'])); + set_pconfig(local_user(),'blogger','bl_username',trim($_POST['bl_username'])); + set_pconfig(local_user(),'blogger','bl_password',trim($_POST['bl_password'])); + set_pconfig(local_user(),'blogger','bl_blog',trim($_POST['bl_blog'])); + } + } function blogger_post_local(&$a,&$b) { + // This can probably be changed to allow editing by pointing to a different API endpoint - if ($b['edit']) { + if($b['edit']) return; - } - if (!local_user() || (local_user() != $b['uid'])) { + if((! local_user()) || (local_user() != $b['uid'])) return; - } - if ($b['private'] || $b['parent']) { + if($b['private'] || $b['parent']) return; - } - $bl_post = intval(PConfig::get(local_user(),'blogger','post')); + $bl_post = intval(get_pconfig(local_user(),'blogger','post')); $bl_enable = (($bl_post && x($_REQUEST,'blogger_enable')) ? intval($_REQUEST['blogger_enable']) : 0); - if ($b['api_source'] && intval(PConfig::get(local_user(),'blogger','post_by_default'))) { + if($b['api_source'] && intval(get_pconfig(local_user(),'blogger','post_by_default'))) $bl_enable = 1; - } - - if (!$bl_enable) { - return; - } - if (strlen($b['postopts'])) { - $b['postopts'] .= ','; - } + if(! $bl_enable) + return; - $b['postopts'] .= 'blogger'; + if(strlen($b['postopts'])) + $b['postopts'] .= ','; + $b['postopts'] .= 'blogger'; } function blogger_send(&$a,&$b) { - if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { - return; - } - if (! strstr($b['postopts'],'blogger')) { - return; - } + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) + return; + + if(! strstr($b['postopts'],'blogger')) + return; + + if($b['parent'] != $b['id']) + return; - if ($b['parent'] != $b['id']) { - return; - } - $bl_username = xmlify(PConfig::get($b['uid'],'blogger','bl_username')); - $bl_password = xmlify(PConfig::get($b['uid'],'blogger','bl_password')); - $bl_blog = PConfig::get($b['uid'],'blogger','bl_blog'); + $bl_username = xmlify(get_pconfig($b['uid'],'blogger','bl_username')); + $bl_password = xmlify(get_pconfig($b['uid'],'blogger','bl_password')); + $bl_blog = get_pconfig($b['uid'],'blogger','bl_blog'); - if ($bl_username && $bl_password && $bl_blog) { + if($bl_username && $bl_password && $bl_blog) { require_once('include/bbcode.php'); @@ -199,10 +197,10 @@ EOT; logger('blogger: data: ' . $xml, LOGGER_DATA); - if ($bl_blog !== 'test') { + if($bl_blog !== 'test') $x = post_url($bl_blog,$xml); - } - logger('posted to blogger: ' . (($x) ? $x : ''), LOGGER_DEBUG); + } -} \ No newline at end of file +} + diff --git a/buffer/buffer.php b/buffer/buffer.php index b90d9090..ca33708c 100644 --- a/buffer/buffer.php +++ b/buffer/buffer.php @@ -5,11 +5,7 @@ * Version: 0.2 * Author: Michael Vogel */ -require 'addon/buffer/bufferapp.php'; - -use Friendica\App; -use Friendica\Core\Config; -use Friendica\Core\PConfig; +require('addon/buffer/bufferapp.php'); function buffer_install() { register_hook('post_local', 'addon/buffer/buffer.php', 'buffer_post_local'); @@ -57,18 +53,18 @@ function buffer_content(&$a) { function buffer_plugin_admin(&$a, &$o){ $t = get_markup_template( "admin.tpl", "addon/buffer/" ); - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Save Settings'), // name, label, value, help, [extra values] - '$client_id' => ['client_id', t('Client ID'), Config::get('buffer', 'client_id' ), ''], - '$client_secret' => ['client_secret', t('Client Secret'), Config::get('buffer', 'client_secret' ), ''], - ]); + '$client_id' => array('client_id', t('Client ID'), get_config('buffer', 'client_id' ), ''), + '$client_secret' => array('client_secret', t('Client Secret'), get_config('buffer', 'client_secret' ), ''), + )); } function buffer_plugin_admin_post(&$a){ $client_id = ((x($_POST,'client_id')) ? notags(trim($_POST['client_id'])) : ''); $client_secret = ((x($_POST,'client_secret')) ? notags(trim($_POST['client_secret'])): ''); - Config::set('buffer','client_id',$client_id); - Config::set('buffer','client_secret',$client_secret); + set_config('buffer','client_id',$client_id); + set_config('buffer','client_secret',$client_secret); info( t('Settings updated.'). EOL ); } @@ -82,8 +78,8 @@ function buffer_connect(&$a) { session_start(); // Define the needed keys - $client_id = Config::get('buffer','client_id'); - $client_secret = Config::get('buffer','client_secret'); + $client_id = get_config('buffer','client_id'); + $client_secret = get_config('buffer','client_secret'); // The callback URL is the script that gets called after the user authenticates with buffer $callback_url = $a->get_baseurl()."/buffer/connect"; @@ -96,7 +92,7 @@ function buffer_connect(&$a) { logger("buffer_connect: authenticated"); $o .= t("You are now authenticated to buffer. "); $o .= '
'.t("return to the connector page").''; - PConfig::set(local_user(), 'buffer','access_token', $buffer->access_token); + set_pconfig(local_user(), 'buffer','access_token', $buffer->access_token); } return($o); @@ -106,9 +102,9 @@ function buffer_jot_nets(&$a,&$b) { if(! local_user()) return; - $buffer_post = PConfig::get(local_user(),'buffer','post'); + $buffer_post = get_pconfig(local_user(),'buffer','post'); if(intval($buffer_post) == 1) { - $buffer_defpost = PConfig::get(local_user(),'buffer','post_by_default'); + $buffer_defpost = get_pconfig(local_user(),'buffer','post_by_default'); $selected = ((intval($buffer_defpost) == 1) ? ' checked="checked" ' : ''); $b .= '
' . t('Post to Buffer') . '
'; @@ -126,11 +122,11 @@ function buffer_settings(&$a,&$s) { /* Get the current state of our config variables */ - $enabled = PConfig::get(local_user(),'buffer','post'); + $enabled = get_pconfig(local_user(),'buffer','post'); $checked = (($enabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); - $def_enabled = PConfig::get(local_user(),'buffer','post_by_default'); + $def_enabled = get_pconfig(local_user(),'buffer','post_by_default'); $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); /* Add some HTML to the existing form */ @@ -143,9 +139,9 @@ function buffer_settings(&$a,&$s) { $s .= '

'. t('Buffer Export').'

'; $s .= ''; - $client_id = Config::get("buffer", "client_id"); - $client_secret = Config::get("buffer", "client_secret"); - $access_token = PConfig::get(local_user(), "buffer", "access_token"); + $client_id = get_config("buffer", "client_id"); + $client_secret = get_config("buffer", "client_secret"); + $access_token = get_pconfig(local_user(), "buffer", "access_token"); $s .= '
'; if ($access_token == "") { @@ -202,12 +198,12 @@ function buffer_settings_post(&$a,&$b) { if(x($_POST,'buffer-submit')) { if(x($_POST,'buffer_delete')) { - PConfig::set(local_user(),'buffer','access_token',''); - PConfig::set(local_user(),'buffer','post',false); - PConfig::set(local_user(),'buffer','post_by_default',false); + set_pconfig(local_user(),'buffer','access_token',''); + set_pconfig(local_user(),'buffer','post',false); + set_pconfig(local_user(),'buffer','post_by_default',false); } else { - PConfig::set(local_user(),'buffer','post',intval($_POST['buffer'])); - PConfig::set(local_user(),'buffer','post_by_default',intval($_POST['buffer_bydefault'])); + set_pconfig(local_user(),'buffer','post',intval($_POST['buffer'])); + set_pconfig(local_user(),'buffer','post_by_default',intval($_POST['buffer_bydefault'])); } } } @@ -218,11 +214,11 @@ function buffer_post_local(&$a,&$b) { return; } - $buffer_post = intval(PConfig::get(local_user(),'buffer','post')); + $buffer_post = intval(get_pconfig(local_user(),'buffer','post')); $buffer_enable = (($buffer_post && x($_REQUEST,'buffer_enable')) ? intval($_REQUEST['buffer_enable']) : 0); - if ($b['api_source'] && intval(PConfig::get(local_user(),'buffer','post_by_default'))) { + if ($b['api_source'] && intval(get_pconfig(local_user(),'buffer','post_by_default'))) { $buffer_enable = 1; } @@ -237,34 +233,24 @@ function buffer_post_local(&$a,&$b) { $b['postopts'] .= 'buffer'; } -function buffer_send(App $a, &$b) -{ - if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { - return; - } +function buffer_send(&$a,&$b) { - if(! strstr($b['postopts'],'buffer')) { + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) return; - } - if($b['parent'] != $b['id']) { + if(! strstr($b['postopts'],'buffer')) return; - } - // Dont't post if the post doesn't belong to us. - // This is a check for forum postings - $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]); - if ($b['contact-id'] != $self['id']) { + if($b['parent'] != $b['id']) return; - } // if post comes from buffer don't send it back //if($b['app'] == "Buffer") // return; - $client_id = Config::get("buffer", "client_id"); - $client_secret = Config::get("buffer", "client_secret"); - $access_token = PConfig::get($b['uid'], "buffer","access_token"); + $client_id = get_config("buffer", "client_id"); + $client_secret = get_config("buffer", "client_secret"); + $access_token = get_pconfig($b['uid'], "buffer","access_token"); if($access_token) { $buffer = new BufferApp($client_id, $client_secret, $callback_url, $access_token); @@ -306,7 +292,7 @@ function buffer_send(App $a, &$b) break; case 'twitter': $send = ($b["extid"] != NETWORK_TWITTER); - $limit = 280; + $limit = 140; $markup = false; $includedlinks = true; $htmlmode = 8; @@ -335,7 +321,7 @@ function buffer_send(App $a, &$b) $item["body"] = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$item["body"]); } - $post = plaintext($item, $limit, $includedlinks, $htmlmode); + $post = plaintext($a, $item, $limit, $includedlinks, $htmlmode); logger("buffer_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG); // The image proxy is used as a sanitizer. Buffer seems to be really picky about pictures @@ -369,7 +355,7 @@ function buffer_send(App $a, &$b) elseif ($profile->service == "google") $post["text"] .= html_entity_decode(" ", ENT_QUOTES, 'UTF-8'); // Send a special blank to identify the post through the "fromgplus" addon - $message = []; + $message = array(); $message["text"] = $post["text"]; $message["profile_ids[]"] = $profile->id; $message["shorten"] = false; diff --git a/buffer/bufferapp.php b/buffer/bufferapp.php index a222b23e..7215175d 100644 --- a/buffer/bufferapp.php +++ b/buffer/bufferapp.php @@ -12,7 +12,7 @@ public $ok = false; - private $endpoints = [ + private $endpoints = array( '/user' => 'get', '/profiles' => 'get', @@ -37,9 +37,9 @@ '/info/configuration' => 'get', - ]; + ); - public $errors = [ + public $errors = array( 'invalid-endpoint' => 'The endpoint you supplied does not appear to be valid.', '403' => 'Permission denied.', @@ -77,7 +77,7 @@ '1042' => 'User did not save successfully.', '1050' => 'Client could not be found.', '1051' => 'No authorization to access client.', - ]; + ); function __construct($client_id = '', $client_secret = '', $callback_url = '', $access_token = '') { if ($client_id) $this->set_client_id($client_id); @@ -110,7 +110,7 @@ if (!$ok) return $this->error('invalid-endpoint'); } - if (!$data || !is_array($data)) $data = []; + if (!$data || !is_array($data)) $data = array(); $data['access_token'] = $this->access_token; $method = $this->endpoints[$done_endpoint]; //get() or post() @@ -130,17 +130,17 @@ } function error($error) { - return (object) ['error' => $this->errors[$error]]; + return (object) array('error' => $this->errors[$error]); } function create_access_token_url() { - $data = [ + $data = array( 'code' => $this->code, 'grant_type' => 'authorization_code', 'client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'redirect_uri' => $this->callback_url, - ]; + ); $obj = $this->post($this->access_token_url, $data); $this->access_token = $obj->access_token; @@ -150,15 +150,15 @@ function req($url = '', $data = '', $post = true) { if (!$url) return false; - if (!$data || !is_array($data)) $data = []; + if (!$data || !is_array($data)) $data = array(); - $options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false]; + $options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false); if ($post) { - $options += [ + $options += array( CURLOPT_POST => $post, CURLOPT_POSTFIELDS => $data - ]; + ); } else { $url .= '?' . http_build_query($data); } diff --git a/cal/LICENSE b/cal/LICENSE new file mode 100644 index 00000000..2c696e9a --- /dev/null +++ b/cal/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013 Tobias Diekershoff + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/cal/README.md b/cal/README.md new file mode 100644 index 00000000..cb7501cd --- /dev/null +++ b/cal/README.md @@ -0,0 +1,29 @@ +Calendar Export +=============== + +This addon makes it possible to export the events posted by your users, +so they can be imported into other calendar applications. + +Exporting a calendar is an _opt-in_ feature which has to be activated by each +of the users in the _addon settings_. As the admin you can only provide the +service but should not force it upon your users. + +The calendars are exported at + + http://example.com/cal/username/export/format + +currently the following formats are supported + +* ical +* csv. + +Author +------ + +This addon is developed by [Tobias Diekershoff](https://f.diekershoff.de/profile/tobias). + +License +------- + +This addon is licensed under the [MIT](http://opensource.org/licenses/MIT) +license, see also the LICENSE file in the addon directory. diff --git a/cal/cal.php b/cal/cal.php new file mode 100644 index 00000000..5c2f1021 --- /dev/null +++ b/cal/cal.php @@ -0,0 +1,200 @@ + + * License: MIT + * Status: Unsupported + * ******************************************************************/ + + +function cal_install() +{ + register_hook('plugin_settings', 'addon/cal/cal.php', 'cal_addon_settings'); + register_hook('plugin_settings_post', 'addon/cal/cal.php', 'cal_addon_settings_post'); +} +function cal_uninstall() +{ + unregister_hook('plugin_settings', 'addon/cal/cal.php', 'cal_addon_settings'); + unregister_hook('plugin_settings_post', 'addon/cal/cal.php', 'cal_addon_settings_post'); +} +function cal_module() +{ +} +/* pathes + * /cal/$user/export/$format + * currently supported formats are ical (iCalendar) and CSV + */ +function cal_content() +{ + $a = get_app(); + $o = ""; + if ($a->argc == 1) { + $o .= "

".t('Event Export')."

".t('You can download public events from: ').$a->get_baseurl()."/cal/username/export/ical

"; + } elseif ($a->argc==4) { + // get the parameters from the request we just received + $username = $a->argv[1]; + $do = $a->argv[2]; + $format = $a->argv[3]; + // check that there is a user matching the requested profile + $r = q("SELECT uid FROM user WHERE nickname='".$username."' LIMIT 1;"); + if (count($r)) + { + $uid = $r[0]['uid']; + } else { + killme(); + } + // if we shall do anything other then export, end here + if (! $do == 'export' ) + killme(); + // check if the user allows us to share the profile + $enable = get_pconfig( $uid, 'cal', 'enable'); + if (! $enable == 1) { + info(t('The user does not export the calendar.')); + return; + } + // we are allowed to show events + // get the timezone the user is in + $r = q("SELECT timezone FROM user WHERE uid=".$uid." LIMIT 1;"); + if (count($r)) + $timezone = $r[0]['timezone']; + // does the user who requests happen to be the owner of the events + // requested? then show all of your events, otherwise only those that + // don't have limitations set in allow_cid and allow_gid + if (local_user() == $uid) { + $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location` FROM `event` WHERE `uid`=".$uid." and `cid`=0;"); + } else { + $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location` FROM `event` WHERE `allow_cid`='' and `allow_gid`='' and `uid`='".$uid."' and `cid`='0';"); + } + // we have the events that are available for the requestor + // now format the output according to the requested format + $res = cal_format_output($r, $format, $timezone); + if (! $res=='') + info($res); + } else { + // wrong number of parameters + killme(); + } + return $o; +} + +function cal_format_output ($r, $f, $tz) +{ + $res = t('This calendar format is not supported'); + switch ($f) + { + // format the exported data as a CSV file + case "csv": + header("Content-type: text/csv"); + $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL; + foreach ($r as $rr) { +// TODO the time / date entries don't include any information about the +// timezone the event is scheduled in :-/ + $tmp1 = strtotime($rr['start']); + $tmp2 = strtotime($rr['finish']); + $time_format = "%H:%M:%S"; + $date_format = "%Y-%m-%d"; + $o .= '"'.$rr['summary'].'", "'.strftime($date_format, $tmp1) . + '", "'.strftime($time_format, $tmp1).'", "'.$rr['desc'] . + '", "'.strftime($date_format, $tmp2) . + '", "'.strftime($time_format, $tmp2) . + '", "'.$rr['location'].'"' . PHP_EOL; + } + echo $o; + killme(); + + case "ical": + header("Content-type: text/ics"); + $o = 'BEGIN:VCALENDAR'. PHP_EOL + . 'VERSION:2.0' . PHP_EOL + . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL; +// TODO include timezone informations in cases were the time is not in UTC +// see http://tools.ietf.org/html/rfc2445#section-4.8.3 +// . 'BEGIN:VTIMEZONE' . PHP_EOL +// . 'TZID:' . $tz . PHP_EOL +// . 'END:VTIMEZONE' . PHP_EOL; +// TODO instead of PHP_EOL CRLF should be used for long entries +// but test your solution against http://icalvalid.cloudapp.net/ +// also long lines SHOULD be split at 75 characters length + foreach ($r as $rr) { + if ($rr['adjust'] == 1) { + $UTC = 'Z'; + } else { + $UTC = ''; + } + $o .= 'BEGIN:VEVENT' . PHP_EOL; + if ($rr[start]) { + $tmp = strtotime($rr['start']); + $dtformat = "%Y%m%dT%H%M%S".$UTC; + $o .= 'DTSTART:'.strftime($dtformat, $tmp).PHP_EOL; + } + if ($rr['finish']) { + $tmp = strtotime($rr['finish']); + $dtformat = "%Y%m%dT%H%M%S".$UTC; + $o .= 'DTEND:'.strftime($dtformat, $tmp).PHP_EOL; + } + if ($rr['summary']) + $tmp = $rr['summary']; + $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp); + $tmp = addcslashes($tmp, ',;'); + $o .= 'SUMMARY:' . $tmp . PHP_EOL; + if ($rr['desc']) + $tmp = $rr['desc']; + $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp); + $tmp = addcslashes($tmp, ',;'); + $o .= 'DESCRIPTION:' . $tmp . PHP_EOL; + if ($rr['location']) { + $tmp = $rr['location']; + $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp); + $tmp = addcslashes($tmp, ',;'); + $o .= 'LOCATION:' . $tmp . PHP_EOL; + } + $o .= 'END:VEVENT' . PHP_EOL; + } + $o .= 'END:VCALENDAR' . PHP_EOL; + echo $o; + killme(); + } + return $res; +} + +function cal_addon_settings_post ( &$a, &$b ) +{ + if (! local_user()) + return; + + if (!x($_POST,'cal-submit')) + return; + + set_pconfig(local_user(),'cal','enable',intval($_POST['cal-enable'])); +} +function cal_addon_settings ( &$a, &$s ) +{ + if (! local_user()) + return; + + $enabled = get_pconfig(local_user(), 'cal', 'enable'); + $checked = (($enabled) ? ' checked="checked" ' : ''); + $url = $a->get_baseurl().'/cal/'.$a->user['nickname'].'/export/format'; + + $s .= ''; + $s .= '

'.t('Export Events').'

'; + $s .= '
'; + $s .= ''; +} + +?> diff --git a/cal/lang/C/messages.po b/cal/lang/C/messages.po new file mode 100644 index 00000000..91883299 --- /dev/null +++ b/cal/lang/C/messages.po @@ -0,0 +1,54 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "" + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "" + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "" + +#: cal.php:193 +msgid "Save Settings" +msgstr "" diff --git a/cal/lang/C/strings.php b/cal/lang/C/strings.php new file mode 100644 index 00000000..a72dc119 --- /dev/null +++ b/cal/lang/C/strings.php @@ -0,0 +1,12 @@ +strings["Event Export"] = ""; +$a->strings["You can download public events from: "] = ""; +$a->strings["The user does not export the calendar."] = ""; +$a->strings["This calendar format is not supported"] = ""; +$a->strings["Export Events"] = ""; +$a->strings["If this is enabled, your public events will be available at"] = ""; +$a->strings["Currently supported formats are ical and csv."] = ""; +$a->strings["Enable calendar export"] = ""; +$a->strings["Submit"] = ""; diff --git a/cal/lang/cs/messages.po b/cal/lang/cs/messages.po new file mode 100644 index 00000000..28fcb4f9 --- /dev/null +++ b/cal/lang/cs/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# Michal Šupler , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2014-09-07 11:04+0000\n" +"Last-Translator: Michal Šupler \n" +"Language-Team: Czech (http://www.transifex.com/projects/p/friendica/language/cs/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: cs\n" +"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Export událostí" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Veřejné události si můžete stánout z:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "Uživatel kalenář neexportuje." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Tento kalendářový formát není podporován." + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Export událostí" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Pokud je toto povoleno, vaše veřejné události budou viditelné na" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Aktuálně podporované formáty jsou ical a csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Povolit export kalendáře" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Uložit Nastavení" diff --git a/cal/lang/cs/strings.php b/cal/lang/cs/strings.php new file mode 100644 index 00000000..9a99079d --- /dev/null +++ b/cal/lang/cs/strings.php @@ -0,0 +1,16 @@ +=2 && $n<=4) ? 1 : 2;; +}} +; +$a->strings["Event Export"] = "Export událostí"; +$a->strings["You can download public events from: "] = "Veřejné události si můžete stánout z:"; +$a->strings["The user does not export the calendar."] = "Uživatel kalenář neexportuje."; +$a->strings["This calendar format is not supported"] = "Tento kalendářový formát není podporován."; +$a->strings["Export Events"] = "Export událostí"; +$a->strings["If this is enabled, your public events will be available at"] = "Pokud je toto povoleno, vaše veřejné události budou viditelné na"; +$a->strings["Currently supported formats are ical and csv."] = "Aktuálně podporované formáty jsou ical a csv."; +$a->strings["Enable calendar export"] = "Povolit export kalendáře"; +$a->strings["Save Settings"] = "Uložit Nastavení"; diff --git a/cal/lang/de/messages.po b/cal/lang/de/messages.po new file mode 100644 index 00000000..29f6b601 --- /dev/null +++ b/cal/lang/de/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# bavatar , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2014-09-28 10:39+0000\n" +"Last-Translator: bavatar \n" +"Language-Team: German (http://www.transifex.com/projects/p/friendica/language/de/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: de\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Ereignis Export" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Du kannst öffentliche Ereignisse hier herunterladen;" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "Diese_r Nutzer_in exportiert den Kalender nicht." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Dieses Kalenderformat wird nicht unterstützt." + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Exportiere Ereignisse" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Wenn dies aktiviert ist, werden alle öffentliche Ereignisse unter folgender URL verfügbar sein" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Derzeit werden die Formate ical und csv unterstützt." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Kalenderexport aktivieren" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Einstellungen speichern" diff --git a/cal/lang/de/strings.php b/cal/lang/de/strings.php new file mode 100644 index 00000000..39359271 --- /dev/null +++ b/cal/lang/de/strings.php @@ -0,0 +1,16 @@ +strings["Event Export"] = "Ereignis Export"; +$a->strings["You can download public events from: "] = "Du kannst öffentliche Ereignisse hier herunterladen;"; +$a->strings["The user does not export the calendar."] = "Diese_r Nutzer_in exportiert den Kalender nicht."; +$a->strings["This calendar format is not supported"] = "Dieses Kalenderformat wird nicht unterstützt."; +$a->strings["Export Events"] = "Exportiere Ereignisse"; +$a->strings["If this is enabled, your public events will be available at"] = "Wenn dies aktiviert ist, werden alle öffentliche Ereignisse unter folgender URL verfügbar sein"; +$a->strings["Currently supported formats are ical and csv."] = "Derzeit werden die Formate ical und csv unterstützt."; +$a->strings["Enable calendar export"] = "Kalenderexport aktivieren"; +$a->strings["Save Settings"] = "Einstellungen speichern"; diff --git a/cal/lang/es/messages.po b/cal/lang/es/messages.po new file mode 100644 index 00000000..65b2a322 --- /dev/null +++ b/cal/lang/es/messages.po @@ -0,0 +1,55 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2016-10-10 20:48+0000\n" +"Last-Translator: Athalbert\n" +"Language-Team: Spanish (http://www.transifex.com/Friendica/friendica/language/es/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: es\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Exportación de evento" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Puede descargar eventos públicos desde:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "El usuario no exporta el calendario." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "No se soporta este formato de calendario" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Exportar Eventos" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Si esto está habilitado, sus eventos públicos estarán permitidos en" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Los formatos soportados actualmente son ical y csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Habilitar exportar calendario" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Guardar Ajustes" diff --git a/cal/lang/es/strings.php b/cal/lang/es/strings.php new file mode 100644 index 00000000..29c9cc93 --- /dev/null +++ b/cal/lang/es/strings.php @@ -0,0 +1,16 @@ +strings["Event Export"] = "Exportación de evento"; +$a->strings["You can download public events from: "] = "Puede descargar eventos públicos desde:"; +$a->strings["The user does not export the calendar."] = "El usuario no exporta el calendario."; +$a->strings["This calendar format is not supported"] = "No se soporta este formato de calendario"; +$a->strings["Export Events"] = "Exportar Eventos"; +$a->strings["If this is enabled, your public events will be available at"] = "Si esto está habilitado, sus eventos públicos estarán permitidos en"; +$a->strings["Currently supported formats are ical and csv."] = "Los formatos soportados actualmente son ical y csv."; +$a->strings["Enable calendar export"] = "Habilitar exportar calendario"; +$a->strings["Save Settings"] = "Guardar Ajustes"; diff --git a/cal/lang/fr/messages.po b/cal/lang/fr/messages.po new file mode 100644 index 00000000..1b33c119 --- /dev/null +++ b/cal/lang/fr/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# Tubuntu , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2014-09-07 09:24+0000\n" +"Last-Translator: Tubuntu \n" +"Language-Team: French (http://www.transifex.com/projects/p/friendica/language/fr/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: fr\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Exportation d'événement" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Vous pouvez télécharger les événements publiques de :" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "L'utilisateur n'exporte pas le calendrier." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Ce format de calendrier n'est pas pris en charge" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Exporter les événements" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Si activé, vos événements publiques seront disponible à" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Les formats actuellement pris en charge sont ical et csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Activer l'export de calendrier" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Sauvegarder les paramètres" diff --git a/cal/lang/fr/strings.php b/cal/lang/fr/strings.php new file mode 100644 index 00000000..b3517062 --- /dev/null +++ b/cal/lang/fr/strings.php @@ -0,0 +1,16 @@ + 1);; +}} +; +$a->strings["Event Export"] = "Exportation d'événement"; +$a->strings["You can download public events from: "] = "Vous pouvez télécharger les événements publiques de :"; +$a->strings["The user does not export the calendar."] = "L'utilisateur n'exporte pas le calendrier."; +$a->strings["This calendar format is not supported"] = "Ce format de calendrier n'est pas pris en charge"; +$a->strings["Export Events"] = "Exporter les événements"; +$a->strings["If this is enabled, your public events will be available at"] = "Si activé, vos événements publiques seront disponible à"; +$a->strings["Currently supported formats are ical and csv."] = "Les formats actuellement pris en charge sont ical et csv."; +$a->strings["Enable calendar export"] = "Activer l'export de calendrier"; +$a->strings["Save Settings"] = "Sauvegarder les paramètres"; diff --git a/cal/lang/it/messages.po b/cal/lang/it/messages.po new file mode 100644 index 00000000..f2aa1cbb --- /dev/null +++ b/cal/lang/it/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# fabrixxm , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2014-09-10 10:30+0000\n" +"Last-Translator: fabrixxm \n" +"Language-Team: Italian (http://www.transifex.com/Friendica/friendica/language/it/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: it\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Esporta Evento" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Puoi scaricare gli eventi publici da:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "L'utente non esporta il calendario." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Il formato del calendario non è supportato" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Esporta Eventi" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Se abilitato, i tuoi eventi pubblici saranno disponibili a" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "I formati supportati sono ical e csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Abilita esporazione calendario" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Salva Impostazioni" diff --git a/cal/lang/it/strings.php b/cal/lang/it/strings.php new file mode 100644 index 00000000..c7f228bb --- /dev/null +++ b/cal/lang/it/strings.php @@ -0,0 +1,16 @@ +strings["Event Export"] = "Esporta Evento"; +$a->strings["You can download public events from: "] = "Puoi scaricare gli eventi publici da:"; +$a->strings["The user does not export the calendar."] = "L'utente non esporta il calendario."; +$a->strings["This calendar format is not supported"] = "Il formato del calendario non è supportato"; +$a->strings["Export Events"] = "Esporta Eventi"; +$a->strings["If this is enabled, your public events will be available at"] = "Se abilitato, i tuoi eventi pubblici saranno disponibili a"; +$a->strings["Currently supported formats are ical and csv."] = "I formati supportati sono ical e csv."; +$a->strings["Enable calendar export"] = "Abilita esporazione calendario"; +$a->strings["Save Settings"] = "Salva Impostazioni"; diff --git a/cal/lang/pt-br/messages.po b/cal/lang/pt-br/messages.po new file mode 100644 index 00000000..7defc7d5 --- /dev/null +++ b/cal/lang/pt-br/messages.po @@ -0,0 +1,57 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# John Brazil, 2015 +# Sérgio Lima , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2015-01-31 01:24+0000\n" +"Last-Translator: John Brazil\n" +"Language-Team: Portuguese (Brazil) (http://www.transifex.com/projects/p/friendica/language/pt_BR/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: pt_BR\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Exportar Evento" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Você pode baixar eventos públicos de:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "O usuário não exportou o calendário." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Esse formato de calendário não é suportado." + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Exporta Eventos" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Se isso estiver habiltiado, seus eventos públicos estarão disponíveis" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Os formatos disponíveis atualmente são ical e csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Habilite exportar calendário" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Salvar as Configurações" diff --git a/cal/lang/pt-br/strings.php b/cal/lang/pt-br/strings.php new file mode 100644 index 00000000..69e35ea5 --- /dev/null +++ b/cal/lang/pt-br/strings.php @@ -0,0 +1,16 @@ + 1);; +}} +; +$a->strings["Event Export"] = "Exportar Evento"; +$a->strings["You can download public events from: "] = "Você pode baixar eventos públicos de:"; +$a->strings["The user does not export the calendar."] = "O usuário não exportou o calendário."; +$a->strings["This calendar format is not supported"] = "Esse formato de calendário não é suportado."; +$a->strings["Export Events"] = "Exporta Eventos"; +$a->strings["If this is enabled, your public events will be available at"] = "Se isso estiver habiltiado, seus eventos públicos estarão disponíveis"; +$a->strings["Currently supported formats are ical and csv."] = "Os formatos disponíveis atualmente são ical e csv."; +$a->strings["Enable calendar export"] = "Habilite exportar calendário"; +$a->strings["Save Settings"] = "Salvar as Configurações"; diff --git a/cal/lang/ro/messages.po b/cal/lang/ro/messages.po new file mode 100644 index 00000000..c0cd3f87 --- /dev/null +++ b/cal/lang/ro/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# Doru DEACONU , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2014-11-27 14:13+0000\n" +"Last-Translator: Doru DEACONU \n" +"Language-Team: Romanian (Romania) (http://www.transifex.com/projects/p/friendica/language/ro_RO/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: ro_RO\n" +"Plural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1));\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Exportare Eveniment" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Puteți descărca evenimente publice de la:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "Utilizatorul nu își exportă calendarul." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Acest format de calendar nu este acceptat" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Exportați Evenimente" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Dacă este activat, evenimente dvs publice vor fi disponibile pe" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Formate acceptate în prezent sunt ical şi csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Activați exportarea calendarului" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Salvare Configurări" diff --git a/cal/lang/ro/strings.php b/cal/lang/ro/strings.php new file mode 100644 index 00000000..8e328e98 --- /dev/null +++ b/cal/lang/ro/strings.php @@ -0,0 +1,16 @@ +19)||(($n%100==0)&&($n!=0)))?2:1));; +}} +; +$a->strings["Event Export"] = "Exportare Eveniment"; +$a->strings["You can download public events from: "] = "Puteți descărca evenimente publice de la:"; +$a->strings["The user does not export the calendar."] = "Utilizatorul nu își exportă calendarul."; +$a->strings["This calendar format is not supported"] = "Acest format de calendar nu este acceptat"; +$a->strings["Export Events"] = "Exportați Evenimente"; +$a->strings["If this is enabled, your public events will be available at"] = "Dacă este activat, evenimente dvs publice vor fi disponibile pe"; +$a->strings["Currently supported formats are ical and csv."] = "Formate acceptate în prezent sunt ical şi csv."; +$a->strings["Enable calendar export"] = "Activați exportarea calendarului"; +$a->strings["Save Settings"] = "Salvare Configurări"; diff --git a/cal/lang/ru/messages.po b/cal/lang/ru/messages.po new file mode 100644 index 00000000..155cba8e --- /dev/null +++ b/cal/lang/ru/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# Stanislav N. , 2017 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2017-04-08 17:06+0000\n" +"Last-Translator: Stanislav N. \n" +"Language-Team: Russian (http://www.transifex.com/Friendica/friendica/language/ru/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: ru\n" +"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "Экспорт событий" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "Вы можете скачать публичные события из:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "Пользователь не экспортировал календарь." + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "Этот формат календарей не поддерживается" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "Экспорт событий" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "Если эта настройка включена, то ваши публичные события будут доступны на:" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "Текущие поддерживаемые форматы ical и csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "Включить экспорт календаря" + +#: cal.php:193 +msgid "Save Settings" +msgstr "Сохранить настройки" diff --git a/cal/lang/ru/strings.php b/cal/lang/ru/strings.php new file mode 100644 index 00000000..d2ab1418 --- /dev/null +++ b/cal/lang/ru/strings.php @@ -0,0 +1,16 @@ +=2 && $n%10<=4 && ($n%100<12 || $n%100>14) ? 1 : $n%10==0 || ($n%10>=5 && $n%10<=9) || ($n%100>=11 && $n%100<=14)? 2 : 3);; +}} +; +$a->strings["Event Export"] = "Экспорт событий"; +$a->strings["You can download public events from: "] = "Вы можете скачать публичные события из:"; +$a->strings["The user does not export the calendar."] = "Пользователь не экспортировал календарь."; +$a->strings["This calendar format is not supported"] = "Этот формат календарей не поддерживается"; +$a->strings["Export Events"] = "Экспорт событий"; +$a->strings["If this is enabled, your public events will be available at"] = "Если эта настройка включена, то ваши публичные события будут доступны на:"; +$a->strings["Currently supported formats are ical and csv."] = "Текущие поддерживаемые форматы ical и csv."; +$a->strings["Enable calendar export"] = "Включить экспорт календаря"; +$a->strings["Save Settings"] = "Сохранить настройки"; diff --git a/cal/lang/zh-cn/messages.po b/cal/lang/zh-cn/messages.po new file mode 100644 index 00000000..15f34a47 --- /dev/null +++ b/cal/lang/zh-cn/messages.po @@ -0,0 +1,56 @@ +# ADDON cal +# Copyright (C) +# This file is distributed under the same license as the Friendica cal addon package. +# +# +# Translators: +# mytbk , 2017 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-22 13:18+0200\n" +"PO-Revision-Date: 2017-10-02 05:52+0000\n" +"Last-Translator: mytbk \n" +"Language-Team: Chinese (China) (http://www.transifex.com/Friendica/friendica/language/zh_CN/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: zh_CN\n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#: cal.php:33 +msgid "Event Export" +msgstr "事件导出" + +#: cal.php:33 +msgid "You can download public events from: " +msgstr "你可以从这里下载公开事件:" + +#: cal.php:53 +msgid "The user does not export the calendar." +msgstr "这个用户没有导出日历。" + +#: cal.php:83 +msgid "This calendar format is not supported" +msgstr "不支持这个日历格式" + +#: cal.php:181 cal.php:185 +msgid "Export Events" +msgstr "导出事件" + +#: cal.php:189 +msgid "If this is enabled, your public events will be available at" +msgstr "如果这个被启用,你的公开事件会在" + +#: cal.php:190 +msgid "Currently supported formats are ical and csv." +msgstr "当前支持的格式是 ical 和 csv." + +#: cal.php:191 +msgid "Enable calendar export" +msgstr "启用日历导出" + +#: cal.php:193 +msgid "Save Settings" +msgstr "保存设置" diff --git a/cal/lang/zh-cn/strings.php b/cal/lang/zh-cn/strings.php new file mode 100644 index 00000000..e94fa51b --- /dev/null +++ b/cal/lang/zh-cn/strings.php @@ -0,0 +1,16 @@ +strings["Event Export"] = "事件导出"; +$a->strings["You can download public events from: "] = "你可以从这里下载公开事件:"; +$a->strings["The user does not export the calendar."] = "这个用户没有导出日历。"; +$a->strings["This calendar format is not supported"] = "不支持这个日历格式"; +$a->strings["Export Events"] = "导出事件"; +$a->strings["If this is enabled, your public events will be available at"] = "如果这个被启用,你的公开事件会在"; +$a->strings["Currently supported formats are ical and csv."] = "当前支持的格式是 ical 和 csv."; +$a->strings["Enable calendar export"] = "启用日历导出"; +$a->strings["Save Settings"] = "保存设置"; diff --git a/communityhome/communityhome.php b/communityhome/communityhome.php index 8364392b..ff3215d3 100644 --- a/communityhome/communityhome.php +++ b/communityhome/communityhome.php @@ -6,8 +6,6 @@ * Author: Fabio Comuni */ -use Friendica\Core\Config; -use Friendica\Module\Login; require_once('mod/community.php'); @@ -22,73 +20,37 @@ function communityhome_uninstall() { logger("removed communityhome"); } -function communityhome_getopts() { - return [ - 'hidelogin'=>t('Hide login form'), - 'showlastusers'=>t('Show last new users'), - 'showactiveusers'=>t('Show last active users'), - 'showlastphotos'=>t('Show last photos'), - 'showlastlike'=>t('Show last liked items'), - 'showcommunitystream'=>t('Show community stream') - ]; -} - -function communityhome_plugin_admin(&$a, &$o) { - $tpl = get_markup_template( 'settings.tpl', 'addon/communityhome/' ); - - $opts = communityhome_getopts(); - $ctx = [ - '$submit' => t("Submit"), - '$fields' => [], - ]; - foreach($opts as $k=>$v) { - $ctx['fields'][] = ['communityhome_'.$k, $v, Config::get('communityhome', $k)]; - } - $o = replace_macros($tpl, $ctx); -} - -function communityhome_plugin_admin_post(&$a,&$b) { - if(x($_POST,'communityhome-submit')) { - $opts = communityhome_getopts(); - foreach($opts as $k=>$v) { - Config::set('communityhome', $k, x($_POST,'communityhome_'.$k)); - } - } -} - - function communityhome_home(&$a, &$o){ // custom css $a->page['htmlhead'] .= ''; - if (!Config::get('communityhome','hidelogin')){ - $aside = [ + if (!get_config('communityhome','hidelogin')){ + $aside = array( '$tab_1' => t('Login'), '$tab_2' => t('OpenID'), - '$noOid' => Config::get('system','no_openid'), - ]; + '$noOid' => get_config('system','no_openid'), + ); // login form $aside['$login_title'] = t('Login'); - $aside['$login_form'] = Login::form($a->query_string, $a->config['register_policy'] == REGISTER_CLOSED ? false : true); - } else { - $aside = [ + $aside['$login_form'] = login(($a->config['register_policy'] == REGISTER_CLOSED) ? false : true); + } else + $aside = array( //'$tab_1' => t('Login'), //'$tab_2' => t('OpenID'), - //'$noOid' => Config::get('system','no_openid'), - ]; - } + //'$noOid' => get_config('system','no_openid'), + ); // last 12 users - if (Config::get('communityhome','showlastusers')){ + if (get_config('communityhome','showlastusers')===true){ $aside['$lastusers_title'] = t('Latest users'); - $aside['$lastusers_items'] = []; + $aside['$lastusers_items'] = array(); $sql_extra = ""; - $publish = (Config::get('system','publish_all') ? '' : " AND `publish` = 1 " ); + $publish = (get_config('system','publish_all') ? '' : " AND `publish` = 1 " ); $order = " ORDER BY `register_date` DESC "; $r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname` - FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` + FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 $sql_extra $order LIMIT %d , %d ", 0, 12 @@ -99,25 +61,25 @@ function communityhome_home(&$a, &$o){ $photo = 'thumb'; foreach($r as $rr) { $profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); - $entry = replace_macros($tpl,[ + $entry = replace_macros($tpl,array( '$id' => $rr['id'], '$profile_link' => $profile_link, - '$photo' => $rr[$photo], + '$photo' => $a->get_cached_avatar_image($rr[$photo]), '$alt_text' => $rr['name'], - ]); + )); $aside['$lastusers_items'][] = $entry; } } } // 12 most active users (by posts and contacts) // this query don't work on some mysql versions - if (Config::get('communityhome','showactiveusers')){ + if (get_config('communityhome','showactiveusers')===true){ $r = q("SELECT `uni`.`contacts`,`uni`.`items`, `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname` FROM (SELECT COUNT(*) as `contacts`, `uid` FROM `contact` WHERE `self`=0 GROUP BY `uid`) AS `con`, (SELECT COUNT(*) as `items`, `uid` FROM `item` WHERE `item`.`changed` > DATE(NOW() - INTERVAL 1 MONTH) AND `item`.`wall` = 1 GROUP BY `uid`) AS `ite`, ( - SELECT `contacts`,`items`,`ite`.`uid` FROM `con` RIGHT OUTER JOIN `ite` ON `con`.`uid`=`ite`.`uid` - UNION ALL + SELECT `contacts`,`items`,`ite`.`uid` FROM `con` RIGHT OUTER JOIN `ite` ON `con`.`uid`=`ite`.`uid` + UNION ALL SELECT `contacts`,`items`,`con`.`uid` FROM `con` LEFT OUTER JOIN `ite` ON `con`.`uid`=`ite`.`uid` ) AS `uni`, `user`, `profile` WHERE `uni`.`uid`=`user`.`uid` @@ -127,31 +89,31 @@ function communityhome_home(&$a, &$o){ LIMIT 0,10"); if($r && count($r)) { $aside['$activeusers_title'] = t('Most active users'); - $aside['$activeusers_items'] = []; + $aside['$activeusers_items'] = array(); $photo = 'thumb'; foreach($r as $rr) { $profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); - $entry = replace_macros($tpl,[ + $entry = replace_macros($tpl,array( '$id' => $rr['id'], '$profile_link' => $profile_link, '$photo' => $rr[$photo], - '$photo_user' => sprintf("%s (%s posts, %s contacts)",$rr['name'], ($rr['items']?$rr['items']:'0'), ($rr['contacts']?$rr['contacts']:'0')) - ]); + '$alt_text' => sprintf("%s (%s posts, %s contacts)",$rr['name'], ($rr['items']?$rr['items']:'0'), ($rr['contacts']?$rr['contacts']:'0')) + )); $aside['$activeusers_items'][] = $entry; } } } // last 12 photos - if (Config::get('communityhome','showlastphotos')){ + if (get_config('communityhome','showlastphotos')===true){ $aside['$photos_title'] = t('Latest photos'); - $aside['$photos_items'] = []; - $r = q("SELECT `photo`.`id`, `photo`.`resource-id`, `photo`.`scale`, `photo`.`desc`, `user`.`nickname`, `user`.`username` FROM - (SELECT `resource-id`, MAX(`scale`) as maxscale FROM `photo` + $aside['$photos_items'] = array(); + $r = q("SELECT `photo`.`id`, `photo`.`resource-id`, `photo`.`scale`, `photo`.`desc`, `user`.`nickname`, `user`.`username` FROM + (SELECT `resource-id`, MAX(`scale`) as maxscale FROM `photo` WHERE `profile`=0 AND `contact-id`=0 AND `album` NOT IN ('Contact Photos', '%s', 'Profile Photos', '%s') AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`='' GROUP BY `resource-id`) AS `t1` INNER JOIN `photo` ON `photo`.`resource-id`=`t1`.`resource-id` AND `photo`.`scale` = `t1`.`maxscale`, - `user` + `user` WHERE `user`.`uid` = `photo`.`uid` AND `user`.`blockwall`=0 AND `user`.`hidewall` = 0 @@ -169,13 +131,12 @@ function communityhome_home(&$a, &$o){ $photo_page = $a->get_baseurl() . '/photos/' . $rr['nickname'] . '/image/' . $rr['resource-id']; $photo_url = $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] .'.jpg'; - $entry = replace_macros($tpl,[ + $entry = replace_macros($tpl,array( '$id' => $rr['id'], '$profile_link' => $photo_page, '$photo' => $photo_url, - '$photo_user' => $rr['username'], - '$photo_title' => $rr['desc'] - ]); + '$alt_text' => $rr['username']." : ".$rr['desc'], + )); $aside['$photos_items'][] = $entry; } @@ -183,13 +144,13 @@ function communityhome_home(&$a, &$o){ } // last 10 liked items - if (Config::get('communityhome','showlastlike')){ + if (get_config('communityhome','showlastlike')===true){ $aside['$like_title'] = t('Latest likes'); - $aside['$like_items'] = []; - $r = q("SELECT `T1`.`created`, `T1`.`liker`, `T1`.`liker-link`, `item`.* FROM - (SELECT `parent-uri`, `created`, `author-name` AS `liker`,`author-link` AS `liker-link` + $aside['$like_items'] = array(); + $r = q("SELECT `T1`.`created`, `T1`.`liker`, `T1`.`liker-link`, `item`.* FROM + (SELECT `parent-uri`, `created`, `author-name` AS `liker`,`author-link` AS `liker-link` FROM `item` WHERE `verb`='http://activitystrea.ms/schema/1.0/like' GROUP BY `parent-uri` ORDER BY `created` DESC) AS T1 - INNER JOIN `item` ON `item`.`uri`=`T1`.`parent-uri` + INNER JOIN `item` ON `item`.`uri`=`T1`.`parent-uri` WHERE `T1`.`liker-link` LIKE '%s%%' OR `item`.`author-link` LIKE '%s%%' GROUP BY `uri` ORDER BY `T1`.`created` DESC @@ -215,7 +176,7 @@ function communityhome_home(&$a, &$o){ default: if ($rr['resource-id']){ $post_type = t('photo'); - $m=[]; preg_match("/\[url=([^]]*)\]/", $rr['body'], $m); + $m=array(); preg_match("/\[url=([^]]*)\]/", $rr['body'], $m); $rr['plink'] = $m[1]; } else { $post_type = t('status'); @@ -237,14 +198,14 @@ function communityhome_home(&$a, &$o){ if(file_exists('home.html')) $o = file_get_contents('home.html'); - if (Config::get('communityhome','showcommunitystream')){ - $oldset = Config::get('system','community_page_style'); + if (get_config('communityhome','showcommunitystream')===true){ + $oldset = get_config('system','community_page_style'); if ($oldset == CP_NO_COMMUNITY_PAGE) - Config::set('system','community_page_style', CP_USERS_ON_SERVER); + set_config('system','community_page_style', CP_USERS_ON_SERVER); $o .= community_content($a,1); if ($oldset == CP_NO_COMMUNITY_PAGE) - Config::set('system','community_page_style', $oldset); + set_config('system','community_page_style', $oldset); } } diff --git a/communityhome/templates/directory_item.tpl b/communityhome/templates/directory_item.tpl index 30512f4e..5fb11986 100644 --- a/communityhome/templates/directory_item.tpl +++ b/communityhome/templates/directory_item.tpl @@ -2,8 +2,8 @@
diff --git a/communityhome/templates/settings.tpl b/communityhome/templates/settings.tpl deleted file mode 100644 index d73ed74c..00000000 --- a/communityhome/templates/settings.tpl +++ /dev/null @@ -1,9 +0,0 @@ -
- {{foreach $fields as $field}} - {{include file="field_checkbox.tpl" field=$field}} - {{/foreach}} -
-
- -
- diff --git a/convert/convert.php b/convert/convert.php index 03b1e9d5..75131650 100644 --- a/convert/convert.php +++ b/convert/convert.php @@ -15,7 +15,7 @@ function convert_uninstall() { } function convert_app_menu($a,&$b) { - $b['app_menu'][] = ''; + $b['app_menu'][] = ''; } @@ -30,7 +30,7 @@ function convert_module() {} function convert_content($app) { include("UnitConvertor.php"); - + class TP_Converter extends UnitConvertor { function TP_Converter($lang = "en") { @@ -39,7 +39,7 @@ include("UnitConvertor.php"); } else { $dec_point = '.'; $thousand_sep = ","; } - + $this->UnitConvertor($dec_point , $thousand_sep ); } // end func UnitConvertor @@ -47,24 +47,24 @@ include("UnitConvertor.php"); function find_base_unit($from,$to) { while (list($skey,$sval) = each($this->bases)) { if ($skey == $from || $to == $skey || in_array($to,$sval) || in_array($from,$sval)) { - return $skey; + return $skey; } } - return false; + return false; } function getTable($value, $from_unit, $to_unit, $precision) { - + if ($base_unit = $this->find_base_unit($from_unit,$to_unit)) { - - // A baseunit was found now lets convert from -> $base_unit - - $cell ['value'] = $this->convert($value, $from_unit, $base_unit, $precision)." ".$base_unit; + + // A baseunit was found now lets convert from -> $base_unit + + $cell ['value'] = $this->convert($value, $from_unit, $base_unit, $precision)." ".$base_unit; $cell ['class'] = ($base_unit == $from_unit || $base_unit == $to_unit) ? "framedred": ""; $cells[] = $cell; // We now have the base unit and value now lets produce the table; while (list($key,$val) = each($this->bases[$base_unit])) { - $cell ['value'] = $this->convert($value, $from_unit, $val, $precision)." ".$val; + $cell ['value'] = $this->convert($value, $from_unit, $val, $precision)." ".$val; $cell ['class'] = ($val == $from_unit || $val == $to_unit) ? "framedred": ""; $cells[] = $cell; } @@ -83,8 +83,8 @@ include("UnitConvertor.php"); } $string .= ""; return $string; - } - + } + } } @@ -92,16 +92,16 @@ include("UnitConvertor.php"); $conv = new TP_Converter('en'); -$conversions = [ - 'Temperature'=>['base' =>'Celsius', - 'conv'=>[ - 'Fahrenheit'=>['ratio'=>1.8, 'offset'=>32], - 'Kelvin'=>['ratio'=>1, 'offset'=>273], +$conversions = array( + 'Temperature'=>array('base' =>'Celsius', + 'conv'=>array( + 'Fahrenheit'=>array('ratio'=>1.8, 'offset'=>32), + 'Kelvin'=>array('ratio'=>1, 'offset'=>273), 'Reaumur'=>0.8 - ] - ], - 'Weight' => ['base' =>'kg', - 'conv'=>[ + ) + ), + 'Weight' => array('base' =>'kg', + 'conv'=>array( 'g'=>1000, 'mg'=>1000000, 't'=>0.001, @@ -109,13 +109,13 @@ $conversions = [ 'oz'=>35.274, 'lb'=>2.2046, 'cwt(UK)' => 0.019684, - 'cwt(US)' => 0.022046, + 'cwt(US)' => 0.022046, 'ton (US)' => 0.0011023, 'ton (UK)' => 0.0009842 - ] - ], - 'Distance' => ['base' =>'km', - 'conv'=>[ + ) + ), + 'Distance' => array('base' =>'km', + 'conv'=>array( 'm'=>1000, 'dm'=>10000, 'cm'=>100000, @@ -127,25 +127,25 @@ $conversions = [ 'yd'=>1093.6, 'furlong'=>4.970969537898672, 'fathom'=>546.8066491688539 - ] - ], - 'Area' => ['base' =>'km 2', - 'conv'=>[ + ) + ), + 'Area' => array('base' =>'km 2', + 'conv'=>array( 'ha'=>100, 'acre'=>247.105, 'm 2'=>pow(1000,2), 'dm 2'=>pow(10000,2), 'cm 2'=>pow(100000,2), - 'mm 2'=>pow(1000000,2), + 'mm 2'=>pow(1000000,2), 'mile 2'=>pow(0.62137,2), 'naut.miles 2'=>pow(0.53996,2), 'in 2'=>pow(39370,2), 'ft 2'=>pow(3280.8,2), 'yd 2'=>pow(1093.6,2), - ] - ], - 'Volume' => ['base' =>'m 3', - 'conv'=>[ + ) + ), + 'Volume' => array('base' =>'m 3', + 'conv'=>array( 'in 3'=>61023.6, 'ft 3'=>35.315, 'cm 3'=>pow(10,6), @@ -161,22 +161,22 @@ $conversions = [ 'fl oz' => 33814.02, 'tablespoon' => 67628.04, 'teaspoon' => 202884.1, - 'pt (UK)'=>1000/0.56826, + 'pt (UK)'=>1000/0.56826, 'barrel petroleum'=>1000/158.99, - 'Register Tons'=>2.832, + 'Register Tons'=>2.832, 'Ocean Tons'=>1.1327 - ] - ], - 'Speed' =>['base' =>'kmph', - 'conv'=>[ + ) + ), + 'Speed' =>array('base' =>'kmph', + 'conv'=>array( 'mps'=>0.0001726031, 'milesph'=>0.62137, 'knots'=>0.53996, 'mach STP'=>0.0008380431, 'c (warp)'=>9.265669e-10 - ] - ] -]; + ) + ) +); while (list($key,$val) = each($conversions)) { @@ -223,6 +223,6 @@ while (list($key,$val) = each($conversions)) { $o .= ''; $o .= ''; - + return $o; } diff --git a/convpath/README b/convpath/README new file mode 100644 index 00000000..9d1c3072 --- /dev/null +++ b/convpath/README @@ -0,0 +1,7 @@ +convpath + +This addon converts all internal paths according to the current scheme. + +That means that if a page is called via https then all internal links are also converted into https. + +Same happens when you call your page with http. diff --git a/convpath/convpath.php b/convpath/convpath.php new file mode 100644 index 00000000..0aaeb5f9 --- /dev/null +++ b/convpath/convpath.php @@ -0,0 +1,102 @@ + + * Status: Unsupported + */ + +function convpath_install() { + register_hook('page_end', 'addon/convpath/convpath.php', 'convpath_page_end'); + register_hook('page_header', 'addon/convpath/convpath.php', 'convpath_page_header'); + register_hook('ping_xmlize', 'addon/convpath/convpath.php', 'convpath_ping_xmlize_hook'); + register_hook('prepare_body', 'addon/convpath/convpath.php', 'convpath_prepare_body_hook'); + register_hook('display_item', 'addon/convpath/convpath.php', 'convpath_display_item_hook'); +} + + +function convpath_uninstall() { + unregister_hook('page_end', 'addon/convpath/convpath.php', 'convpath_page_end'); + unregister_hook('page_header', 'addon/convpath/convpath.php', 'convpath_page_header'); + unregister_hook('ping_xmlize', 'addon/convpath/convpath.php', 'convpath_ping_xmlize_hook'); + unregister_hook('prepare_body', 'addon/convpath/convpath.php', 'convpath_prepare_body_hook'); + unregister_hook('display_item', 'addon/convpath/convpath.php', 'convpath_display_item_hook'); +} + +function convpath_ping_xmlize_hook(&$a, &$o) { + $o["photo"] = convpath_url($a, $o["photo"]); +} + +function convpath_page_header(&$a, &$o){ + $o = convpath_convert($o); +} + +function convpath_page_end(&$a, &$o){ + $o = convpath_convert($o); + if (isset($a->page['aside'])) + $a->page['aside'] = convpath_convert($a->page['aside']); +} + +function convpath_prepare_body_hook(&$a, &$o) { + $o["html"] = convpath_convert($o["html"]); +} + +function convpath_display_item_hook(&$a, &$o) { + if (isset($o["output"])) { + if (isset($o["output"]["thumb"])) + $o["output"]["thumb"] = convpath_url($a, $o["output"]["thumb"]); + if (isset($o["output"]["author-avatar"])) + $o["output"]["author-avatar"] = convpath_url($a, $o["output"]["author-avatar"]); + if (isset($o["output"]["owner-avatar"])) + $o["output"]["owner-avatar"] = convpath_url($a, $o["output"]["owner-avatar"]); + if (isset($o["output"]["owner_photo"])) + $o["output"]["owner_photo"] = convpath_url($a, $o["output"]["owner_photo"]); + } +} + +function convpath_url($a, $path) { + if ($path == "") + return(""); + + $ssl = (substr($a->get_baseurl(), 0, 8) == "https://"); + + if ($ssl) { + $search = "http://".$a->get_hostname(); + $replace = "https://".$a->get_hostname(); + } else { + $search = "https://".$a->get_hostname(); + $replace = "http://".$a->get_hostname(); + } + + $path = str_replace($search, $replace, $path); + + return($path); +} + +/* +Converts a given path according to the current scheme +*/ +function convpath_convert($path) { + global $a; + + if ($path == "") + return(""); + + $ssl = (substr($a->get_baseurl(), 0, 8) == "https://"); + + if ($ssl) { + $search = "http://".$a->get_hostname(); + $replace = "https://".$a->get_hostname(); + } else { + $search = "https://".$a->get_hostname(); + $replace = "http://".$a->get_hostname(); + } + $searcharr = array("src='".$search, 'src="'.$search); + $replacearr = array("src='".$replace, 'src="'.$replace); + $path = str_replace($searcharr, $replacearr, $path); + + //$path = str_replace($search, $replace, $path); + + return($path); +} diff --git a/convpath/lang/C/messages.po b/convpath/lang/C/messages.po new file mode 100644 index 00000000..e69de29b diff --git a/curweather/curweather.php b/curweather/curweather.php index 7b8b89e3..71d95e46 100644 --- a/curweather/curweather.php +++ b/curweather/curweather.php @@ -1,6 +1,6 @@ @@ -13,17 +13,13 @@ require_once('include/network.php'); require_once("mod/proxy.php"); require_once('include/text.php'); -use Friendica\Core\Cache; -use Friendica\Core\Config; -use Friendica\Core\PConfig; - // get the weather data from OpenWeatherMap function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) { $url = "http://api.openweathermap.org/data/2.5/weather?q=".$loc."&appid=".$appid."&lang=".$lang."&units=".$units."&mode=xml"; $cached = Cache::get('curweather'.md5($url)); $now = new DateTime(); if (!is_null($cached)) { - $cdate = PConfig::get(local_user(), 'curweather', 'last'); + $cdate = get_pconfig(local_user(), 'curweather', 'last'); $cached = unserialize($cached); if ($cdate + $cachetime > $now->getTimestamp()) { return $cached; @@ -47,7 +43,7 @@ function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) } else { $desc = (string)$res->weather['value'].', '.(string)$res->clouds['name']; } - $r = [ + $r = array( 'city'=> (string) $res->city['name'][0], 'country' => (string) $res->city->country[0], 'lat' => (string) $res->city->coord['lat'], @@ -59,8 +55,8 @@ function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) 'wind' => (string)$res->wind->speed['name'].' ('.(string)$res->wind->speed['value'].$wunit.')', 'update' => (string)$res->lastupdate['value'], 'icon' => (string)$res->weather['icon'] - ]; - PConfig::set(local_user(), 'curweather', 'last', $now->getTimestamp()); + ); + set_pconfig(local_user(), 'curweather', 'last', $now->getTimestamp()); Cache::set('curweather'.md5($url), serialize($r), CACHE_HOUR); return $r; } @@ -79,7 +75,7 @@ function curweather_uninstall() { function curweather_network_mod_init(&$fk_app,&$b) { - if(! intval(PConfig::get(local_user(),'curweather','curweather_enable'))) + if(! intval(get_pconfig(local_user(),'curweather','curweather_enable'))) return; $fk_app->page['htmlhead'] .= '' . "\r\n"; @@ -93,14 +89,14 @@ function curweather_network_mod_init(&$fk_app,&$b) { // those parameters will be used to get: cloud status, temperature, preassure // and relative humidity for display, also the relevent area of the map is // linked from lat/log of the reply of OWMp - $rpt = PConfig::get(local_user(), 'curweather', 'curweather_loc'); + $rpt = get_pconfig(local_user(), 'curweather', 'curweather_loc'); // set the language to the browsers language and use metric units $lang = $_SESSION['language']; - $units = PConfig::get( local_user(), 'curweather', 'curweather_units'); - $appid = Config::get('curweather','appid'); - $cachetime = intval(Config::get('curweather','cachetime')); + $units = get_pconfig( local_user(), 'curweather', 'curweather_units'); + $appid = get_config('curweather','appid'); + $cachetime = intval(get_config('curweather','cachetime')); if ($units==="") $units = 'metric'; $ok = true; @@ -111,7 +107,7 @@ function curweather_network_mod_init(&$fk_app,&$b) { if ($ok) { $t = get_markup_template("widget.tpl", "addon/curweather/" ); - $curweather = replace_macros ($t, [ + $curweather = replace_macros ($t, array( '$title' => t("Current Weather"), '$icon' => proxy_url('http://openweathermap.org/img/w/'.$res['icon'].'.png'), '$city' => $res['city'], @@ -119,20 +115,20 @@ function curweather_network_mod_init(&$fk_app,&$b) { '$lat' => $res['lat'], '$description' => $res['descripion'], '$temp' => $res['temperature'], - '$relhumidity' => ['caption'=>t('Relative Humidity'), 'val'=>$res['humidity']], - '$pressure' => ['caption'=>t('Pressure'), 'val'=>$res['pressure']], - '$wind' => ['caption'=>t('Wind'), 'val'=> $res['wind']], + '$relhumidity' => array('caption'=>t('Relative Humidity'), 'val'=>$res['humidity']), + '$pressure' => array('caption'=>t('Pressure'), 'val'=>$res['pressure']), + '$wind' => array('caption'=>t('Wind'), 'val'=> $res['wind']), '$lastupdate' => t('Last Updated').': '.$res['update'].'UTC', '$databy' => t('Data by'), '$showonmap' => t('Show on map') - ]); + )); } else { $t = get_markup_template('widget-error.tpl', 'addon/curweather/'); - $curweather = replace_macros( $t, [ + $curweather = replace_macros( $t, array( '$problem' => t('There was a problem accessing the weather data. But have a look'), '$rpt' => $rpt, '$atOWM' => t('at OpenWeatherMap') - ]); + )); } $fk_app->page['aside'] = $curweather.$fk_app->page['aside']; @@ -143,9 +139,9 @@ function curweather_network_mod_init(&$fk_app,&$b) { function curweather_plugin_settings_post($a,$post) { if(! local_user() || (! x($_POST,'curweather-settings-submit'))) return; - PConfig::set(local_user(),'curweather','curweather_loc',trim($_POST['curweather_loc'])); - PConfig::set(local_user(),'curweather','curweather_enable',intval($_POST['curweather_enable'])); - PConfig::set(local_user(),'curweather','curweather_units',trim($_POST['curweather_units'])); + set_pconfig(local_user(),'curweather','curweather_loc',trim($_POST['curweather_loc'])); + set_pconfig(local_user(),'curweather','curweather_enable',intval($_POST['curweather_enable'])); + set_pconfig(local_user(),'curweather','curweather_units',trim($_POST['curweather_units'])); info( t('Current Weather settings updated.') . EOL); } @@ -158,28 +154,28 @@ function curweather_plugin_settings(&$a,&$s) { /* Get the current state of our config variable */ - $curweather_loc = PConfig::get(local_user(), 'curweather', 'curweather_loc'); - $curweather_units = PConfig::get(local_user(), 'curweather', 'curweather_units'); - $appid = Config::get('curweather','appid'); - if ($appid=="") { + $curweather_loc = get_pconfig(local_user(), 'curweather', 'curweather_loc'); + $curweather_units = get_pconfig(local_user(), 'curweather', 'curweather_units'); + $appid = get_config('curweather','appid'); + if ($appid=="") { $noappidtext = t('No APPID found, please contact your admin to obtain one.'); } else { $noappidtext = ''; } - $enable = intval(PConfig::get(local_user(),'curweather','curweather_enable')); + $enable = intval(get_pconfig(local_user(),'curweather','curweather_enable')); $enable_checked = (($enable) ? ' checked="checked" ' : ''); - + // load template and replace the macros $t = get_markup_template("settings.tpl", "addon/curweather/" ); - $s = replace_macros ($t, [ - '$submit' => t('Save Settings'), + $s = replace_macros ($t, array( + '$submit' => t('Save Settings'), '$header' => t('Current Weather').' '.t('Settings'), '$noappidtext' => $noappidtext, '$info' => t('Enter either the name of your location or the zip code.'), - '$curweather_loc' => [ 'curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.') ], - '$curweather_units' => [ 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), ['metric'=>'°C', 'imperial'=>'°F']], - '$enabled' => [ 'curweather_enable', t('Show weather data'), $enable, ''] - ]); + '$curweather_loc' => array( 'curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.') ), + '$curweather_units' => array( 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), array('metric'=>'°C', 'imperial'=>'°F')), + '$enabled' => array( 'curweather_enable', t('Show weather data'), $enable, '') + )); return; } @@ -189,20 +185,20 @@ function curweather_plugin_admin_post (&$a) { if(! is_site_admin()) return; if ($_POST['curweather-submit']) { - Config::set('curweather','appid',trim($_POST['appid'])); - Config::set('curweather','cachetime',trim($_POST['cachetime'])); + set_config('curweather','appid',trim($_POST['appid'])); + set_config('curweather','cachetime',trim($_POST['cachetime'])); info( t('Curweather settings saved.'.EOL)); } } function curweather_plugin_admin (&$a, &$o) { if(! is_site_admin()) return; - $appid = Config::get('curweather','appid'); - $cachetime = Config::get('curweather','cachetime'); + $appid = get_config('curweather','appid'); + $cachetime = get_config('curweather','cachetime'); $t = get_markup_template("admin.tpl", "addon/curweather/" ); - $o = replace_macros ($t, [ + $o = replace_macros ($t, array( '$submit' => t('Save Settings'), - '$cachetime' => ['cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), ['0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes')]], - '$appid' => ['appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap')] - ]); + '$cachetime' => array('cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), array('0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes'))), + '$appid' => array('appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap')) + )); } diff --git a/curweather/templates/widget.tpl b/curweather/templates/widget.tpl index db3b7a8f..b893eef6 100644 --- a/curweather/templates/widget.tpl +++ b/curweather/templates/widget.tpl @@ -11,7 +11,7 @@
  • {{$wind['caption']}}: {{$wind['val']}}
  • diff --git a/dav/README.md b/dav/README.md index 7c2abdb8..a8243972 100644 --- a/dav/README.md +++ b/dav/README.md @@ -1,6 +1,4 @@ -# Calendar with CalDAV Support - -**THIS ADDON IS UNSUPPORTED** +Calendar with CalDAV Support This is a rewrite of the calendar system used by the german social network [Animexx](http://www.animexx.de/). It's still in a very early stage, so expect major bugs. Please feel free to report any of them, by mail (cato@animexx.de) or Friendica: http://friendica.hoessl.eu/profile/cato @@ -18,28 +16,28 @@ At the moment, the calendar system supports the following features: - The events of a calendar can be exported as ICS file. ICS files can be imported into a calendar -## Internationalization: +Internationalization: - At the moment, settings for the US and the german systems are selectable (regarding the date format and the first day of the week). More will be added on request. - The basic design of the system is aware of timezones; however this is not reflected in the UI yet. It currently assumes that the timezone set in the friendica-installation matches the user's local time and matches the local time set in the user's operating system. -## CalDAV device compatibility: +CalDAV device compatibility: - iOS (iPhone/iPodTouch) works - Thunderbird Lightning works - Android: - aCal (http://andrew.mcmillan.net.nz/projects/aCal) works, available in F-Droid and Google Play - CalDAV-Sync (http://dmfs.org/caldav/) works, non-free -## Installation +Installation After activating, serveral tables in the database have to be created. The admin-interface of the plugin will try to do this automatically. In case of errors, the SQL-statement to create the tables manually are shown in the admin-interface. -## Functuality missing: (a.k.a. "Roadmap") +Functuality missing: (a.k.a. "Roadmap") - Sharing events; all events are private at the moment, therefore this system is not a complete replacement for the friendica-native events - Attendees / Collaboration -## Used libraries +Used libraries SabreDAV http://code.google.com/p/sabredav/ diff --git a/dav/common/wdcal_configuration.php b/dav/common/wdcal_configuration.php index 337451cb..c7b66fb1 100644 --- a/dav/common/wdcal_configuration.php +++ b/dav/common/wdcal_configuration.php @@ -1,7 +1,5 @@ = 5.3. * Version: 0.3.0 * Author: Tobias Hößl - * Status: Unsupported */ $_v = explode(".", phpversion()); if ($_v[0] > 5 || ($_v[0] == 5 && $_v[1] >= 3)) { require(__DIR__ . "/friendica/main.php"); -} +} \ No newline at end of file diff --git a/dav/friendica/calendar.friendica.fnk.php b/dav/friendica/calendar.friendica.fnk.php index b5d9082e..60dd9c6b 100644 --- a/dav/friendica/calendar.friendica.fnk.php +++ b/dav/friendica/calendar.friendica.fnk.php @@ -16,13 +16,13 @@ define("CALDAV_NAMESPACE_PRIVATE", 1); define("CALDAV_FRIENDICA_MINE", "friendica-mine"); define("CALDAV_FRIENDICA_CONTACTS", "friendica-contacts"); -$GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"] = [CALDAV_FRIENDICA_MINE, CALDAV_FRIENDICA_CONTACTS]; -$GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] = ["Sabre_CalDAV_Backend_Friendica"]; +$GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"] = array(CALDAV_FRIENDICA_MINE, CALDAV_FRIENDICA_CONTACTS); +$GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CalDAV_Backend_Friendica"); define("CARDDAV_NAMESPACE_PRIVATE", 1); define("CARDDAV_FRIENDICA_CONTACT", "friendica"); -$GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"] = [CARDDAV_FRIENDICA_CONTACT]; -$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = ["Sabre_CardDAV_Backend_Friendica"]; +$GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"] = array(CARDDAV_FRIENDICA_CONTACT); +$GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] = array("Sabre_CardDAV_Backend_Friendica"); $GLOBALS["CALDAV_ACL_PLUGIN_CLASS"] = "Sabre_DAVACL_Plugin_Friendica"; @@ -106,7 +106,7 @@ function dav_compat_principal2namespace($principalUri = "") if (strpos($principalUri, "principals/users/") !== 0) return null; $username = substr($principalUri, strlen("principals/users/")); - return ["namespace" => CALDAV_NAMESPACE_PRIVATE, "namespace_id" => dav_compat_username2id($username)]; + return array("namespace" => CALDAV_NAMESPACE_PRIVATE, "namespace_id" => dav_compat_username2id($username)); } @@ -200,13 +200,13 @@ function wdcal_calendar_factory_by_id($calendar_id) */ function wdcal_create_std_calendars_get_statements($user_id, $withcheck = true) { - $stms = []; + $stms = array(); $a = get_app(); - $uris = [ + $uris = array( 'private' => t("Private Calendar"), CALDAV_FRIENDICA_MINE => t("Friendica Events: Mine"), CALDAV_FRIENDICA_CONTACTS => t("Friendica Events: Contacts"), - ]; + ); foreach ($uris as $uri => $name) { $cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($uri)); @@ -242,12 +242,12 @@ function wdcal_create_std_calendars() */ function wdcal_create_std_addressbooks_get_statements($user_id, $withcheck = true) { - $stms = []; + $stms = array(); $a = get_app(); - $uris = [ + $uris = array( 'private' => t("Private Addresses"), CARDDAV_FRIENDICA_CONTACT => t("Friendica Contacts"), - ]; + ); foreach ($uris as $uri => $name) { $cals = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, IntVal($user_id), dbesc($uri)); diff --git a/dav/friendica/database-init.inc.php b/dav/friendica/database-init.inc.php index d8ef96eb..e172b44d 100644 --- a/dav/friendica/database-init.inc.php +++ b/dav/friendica/database-init.inc.php @@ -7,7 +7,7 @@ */ function dav_get_update_statements($from_version) { - $stms = []; + $stms = array(); if ($from_version == 1) { $stms[] = "ALTER TABLE `dav_calendarobjects` @@ -30,7 +30,7 @@ function dav_get_update_statements($from_version) `dav_locks` , `dav_notifications` ;"; - $stms = array_merge($stms, dav_get_create_statements(["dav_calendarobjects"])); + $stms = array_merge($stms, dav_get_create_statements(array("dav_calendarobjects"))); $user_ids = q("SELECT DISTINCT `uid` FROM %s%scalendars", CALDAV_SQL_DB, CALDAV_SQL_PREFIX); foreach ($user_ids as $user) $stms = array_merge($stms, wdcal_create_std_calendars_get_statements($user["uid"], false)); @@ -43,7 +43,7 @@ function dav_get_update_statements($from_version) } - if (in_array($from_version, [1, 2])) { + if (in_array($from_version, array(1, 2))) { $stms[] = "CREATE TABLE IF NOT EXISTS `dav_addressbooks` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `namespace` mediumint(9) NOT NULL, @@ -80,9 +80,9 @@ function dav_get_update_statements($from_version) * @param array $except * @return array */ -function dav_get_create_statements($except = []) +function dav_get_create_statements($except = array()) { - $arr = []; + $arr = array(); if (!in_array("dav_caldav_log", $except)) $arr[] = "CREATE TABLE IF NOT EXISTS `dav_caldav_log` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, @@ -240,7 +240,7 @@ function dav_check_tables() function dav_create_tables() { $stms = dav_get_create_statements(); - $errors = []; + $errors = array(); foreach ($stms as $st) { // @TODO Friendica-dependent dba::e($st); @@ -258,10 +258,10 @@ function dav_create_tables() function dav_upgrade_tables() { $ver = dav_check_tables(); - if (!in_array($ver, [1, 2])) return ["Unknown error"]; + if (!in_array($ver, array(1, 2))) return array("Unknown error"); $stms = dav_get_update_statements($ver); - $errors = []; + $errors = array(); foreach ($stms as $st) { // @TODO Friendica-dependent dba::e($st); diff --git a/dav/friendica/dav_caldav_backend_virtual_friendica.inc.php b/dav/friendica/dav_caldav_backend_virtual_friendica.inc.php index 169c5bcb..0afc03bd 100644 --- a/dav/friendica/dav_caldav_backend_virtual_friendica.inc.php +++ b/dav/friendica/dav_caldav_backend_virtual_friendica.inc.php @@ -124,7 +124,7 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual $summary = (($row["summary"]) ? $row["summary"] : substr(preg_replace("/\[[^\]]*\]/", "", $row["desc"]), 0, 100)); - return [ + return array( "jq_id" => $row["id"], "ev_id" => $row["id"], "summary" => escape_tags($summary), @@ -142,7 +142,7 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual "url_detail" => $base_path . "/events/event/" . $row["id"], "url_edit" => "", "special_type" => ($row["type"] == "birthday" ? "birthday" : ""), - ]; + ); } @@ -179,7 +179,7 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual if (is_numeric($date_to)) $sql_where .= " AND `start` <= '" . date("Y-m-d H:i:s", $date_to) . "'"; else $sql_where .= " AND `start` <= '" . dbesc($date_to) . "'"; } - $ret = []; + $ret = array(); $r = q("SELECT * FROM `event` WHERE `uid` = %d " . $sql_where . " ORDER BY `start`", IntVal($calendar["namespace_id"])); @@ -214,21 +214,21 @@ class Sabre_CalDAV_Backend_Friendica extends Sabre_CalDAV_Backend_Virtual public function getCalendarsForUser($principalUri) { $n = dav_compat_principal2namespace($principalUri); - if ($n["namespace"] != $this->getNamespace()) return []; + if ($n["namespace"] != $this->getNamespace()) return array(); $cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $this->getNamespace(), IntVal($n["namespace_id"])); - $ret = []; + $ret = array(); foreach ($cals as $cal) { if (!in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue; - $dat = [ + $dat = array( "id" => $cal["id"], "uri" => $cal["uri"], "principaluri" => $principalUri, '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0', - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(["VEVENT"]), + '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array("VEVENT")), "calendar_class" => "Sabre_CalDAV_Calendar_Virtual", - ]; + ); foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field]; $ret[] = $dat; diff --git a/dav/friendica/dav_carddav_backend_virtual_friendica.inc.php b/dav/friendica/dav_carddav_backend_virtual_friendica.inc.php index 8d51022d..3a06d042 100644 --- a/dav/friendica/dav_carddav_backend_virtual_friendica.inc.php +++ b/dav/friendica/dav_carddav_backend_virtual_friendica.inc.php @@ -46,13 +46,13 @@ class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual { $uid = dav_compat_principal2uid($principalUri); - $addressBooks = []; + $addressBooks = array(); $books = q("SELECT id, ctag FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CARDDAV_NAMESPACE_PRIVATE, IntVal($uid), dbesc(CARDDAV_FRIENDICA_CONTACT)); $ctag = $books[0]["ctag"]; - $addressBooks[] = [ + $addressBooks[] = array( 'id' => $books[0]["id"], 'uri' => "friendica", 'principaluri' => $principalUri, @@ -61,7 +61,7 @@ class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual '{http://calendarserver.org/ns/}getctag' => $ctag, '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), - ]; + ); return $addressBooks; @@ -76,7 +76,7 @@ class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual { $name = explode(" ", $contact["name"]); $first_name = $last_name = ""; - $middle_name = []; + $middle_name = array(); $num = count($name); for ($i = 0; $i < $num && $first_name == ""; $i++) if ($name[$i] != "") { $first_name = $name[$i]; @@ -114,14 +114,14 @@ class Sabre_CardDAV_Backend_Friendica extends Sabre_CardDAV_Backend_Virtual } $vcard = vcard_source_compile($vcarddata); - return [ + return array( "id" => $contact["id"], "carddata" => $vcard, "uri" => $contact["id"] . ".vcf", "lastmodified" => wdcal_mySql2PhpTime($vcarddata->last_update), "etag" => md5($vcard), "size" => strlen($vcard), - ]; + ); } diff --git a/dav/friendica/dav_friendica_auth.inc.php b/dav/friendica/dav_friendica_auth.inc.php index 88b8cf01..acc33fa1 100644 --- a/dav/friendica/dav_friendica_auth.inc.php +++ b/dav/friendica/dav_friendica_auth.inc.php @@ -1,41 +1,41 @@ currentUser]; - } + public function getUsers() { + return array($this->currentUser); + } /** * @return null|string */ - public function getCurrentUser() - { - return $this->currentUser; - } + public function getCurrentUser() { + return $this->currentUser; + } /** * Authenticates the user based on the current request. @@ -48,8 +48,8 @@ class Sabre_DAV_Auth_Backend_Std extends Sabre_DAV_Auth_Backend_AbstractBasic * @throws Sabre_DAV_Exception_NotAuthenticated * @return bool */ - public function authenticate(Sabre_DAV_Server $server, $realm) - { + public function authenticate(Sabre_DAV_Server $server, $realm) { + $a = get_app(); if (isset($a->user["uid"])) { $this->currentUser = strtolower($a->user["nickname"]); @@ -67,7 +67,7 @@ class Sabre_DAV_Auth_Backend_Std extends Sabre_DAV_Auth_Backend_AbstractBasic } // Authenticates the user - if (!$this->validateUserPass($userpass[0], $userpass[1])) { + if (!$this->validateUserPass($userpass[0],$userpass[1])) { $auth->requireLogin(); throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match'); } @@ -75,13 +75,19 @@ class Sabre_DAV_Auth_Backend_Std extends Sabre_DAV_Auth_Backend_AbstractBasic return true; } + /** * @param string $username * @param string $password * @return bool */ - protected function validateUserPass($username, $password) - { - return User::authenticate($username, $password); - } + protected function validateUserPass($username, $password) { + $encrypted = hash('whirlpool',trim($password)); + $r = q("SELECT COUNT(*) anz FROM `user` WHERE `nickname` = '%s' AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1", + dbesc(trim($username)), + dbesc($encrypted) + ); + return ($r[0]["anz"] == 1); + } + } diff --git a/dav/friendica/dav_friendica_principal.inc.php b/dav/friendica/dav_friendica_principal.inc.php index d23619ec..780bcd24 100644 --- a/dav/friendica/dav_friendica_principal.inc.php +++ b/dav/friendica/dav_friendica_principal.inc.php @@ -61,16 +61,16 @@ class Sabre_DAVACL_PrincipalBackend_Std implements Sabre_DAVACL_IPrincipalBacken { // This backend only support principals in one collection - if ($prefixPath !== $this->prefix) return []; + if ($prefixPath !== $this->prefix) return array(); - $users = []; + $users = array(); $r = q("SELECT `nickname` FROM `user` WHERE `nickname` = '%s'", escape_tags($this->authBackend->getCurrentUser()) ); foreach ($r as $t) { - $users[] = [ + $users[] = array( 'uri' => $this->prefix . '/' . strtolower($t['nickname']), '{DAV:}displayname' => $t['nickname'], - ]; + ); } return $users; @@ -94,24 +94,24 @@ class Sabre_DAVACL_PrincipalBackend_Std implements Sabre_DAVACL_IPrincipalBacken if ($prefixPath !== $this->prefix) return null; $r = q("SELECT `nickname` FROM `user` WHERE `nickname` = '%s'", escape_tags($userName) ); - if (count($r) == 0) return []; + if (count($r) == 0) return array(); - return [ + return array( 'uri' => $this->prefix . '/' . strtolower($r[0]['nickname']), '{DAV:}displayname' => $r[0]['nickname'], - ]; + ); } function getGroupMemberSet($principal) { - return []; + return array(); } function getGroupMembership($principal) { - return []; + return array(); } diff --git a/dav/friendica/layout.fnk.php b/dav/friendica/layout.fnk.php index f384c50c..80a9ae2d 100644 --- a/dav/friendica/layout.fnk.php +++ b/dav/friendica/layout.fnk.php @@ -1,7 +1,5 @@ page['htmlhead'] .= '' . "\r\n"; $a->page['htmlhead'] .= '' . "\r\n"; - switch (Config::get("system", "language")) { + switch (get_config("system", "language")) { case "de": $a->page['htmlhead'] .= '' . "\r\n"; $a->page['htmlhead'] .= '' . "\r\n"; @@ -80,7 +78,7 @@ function wdcal_import_user_ics($calendar_id) { $server = dav_create_server(true, true, false); $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); - if (!$calendar) goaway('dav/wdcal/'); + if (!$calendar) goaway($a->get_baseurl() . "/dav/wdcal/"); if (isset($_REQUEST["save"])) { check_form_security_token_redirectOnErr('/dav/settings/', 'icsimport'); @@ -91,7 +89,7 @@ function wdcal_import_user_ics($calendar_id) { /** @var Sabre\VObject\Component\VCalendar $vObject */ $vObject = Sabre\VObject\Reader::read($text); $comp = $vObject->getComponents(); - $imported = []; + $imported = array(); foreach ($comp as $c) try { /** @var Sabre\VObject\Component\VEvent $c */ $uid = $c->__get("UID")->value; @@ -171,18 +169,18 @@ function wdcal_import_user_ics($calendar_id) { * @param bool $show_nav * @return string */ -function wdcal_printCalendar($calendars, $calendars_selected, $data_feed_url, $view = "week", $theme = 0, $height_diff = 175, $readonly = false, $curr_day = "", $add_params = [], $show_nav = true) +function wdcal_printCalendar($calendars, $calendars_selected, $data_feed_url, $view = "week", $theme = 0, $height_diff = 175, $readonly = false, $curr_day = "", $add_params = array(), $show_nav = true) { $a = get_app(); $localization = wdcal_local::getInstanceByUser($a->user["uid"]); if (count($calendars_selected) == 0) foreach ($calendars as $c) { - $prop = $c->getProperties(["id"]); + $prop = $c->getProperties(array("id")); $calendars_selected[] = $prop["id"]; } - $opts = [ + $opts = array( "view" => $view, "theme" => $theme, "readonly" => $readonly, @@ -194,7 +192,7 @@ function wdcal_printCalendar($calendars, $calendars_selected, $data_feed_url, $v "date_format_dm3" => $localization->dateformat_js_dm3(), "date_format_full" => $localization->dateformat_datepicker_js(), "baseurl" => $a->get_baseurl() . "/dav/wdcal/", - ]; + ); $x = ' ' . "\r\n"; - $a->page['htmlhead'] .= '' . "\r\n"; - - $a->page['htmlhead'] .= '' . "\r\n"; - } - - $s .= ''; - $s .= '

    ' . t('Jappix Mini') . '

    '; - $s .= '
    '; - $s .= ''; + } diff --git a/openstreetmap/openstreetmap.php b/openstreetmap/openstreetmap.php index ae9cb480..13545169 100644 --- a/openstreetmap/openstreetmap.php +++ b/openstreetmap/openstreetmap.php @@ -8,13 +8,11 @@ * Author: Klaus Weidenbach * */ + +require_once('include/cache.php'); -use Friendica\Core\Cache; -use Friendica\Core\Config; - -function openstreetmap_install() -{ +function openstreetmap_install() { register_hook('render_location', 'addon/openstreetmap/openstreetmap.php', 'openstreetmap_location'); register_hook('generate_map', 'addon/openstreetmap/openstreetmap.php', 'openstreetmap_generate_map'); register_hook('generate_named_map', 'addon/openstreetmap/openstreetmap.php', 'openstreetmap_generate_named_map'); @@ -23,8 +21,7 @@ function openstreetmap_install() logger("installed openstreetmap"); } -function openstreetmap_uninstall() -{ +function openstreetmap_uninstall() { unregister_hook('render_location', 'addon/openstreetmap/openstreetmap.php', 'openstreetmap_location'); unregister_hook('generate_map', 'addon/openstreetmap/openstreetmap.php', 'openstreetmap_generate_map'); unregister_hook('generate_named_map', 'addon/openstreetmap/openstreetmap.php', 'openstreetmap_generate_named_map'); @@ -33,8 +30,7 @@ function openstreetmap_uninstall() logger("removed openstreetmap"); } -function openstreetmap_alterheader($a, &$navHtml) -{ +function openstreetmap_alterheader($a, &$navHtml) { $addScriptTag = '' . "\r\n"; $a->page['htmlhead'] .= $addScriptTag; } @@ -44,15 +40,14 @@ function openstreetmap_alterheader($a, &$navHtml) * * If an item has coordinates add link to a tile map server, e.g. openstreetmap.org. * If an item has a location open it with the help of OSM's Nominatim reverse geocode search. - * + * * @param mixed $a * @param array& $item */ function openstreetmap_location($a, &$item) { - if(! (strlen($item['location']) || strlen($item['coord']))) { + if(! (strlen($item['location']) || strlen($item['coord']))) return; - } /* * Get the configuration variables from the config. @@ -62,25 +57,21 @@ function openstreetmap_location($a, &$item) { * ?mlat=lat&mlon=lon for markers. */ - $tmsserver = Config::get('openstreetmap', 'tmsserver'); - if(! $tmsserver) { + $tmsserver = get_config('openstreetmap', 'tmsserver'); + if(! $tmsserver) $tmsserver = 'http://www.openstreetmap.org'; - } - $nomserver = Config::get('openstreetmap', 'nomserver'); - if(! $nomserver) { + $nomserver = get_config('openstreetmap', 'nomserver'); + if(! $nomserver) $nomserver = 'http://nominatim.openstreetmap.org/search.php'; - } - $zoom = Config::get('openstreetmap', 'zoom'); - if(! $zoom) { + $zoom = get_config('openstreetmap', 'zoom'); + if(! $zoom) $zoom = 16; - } - $marker = Config::get('openstreetmap', 'marker'); - if(! $marker) { + $marker = get_config('openstreetmap', 'marker'); + if(! $marker) $marker = 0; - } if ($item['coord'] != "") { $coords = explode(' ', $item['coord']); @@ -94,23 +85,22 @@ function openstreetmap_location($a, &$item) { } } - if ($target == "") { + if ($target == "") $target = $nomserver.'?q='.urlencode($item['location']); - } - if ($item['location'] != "") { + if ($item['location'] != "") $title = $item['location']; - } else { + else $title = $item['coord']; - } $item['html'] = ''.$title.''; } -function openstreetmap_generate_named_map(&$a, &$b) -{ - $nomserver = Config::get('openstreetmap', 'nomserver'); +function openstreetmap_generate_named_map(&$a,&$b) { + + + $nomserver = get_config('openstreetmap', 'nomserver'); if(! $nomserver) $nomserver = 'http://nominatim.openstreetmap.org/search.php'; $args = '?q=' . urlencode($b['location']) . '&format=json'; @@ -120,33 +110,29 @@ function openstreetmap_generate_named_map(&$a, &$b) $j = json_decode($x['body'],true); if($j && is_array($j) && $j[0]['lat'] && $j[0]['lon']) { - $arr = ['lat' => $j[0]['lat'],'lon' => $j[0]['lon'],'location' => $b['location'], 'html' => '']; + $arr = array('lat' => $j[0]['lat'],'lon' => $j[0]['lon'],'location' => $b['location'], 'html' => ''); openstreetmap_generate_map($a,$arr); $b['html'] = $arr['html']; } } } -function openstreetmap_generate_map(&$a, &$b) -{ - $tmsserver = Config::get('openstreetmap', 'tmsserver'); - if(! $tmsserver) { +function openstreetmap_generate_map(&$a,&$b) { + + $tmsserver = get_config('openstreetmap', 'tmsserver'); + if(! $tmsserver) $tmsserver = 'http://www.openstreetmap.org'; - } - if(strpos(z_root(),'https:') !== false) { + if(strpos(z_root(),'https:') !== false) $tmsserver = str_replace('http:','https:',$tmsserver); - } - $zoom = Config::get('openstreetmap', 'zoom'); - if(! $zoom) { + $zoom = get_config('openstreetmap', 'zoom'); + if(! $zoom) $zoom = 16; - } - $marker = Config::get('openstreetmap', 'marker'); - if(! $marker) { + $marker = get_config('openstreetmap', 'marker'); + if(! $marker) $marker = 0; - } $lat = $b['lat']; // round($b['lat'], 5); $lon = $b['lon']; // round($b['lon'], 5); @@ -163,44 +149,39 @@ function openstreetmap_generate_map(&$a, &$b) } -function openstreetmap_plugin_admin(&$a, &$o) -{ +function openstreetmap_plugin_admin(&$a, &$o) { $t = get_markup_template("admin.tpl", "addon/openstreetmap/"); - $tmsserver = Config::get('openstreetmap', 'tmsserver'); - if(! $tmsserver) { + $tmsserver = get_config('openstreetmap', 'tmsserver'); + if(! $tmsserver) $tmsserver = 'http://www.openstreetmap.org'; - } - $nomserver = Config::get('openstreetmap', 'nomserver'); - if(! $nomserver) { + $nomserver = get_config('openstreetmap', 'nomserver'); + if(! $nomserver) $nomserver = 'http://nominatim.openstreetmap.org/search.php'; - } - $zoom = Config::get('openstreetmap', 'zoom'); - if(! $zoom) { + $zoom = get_config('openstreetmap', 'zoom'); + if(! $zoom) $zoom = 16; - } - $marker = Config::get('openstreetmap', 'marker'); - if(! $marker) { + $marker = get_config('openstreetmap', 'marker'); + if(! $marker) $marker = 0; - } - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Submit'), - '$tmsserver' => ['tmsserver', t('Tile Server URL'), $tmsserver, t('A list of public tile servers')], - '$nomserver' => ['nomserver', t('Nominatim (reverse geocoding) Server URL'), $nomserver, t('A list of Nominatim servers')], - '$zoom' => ['zoom', t('Default zoom'), $zoom, t('The default zoom level. (1:world, 18:highest, also depends on tile server)')], - '$marker' => ['marker', t('Include marker on map'), $marker, t('Include a marker on the map.')], - ]); + '$tmsserver' => array('tmsserver', t('Tile Server URL'), $tmsserver, t('A list of public tile servers')), + '$nomserver' => array('nomserver', t('Nominatim (reverse geocoding) Server URL'), $nomserver, t('A list of Nominatim servers')), + '$zoom' => array('zoom', t('Default zoom'), $zoom, t('The default zoom level. (1:world, 18:highest, also depends on tile server)')), + '$marker' => array('marker', t('Include marker on map'), $marker, t('Include a marker on the map.')), + )); } - -function openstreetmap_plugin_admin_post(&$a) -{ +function openstreetmap_plugin_admin_post(&$a) { $urltms = ((x($_POST, 'tmsserver')) ? notags(trim($_POST['tmsserver'])) : ''); $urlnom = ((x($_POST, 'nomserver')) ? notags(trim($_POST['nomserver'])) : ''); $zoom = ((x($_POST, 'zoom')) ? intval(trim($_POST['zoom'])) : '16'); $marker = ((x($_POST, 'marker')) ? intval(trim($_POST['marker'])) : '0'); - Config::set('openstreetmap', 'tmsserver', $urltms); - Config::set('openstreetmap', 'nomserver', $urlnom); - Config::set('openstreetmap', 'zoom', $zoom); - Config::set('openstreetmap', 'marker', $marker); + set_config('openstreetmap', 'tmsserver', $urltms); + set_config('openstreetmap', 'nomserver', $urlnom); + set_config('openstreetmap', 'zoom', $zoom); + set_config('openstreetmap', 'marker', $marker); info( t('Settings updated.') . EOL); } + + diff --git a/pageheader/pageheader.css b/pageheader/pageheader.css index 8b3282fb..24608edb 100644 --- a/pageheader/pageheader.css +++ b/pageheader/pageheader.css @@ -17,7 +17,7 @@ .pageheader { text-align: center; - width: 100%; + width 100%; margin-top: 25px; font-size: 20px; } diff --git a/pageheader/pageheader.php b/pageheader/pageheader.php index 977bee4e..173fc707 100644 --- a/pageheader/pageheader.php +++ b/pageheader/pageheader.php @@ -10,8 +10,6 @@ * */ -use Friendica\Core\Config; - function pageheader_install() { register_hook('page_content_top', 'addon/pageheader/pageheader.php', 'pageheader_fetch'); register_hook('plugin_settings', 'addon/pageheader/pageheader.php', 'pageheader_addon_settings'); @@ -45,7 +43,7 @@ function pageheader_addon_settings(&$a,&$s) { $a->page['htmlhead'] .= '' . "\r\n"; - $words = Config::get('pageheader','text'); + $words = get_config('pageheader','text'); if(! $words) $words = ''; @@ -68,7 +66,7 @@ function pageheader_addon_settings_post(&$a,&$b) { return; if($_POST['pageheader-submit']) { - Config::set('pageheader','text',trim(strip_tags($_POST['pageheader-words']))); + set_config('pageheader','text',trim(strip_tags($_POST['pageheader-words']))); info( t('pageheader Settings saved.') . EOL); } } @@ -78,7 +76,7 @@ function pageheader_fetch($a,&$b) { if(file_exists('pageheader.html')){ $s = file_get_contents('pageheader.html'); } else { - $s = Config::get('pageheader', 'text'); + $s = get_config('pageheader', 'text'); } $a->page['htmlhead'] .= ' t('Save Settings'), - '$piwikbaseurl' => ['baseurl', t('Piwik Base URL'), Config::get('piwik','baseurl' ), t('Absolute path to your Piwik installation. (without protocol (http/s), with trailing slash)')], - '$siteid' => ['siteid', t('Site ID'), Config::get('piwik','siteid' ), ''], - '$optout' => ['optout', t('Show opt-out cookie link?'), Config::get('piwik','optout' ), ''], - '$async' => ['async', t('Asynchronous tracking'), Config::get('piwik','async' ), ''], - ]); + '$piwikbaseurl' => array('baseurl', t('Piwik Base URL'), get_config('piwik','baseurl' ), t('Absolute path to your Piwik installation. (without protocol (http/s), with trailing slash)')), + '$siteid' => array('siteid', t('Site ID'), get_config('piwik','siteid' ), ''), + '$optout' => array('optout', t('Show opt-out cookie link?'), get_config('piwik','optout' ), ''), + '$async' => array('async', t('Asynchronous tracking'), get_config('piwik','async' ), ''), + )); } function piwik_plugin_admin_post (&$a) { $url = ((x($_POST, 'baseurl')) ? notags(trim($_POST['baseurl'])) : ''); $id = ((x($_POST, 'siteid')) ? trim($_POST['siteid']) : ''); $optout = ((x($_POST, 'optout')) ? trim($_POST['optout']) : ''); $async = ((x($_POST, 'async')) ? trim($_POST['async']) : ''); - Config::set('piwik', 'baseurl', $url); - Config::set('piwik', 'siteid', $id); - Config::set('piwik', 'optout', $optout); - Config::set('piwik', 'async', $async); + set_config('piwik', 'baseurl', $url); + set_config('piwik', 'siteid', $id); + set_config('piwik', 'optout', $optout); + set_config('piwik', 'async', $async); info( t('Settings updated.'). EOL); } diff --git a/planets/planets.php b/planets/planets.php index 0d88e21d..d40e6c61 100644 --- a/planets/planets.php +++ b/planets/planets.php @@ -7,12 +7,11 @@ * Author: Tony Baldwin */ -use Friendica\Core\PConfig; function planets_install() { /** - * + * * Our demo plugin will attach in three places. * The first is just prior to storing a local post. * @@ -22,7 +21,7 @@ function planets_install() { /** * - * Then we'll attach into the plugin settings page, and also the + * Then we'll attach into the plugin settings page, and also the * settings post hook so that we can create and update * user preferences. * @@ -79,7 +78,7 @@ function planets_post_hook($a, &$item) { /* Retrieve our personal config setting */ - $active = PConfig::get(local_user(), 'planets', 'enable'); + $active = get_pconfig(local_user(), 'planets', 'enable'); if(! $active) return; @@ -93,7 +92,7 @@ function planets_post_hook($a, &$item) { * */ - $planets = ['Alderaan','Tatooine','Dagobah','Polis Massa','Coruscant','Hoth','Endor','Kamino','Rattatak','Mustafar','Iego','Geonosis','Felucia','Dantooine','Ansion','Artaru','Bespin','Boz Pity','Cato Neimoidia','Christophsis','Kashyyyk','Kessel','Malastare','Mygeeto','Nar Shaddaa','Ord Mantell','Saleucami','Subterrel','Death Star','Teth','Tund','Utapau','Yavin']; + $planets = array('Alderaan','Tatooine','Dagobah','Polis Massa','Coruscant','Hoth','Endor','Kamino','Rattatak','Mustafar','Iego','Geonosis','Felucia','Dantooine','Ansion','Artaru','Bespin','Boz Pity','Cato Neimoidia','Christophsis','Kashyyyk','Kessel','Malastare','Mygeeto','Nar Shaddaa','Ord Mantell','Saleucami','Subterrel','Death Star','Teth','Tund','Utapau','Yavin'); $planet = array_rand($planets,1); $item['location'] = $planets[$planet]; @@ -117,13 +116,13 @@ function planets_settings_post($a,$post) { if(! local_user()) return; if($_POST['planets-submit']) - PConfig::set(local_user(),'planets','enable',intval($_POST['planets'])); + set_pconfig(local_user(),'planets','enable',intval($_POST['planets'])); } /** * - * Called from the Plugin Setting form. + * Called from the Plugin Setting form. * Add our own settings info to the page. * */ @@ -141,7 +140,7 @@ function planets_settings(&$a,&$s) { /* Get the current state of our config variable */ - $enabled = PConfig::get(local_user(),'planets','enable'); + $enabled = get_pconfig(local_user(),'planets','enable'); $checked = (($enabled) ? ' checked="checked" ' : ''); diff --git a/pledgie/pledgie.css b/pledgie/pledgie.css index 5195871c..9cb9896d 100644 --- a/pledgie/pledgie.css +++ b/pledgie/pledgie.css @@ -22,7 +22,7 @@ .pledgie { text-align: center; - width: 100%; + width 100%; margin-top: 25px; font-size: 20px; } diff --git a/pledgie/pledgie.php b/pledgie/pledgie.php index 6183c76d..fdc727b1 100644 --- a/pledgie/pledgie.php +++ b/pledgie/pledgie.php @@ -8,8 +8,6 @@ * */ -use Friendica\Core\Config; - function pledgie_install() { register_hook('page_end', 'addon/pledgie/pledgie.php', 'pledgie_active'); register_hook('plugin_settings', 'addon/pledgie/pledgie.php', 'pledgie_addon_settings'); @@ -31,8 +29,8 @@ function pledgie_addon_settings(&$a,&$s) { $a->page['htmlhead'] .= '' . "\r\n"; - $campaign = Config::get('pledgie-campaign','text'); - $describe = Config::get('pledgie-describe','text'); + $campaign = get_config('pledgie-campaign','text'); + $describe = get_config('pledgie-describe','text'); if(! $campaign) $campaign = ''; @@ -63,15 +61,15 @@ function pledgie_addon_settings_post(&$a,&$b) { return; if($_POST['pledgie-submit']) { - Config::set('pledgie-describe','text',trim(strip_tags($_POST['pledgie-describe']))); - Config::set('pledgie-campaign','text',trim(strip_tags($_POST['pledgie-campaign']))); + set_config('pledgie-describe','text',trim(strip_tags($_POST['pledgie-describe']))); + set_config('pledgie-campaign','text',trim(strip_tags($_POST['pledgie-campaign']))); info( t('pledgie Settings saved.') . EOL); } } function pledgie_active(&$a,&$b) { - $campaign = Config::get('pledgie-campaign','text'); - $describe = Config::get('pledgie-describe','text'); + $campaign = get_config('pledgie-campaign','text'); + $describe = get_config('pledgie-describe','text'); $b .= '
    '; $b .= $describe . '
    300) { + // set_config('poormancron','lastupdate', $now); + // proc_run('php',"include/poller.php"); + //} +} + +function poormancron_procrun(&$a, &$arr) { + return; // deactivated + + if (get_config('poormancron','usecli')==1) return; + $argv = $arr['args']; + $arr['run_cmd'] = false; + logger("poormancron procrun ".implode(", ",$argv)); + array_shift($argv); + $argc = count($argv); + logger("poormancron procrun require_once ".basename($argv[0])); + require_once(basename($argv[0])); + $funcname=str_replace(".php", "", basename($argv[0]))."_run"; + + $funcname($argv, $argc); +} + + +?> diff --git a/posterous/lang/C/messages.po b/posterous/lang/C/messages.po new file mode 100644 index 00000000..99327c24 --- /dev/null +++ b/posterous/lang/C/messages.po @@ -0,0 +1,58 @@ +# ADDON posterous +# Copyright (C) +# This file is distributed under the same license as the Friendica posterous addon package. +# +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2013-02-27 05:01-0500\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: posterous.php:37 +msgid "Post to Posterous" +msgstr "" + +#: posterous.php:70 +msgid "Posterous Post Settings" +msgstr "" + +#: posterous.php:72 +msgid "Enable Posterous Post Plugin" +msgstr "" + +#: posterous.php:77 +msgid "Posterous login" +msgstr "" + +#: posterous.php:82 +msgid "Posterous password" +msgstr "" + +#: posterous.php:87 +msgid "Posterous site ID" +msgstr "" + +#: posterous.php:92 +msgid "Posterous API token" +msgstr "" + +#: posterous.php:97 +msgid "Post to Posterous by default" +msgstr "" + +#: posterous.php:103 +msgid "Submit" +msgstr "" + +#: posterous.php:189 +msgid "Post from Friendica" +msgstr "" diff --git a/posterous/lang/ca/strings.php b/posterous/lang/ca/strings.php new file mode 100644 index 00000000..ec7bedf6 --- /dev/null +++ b/posterous/lang/ca/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "enviament a Posterous"; +$a->strings["Posterous Post Settings"] = "Configuració d'Enviaments a Posterous"; +$a->strings["Enable Posterous Post Plugin"] = "Habilitar plugin d'Enviament de Posterous"; +$a->strings["Posterous login"] = "Inici de sessió a Posterous"; +$a->strings["Posterous password"] = "Contrasenya a Posterous"; +$a->strings["Posterous site ID"] = "ID al lloc Posterous"; +$a->strings["Posterous API token"] = "Posterous API token"; +$a->strings["Post to Posterous by default"] = "Enviar a Posterous per defecte"; +$a->strings["Submit"] = "Enviar"; +$a->strings["Post from Friendica"] = "Enviament des de Friendica"; diff --git a/posterous/lang/cs/strings.php b/posterous/lang/cs/strings.php new file mode 100644 index 00000000..733ec89a --- /dev/null +++ b/posterous/lang/cs/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Poslat na Posterous"; +$a->strings["Posterous Post Settings"] = "Posterous nastavení příspěvků"; +$a->strings["Enable Posterous Post Plugin"] = "Umožnit Posterous Plugin"; +$a->strings["Posterous login"] = "Posterous login"; +$a->strings["Posterous password"] = "Posterous heslo"; +$a->strings["Posterous site ID"] = "Posterous site ID"; +$a->strings["Posterous API token"] = "Posterous API token"; +$a->strings["Post to Posterous by default"] = "Příspěvky standardně posílat na Posterous"; +$a->strings["Submit"] = "Odeslat"; +$a->strings["Post from Friendica"] = "Příspěvek z Friendica"; diff --git a/posterous/lang/de/strings.php b/posterous/lang/de/strings.php new file mode 100644 index 00000000..186c53d6 --- /dev/null +++ b/posterous/lang/de/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Nach Posterous senden"; +$a->strings["Posterous Post Settings"] = "Posterous Beitrags-Einstellungen"; +$a->strings["Enable Posterous Post Plugin"] = "Posterous-Plugin aktivieren"; +$a->strings["Posterous login"] = "Posterous-Anmeldename"; +$a->strings["Posterous password"] = "Posterous-Passwort"; +$a->strings["Posterous site ID"] = "Posterous site ID"; +$a->strings["Posterous API token"] = "Posterous API token"; +$a->strings["Post to Posterous by default"] = "Veröffentliche öffentliche Beiträge standardmäßig bei Posterous"; +$a->strings["Submit"] = "Senden"; +$a->strings["Post from Friendica"] = "Beitrag via Friendica"; diff --git a/posterous/lang/eo/strings.php b/posterous/lang/eo/strings.php new file mode 100644 index 00000000..06f48635 --- /dev/null +++ b/posterous/lang/eo/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Afiŝi al Posterous"; +$a->strings["Posterous Post Settings"] = "Agordoj pri afiŝoj ĉe Posterous"; +$a->strings["Enable Posterous Post Plugin"] = "Ŝalti la Poserous-afiŝo kromprogramon"; +$a->strings["Posterous login"] = "Posterous salutnomo"; +$a->strings["Posterous password"] = "Posterous pasvorto"; +$a->strings["Posterous site ID"] = "Idento de Posterous retejo"; +$a->strings["Posterous API token"] = "API ĵetono de Posterous retejo"; +$a->strings["Post to Posterous by default"] = "Defaŭlte afiŝi al Posterous"; +$a->strings["Submit"] = "Sendi"; +$a->strings["Post from Friendica"] = "Afiŝo de Friendica"; diff --git a/posterous/lang/es/strings.php b/posterous/lang/es/strings.php new file mode 100644 index 00000000..9198865a --- /dev/null +++ b/posterous/lang/es/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Publicar en Posterous"; +$a->strings["Posterous Post Settings"] = "Configuración de las publicaciones en Posterous"; +$a->strings["Enable Posterous Post Plugin"] = "Activar el módulo de publicación en Posterous"; +$a->strings["Posterous login"] = "Entrar en Posterous"; +$a->strings["Posterous password"] = "Contraseña de Posterous"; +$a->strings["Posterous site ID"] = "ID de Posterous"; +$a->strings["Posterous API token"] = "API de Posterous"; +$a->strings["Post to Posterous by default"] = "Publicar en Posterous por defecto"; +$a->strings["Submit"] = "Envíar"; +$a->strings["Post from Friendica"] = "Publicado desde Friendica"; diff --git a/posterous/lang/fr/strings.php b/posterous/lang/fr/strings.php new file mode 100644 index 00000000..be14e1ec --- /dev/null +++ b/posterous/lang/fr/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Envoyer à Posterous"; +$a->strings["Posterous Post Settings"] = "Réglages de l'envoi à Posterous"; +$a->strings["Enable Posterous Post Plugin"] = "Activer l'envoi à Posterous"; +$a->strings["Posterous login"] = "Login Posterous"; +$a->strings["Posterous password"] = "Mot de passe"; +$a->strings["Posterous site ID"] = "ID du site Posterous"; +$a->strings["Posterous API token"] = "Clé d'API Posterous"; +$a->strings["Post to Posterous by default"] = "Envoyer à Posterous par défaut"; +$a->strings["Submit"] = "Envoyer"; +$a->strings["Post from Friendica"] = "Publier depuis Friendica"; diff --git a/posterous/lang/is/strings.php b/posterous/lang/is/strings.php new file mode 100644 index 00000000..d48afbba --- /dev/null +++ b/posterous/lang/is/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Senda færslu á Posterous"; +$a->strings["Posterous Post Settings"] = "Stilla Posterous Post"; +$a->strings["Enable Posterous Post Plugin"] = "Kveðja á Posterous Post viðbót "; +$a->strings["Posterous login"] = "Posterous notendanafn"; +$a->strings["Posterous password"] = "Posterous aðgangsorð"; +$a->strings["Posterous site ID"] = ""; +$a->strings["Posterous API token"] = ""; +$a->strings["Post to Posterous by default"] = "Sjálfgefið láta færslur flæða á Posterous"; +$a->strings["Submit"] = "Senda inn"; +$a->strings["Post from Friendica"] = "Færslur frá Friendica"; diff --git a/posterous/lang/it/strings.php b/posterous/lang/it/strings.php new file mode 100644 index 00000000..3c2e4067 --- /dev/null +++ b/posterous/lang/it/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Invia a Posterous"; +$a->strings["Posterous Post Settings"] = "Impostazioni di invio a Posterous"; +$a->strings["Enable Posterous Post Plugin"] = "Abilita il plugin di invio a Posterous"; +$a->strings["Posterous login"] = "Posterous login"; +$a->strings["Posterous password"] = "Posterous password"; +$a->strings["Posterous site ID"] = ""; +$a->strings["Posterous API token"] = ""; +$a->strings["Post to Posterous by default"] = "Invia sempre a Posterous"; +$a->strings["Submit"] = "Invia"; +$a->strings["Post from Friendica"] = "Messaggio da Friendica"; diff --git a/posterous/lang/nb-no/strings.php b/posterous/lang/nb-no/strings.php new file mode 100644 index 00000000..64d3fb64 --- /dev/null +++ b/posterous/lang/nb-no/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = ""; +$a->strings["Posterous Post Settings"] = ""; +$a->strings["Enable Posterous Post Plugin"] = ""; +$a->strings["Posterous login"] = ""; +$a->strings["Posterous password"] = ""; +$a->strings["Posterous site ID"] = ""; +$a->strings["Posterous API token"] = ""; +$a->strings["Post to Posterous by default"] = ""; +$a->strings["Submit"] = "Lagre"; +$a->strings["Post from Friendica"] = ""; diff --git a/posterous/lang/pl/strings.php b/posterous/lang/pl/strings.php new file mode 100644 index 00000000..2514fadc --- /dev/null +++ b/posterous/lang/pl/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = ""; +$a->strings["Posterous Post Settings"] = ""; +$a->strings["Enable Posterous Post Plugin"] = ""; +$a->strings["Posterous login"] = ""; +$a->strings["Posterous password"] = ""; +$a->strings["Posterous site ID"] = ""; +$a->strings["Posterous API token"] = ""; +$a->strings["Post to Posterous by default"] = ""; +$a->strings["Submit"] = "Potwierdź"; +$a->strings["Post from Friendica"] = "Post z Friendica"; diff --git a/posterous/lang/pt-br/strings.php b/posterous/lang/pt-br/strings.php new file mode 100644 index 00000000..c2ab2977 --- /dev/null +++ b/posterous/lang/pt-br/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "Postar no Posterous"; +$a->strings["Posterous Post Settings"] = "Configurações de Postagem do Posterous"; +$a->strings["Enable Posterous Post Plugin"] = "Habilitar Plugin de Postagem do Posterous"; +$a->strings["Posterous login"] = "Login do Posterous"; +$a->strings["Posterous password"] = "Senha do Posterous"; +$a->strings["Posterous site ID"] = ""; +$a->strings["Posterous API token"] = ""; +$a->strings["Post to Posterous by default"] = "Postar para o Posterous como padrão"; +$a->strings["Submit"] = "Enviar"; +$a->strings["Post from Friendica"] = "Postar do Friendica"; diff --git a/posterous/lang/ru/strings.php b/posterous/lang/ru/strings.php new file mode 100644 index 00000000..2d1268b6 --- /dev/null +++ b/posterous/lang/ru/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = ""; +$a->strings["Posterous Post Settings"] = ""; +$a->strings["Enable Posterous Post Plugin"] = "Включить Posterous плагин сообщений"; +$a->strings["Posterous login"] = ""; +$a->strings["Posterous password"] = ""; +$a->strings["Posterous site ID"] = ""; +$a->strings["Posterous API token"] = ""; +$a->strings["Post to Posterous by default"] = ""; +$a->strings["Submit"] = "Подтвердить"; +$a->strings["Post from Friendica"] = "Сообщение от Friendica"; diff --git a/posterous/lang/sv/strings.php b/posterous/lang/sv/strings.php new file mode 100644 index 00000000..3ec569a7 --- /dev/null +++ b/posterous/lang/sv/strings.php @@ -0,0 +1,3 @@ +strings["Submit"] = "Spara"; diff --git a/posterous/lang/zh-cn/strings.php b/posterous/lang/zh-cn/strings.php new file mode 100644 index 00000000..ab258a20 --- /dev/null +++ b/posterous/lang/zh-cn/strings.php @@ -0,0 +1,12 @@ +strings["Post to Posterous"] = "发送往Posterous"; +$a->strings["Posterous Post Settings"] = "Posterous发送设置"; +$a->strings["Enable Posterous Post Plugin"] = "使Posterous发送插件可用的"; +$a->strings["Posterous login"] = "Posterous登记名"; +$a->strings["Posterous password"] = "Posterous密码"; +$a->strings["Posterous site ID"] = "Posterous网站身份证明"; +$a->strings["Posterous API token"] = "Posterous API令牌"; +$a->strings["Post to Posterous by default"] = "默认地发送往Posterous"; +$a->strings["Submit"] = "提交"; +$a->strings["Post from Friendica"] = "文章从Friendica"; diff --git a/posterous/posterous.css b/posterous/posterous.css new file mode 100644 index 00000000..0a43bf32 --- /dev/null +++ b/posterous/posterous.css @@ -0,0 +1,16 @@ + +#posterous-enable-label, #posterous-username-label, #posterous-password-label, #posterous-site_id-label, #posterous-api_token-label, #posterous-bydefault-label { + float: left; + width: 200px; + margin-top: 10px; +} + +#posterous-checkbox, #posterous-username, #posterous-password, #posterous-site_id, #posterous-api_token, #posterous-bydefault { + float: left; + margin-top: 10px; +} + +#posterous-submit { + margin-top: 15px; +} + diff --git a/posterous/posterous.php b/posterous/posterous.php new file mode 100644 index 00000000..76eaf77a --- /dev/null +++ b/posterous/posterous.php @@ -0,0 +1,215 @@ + + * Author: Tony Baldwin + * Status: Unsupported + */ + +function posterous_install() { + register_hook('post_local', 'addon/posterous/posterous.php', 'posterous_post_local'); + register_hook('notifier_normal', 'addon/posterous/posterous.php', 'posterous_send'); + register_hook('jot_networks', 'addon/posterous/posterous.php', 'posterous_jot_nets'); + register_hook('connector_settings', 'addon/posterous/posterous.php', 'posterous_settings'); + register_hook('connector_settings_post', 'addon/posterous/posterous.php', 'posterous_settings_post'); + +} +function posterous_uninstall() { + unregister_hook('post_local', 'addon/posterous/posterous.php', 'posterous_post_local'); + unregister_hook('notifier_normal', 'addon/posterous/posterous.php', 'posterous_send'); + unregister_hook('jot_networks', 'addon/posterous/posterous.php', 'posterous_jot_nets'); + unregister_hook('connector_settings', 'addon/posterous/posterous.php', 'posterous_settings'); + unregister_hook('connector_settings_post', 'addon/posterous/posterous.php', 'posterous_settings_post'); +} + + +function posterous_jot_nets(&$a,&$b) { + if(! local_user()) + return; + + $pstr_post = get_pconfig(local_user(),'posterous','post'); + if(intval($pstr_post) == 1) { + $pstr_defpost = get_pconfig(local_user(),'posterous','post_by_default'); + $selected = ((intval($pstr_defpost) == 1) ? ' checked="checked" ' : ''); + $b .= '
    ' + . t('Post to Posterous') . '
    '; + } +} + + +function posterous_settings(&$a,&$s) { + + if(! local_user()) + return; + + /* Add our stylesheet to the page so we can make our settings look nice */ + + $a->page['htmlhead'] .= '' . "\r\n"; + + /* Get the current state of our config variables */ + + $enabled = get_pconfig(local_user(),'posterous','post'); + + $checked = (($enabled) ? ' checked="checked" ' : ''); + + $def_enabled = get_pconfig(local_user(),'posterous','post_by_default'); + + $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); + + $pstr_username = get_pconfig(local_user(), 'posterous', 'posterous_username'); + $pstr_password = get_pconfig(local_user(), 'posterous', 'posterous_password'); + $pstr_site_id = get_pconfig(local_user(), 'posterous', 'posterous_site_id'); + $pstr_api_token = get_pconfig(local_user(), 'posterous', 'posterous_api_token'); + + + /* Add some HTML to the existing form */ + + $s .= '
    '; + $s .= '

    ' . t('Posterous Post Settings') . '

    '; + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + + /* provide a submit button */ + + $s .= '
    '; + +} + + +function posterous_settings_post(&$a,&$b) { + + if(x($_POST,'posterous-submit')) { + + set_pconfig(local_user(),'posterous','post',intval($_POST['posterous'])); + set_pconfig(local_user(),'posterous','post_by_default',intval($_POST['posterous_bydefault'])); + set_pconfig(local_user(),'posterous','posterous_username',trim($_POST['posterous_username'])); + set_pconfig(local_user(),'posterous','posterous_password',trim($_POST['posterous_password'])); + set_pconfig(local_user(),'posterous','posterous_site_id',trim($_POST['posterous_site_id'])); + set_pconfig(local_user(),'posterous','posterous_api_token',trim($_POST['posterous_api_token'])); + + } + +} + +function posterous_post_local(&$a,&$b) { + + // This can probably be changed to allow editing by pointing to a different API endpoint + + if($b['edit']) + return; + + if((! local_user()) || (local_user() != $b['uid'])) + return; + + if($b['private'] || $b['parent']) + return; + + $pstr_post = intval(get_pconfig(local_user(),'posterous','post')); + + $pstr_enable = (($pstr_post && x($_REQUEST,'posterous_enable')) ? intval($_REQUEST['posterous_enable']) : 0); + + if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'posterous','post_by_default'))) + $pstr_enable = 1; + + if(! $pstr_enable) + return; + + if(strlen($b['postopts'])) + $b['postopts'] .= ','; + $b['postopts'] .= 'posterous'; +} + + + + +function posterous_send(&$a,&$b) { + + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) + return; + + if(! strstr($b['postopts'],'posterous')) + return; + + if($b['parent'] != $b['id']) + return; + + + $pstr_username = get_pconfig($b['uid'],'posterous','posterous_username'); + $pstr_password = get_pconfig($b['uid'],'posterous','posterous_password'); + $pstr_site_id = get_pconfig($b['uid'],'posterous','posterous_site_id'); + $pstr_blog = "http://posterous.com/api/2/sites/$pstr_site_id/posts"; + $pstr_api_token = get_pconfig($b['uid'],'posterous','posterous_api_token'); + + if($pstr_username && $pstr_password && $pstr_blog) { + + require_once('include/bbcode.php'); + $tag_arr = array(); + $tags = ''; + $x = preg_match_all('/\#\[(.*?)\](.*?)\[/',$b['tag'],$matches,PREG_SET_ORDER); + + if($x) { + foreach($matches as $mtch) { + $tag_arr[] = $mtch[2]; + } + } + if(count($tag_arr)) + $tags = implode(',',$tag_arr); + + + $params = array( + 'post[title]' => (($b['title']) ? $b['title'] : t('Post from Friendica')), + 'post[source]' => 'Friendica', + 'post[tags]' => $tags, + 'post[body]' => bbcode($b['body']), + 'api_token' => $pstr_api_token, + 'site_id' => $pstr_site_id + ); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $pstr_blog); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); + curl_setopt($ch, CURLOPT_HEADER, false); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $pstr_username . ':' . $pstr_password); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $params); + + $data = curl_exec($ch); + $result = curl_multi_getcontent($ch); + curl_close($ch); + + logger('posterous_send: ' . $result); + } +} + diff --git a/procrunner/lang/C/messages.po b/procrunner/lang/C/messages.po new file mode 100644 index 00000000..e69de29b diff --git a/procrunner/procrunner.php b/procrunner/procrunner.php new file mode 100644 index 00000000..12f8f41e --- /dev/null +++ b/procrunner/procrunner.php @@ -0,0 +1,55 @@ + + * Author: Mike Macgirvin + * Status: Unsupported + */ + +function procrunner_install() { + + $addons = get_config('system','addon'); + if(strstr('poormancron',$addons)) { + logger('procrunner incompatible with poormancron. Not installing procrunner.'); + return; + } + + // check for command line php + $a = get_app(); + $ex = Array(); + $ex[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php'); + $ex[1] = dirname(dirname(dirname(__file__)))."/testargs.php"; + $ex[2] = "test"; + $out = exec(implode(" ", $ex)); + if ($out==="test") { + logger('procrunner not required on this system. Not installing.'); + return; + } else { + register_hook('proc_run', 'addon/procrunner/procrunner.php','procrunner_procrun'); + logger("installed procrunner"); + } + +} + +function procrunner_uninstall() { + unregister_hook('proc_run', 'addon/procrunner/procrunner.php','procrunner_procrun'); + logger("removed procrunner"); +} + + + +function procrunner_procrun(&$a, &$arr) { + return; // deactivated + + $argv = $arr['args']; + $arr['run_cmd'] = false; + logger("procrunner procrun ".implode(", ",$argv)); + array_shift($argv); + $argc = count($argv); + logger("procrunner procrun require_once ".basename($argv[0])); + require_once(basename($argv[0])); + $funcname=str_replace(".php", "", basename($argv[0]))."_run"; + $funcname($argv, $argc); +} diff --git a/public_server/public_server.php b/public_server/public_server.php index 0ea029b3..7d8b8136 100644 --- a/public_server/public_server.php +++ b/public_server/public_server.php @@ -7,8 +7,7 @@ * Author: Keith Fernie */ -use Friendica\Core\Config; -use Friendica\Model\User; + function public_server_install() { @@ -32,8 +31,8 @@ function public_server_register_account($a,$b) { $uid = $b; - $days = Config::get('public_server','expiredays'); - $days_posts = Config::get('public_server','expireposts'); + $days = get_config('public_server','expiredays'); + $days_posts = get_config('public_server','expireposts'); if(! $days) return; @@ -55,7 +54,7 @@ function public_server_cron($a,$b) { if(count($r)) { foreach($r as $rr) { - notification([ + notification(array( 'uid' => $rr['uid'], 'type' => NOTIFY_SYSTEM, 'system_type' => 'public_server_expire', @@ -65,7 +64,7 @@ function public_server_cron($a,$b) { 'source_name' => t('Administrator'), 'source_link' => $a->get_baseurl(), 'source_photo' => $a->get_baseurl() . '/images/person-80.jpg', - ]); + )); q("update user set expire_notification_sent = '%s' where uid = %d", dbesc(datetime_convert()), @@ -76,11 +75,12 @@ function public_server_cron($a,$b) { $r = q("select * from user where account_expired = 1 and account_expires_on < UTC_TIMESTAMP() - INTERVAL 5 DAY and account_expires_on > '0000-00-00 00:00:00'"); if(count($r)) { - foreach($r as $rr) { - User::remove($rr['uid']); - } + require_once('include/Contact.php'); + foreach($r as $rr) + user_remove($rr['uid']); + } - $nologin = Config::get('public_server','nologin'); + $nologin = get_config('public_server','nologin'); if($nologin) { $r = q("select uid from user where account_expired = 0 and login_date = '0000-00-00 00:00:00' and register_date < UTC_TIMESTAMP() - INTERVAL %d DAY and account_expires_on = '0000-00-00 00:00:00'",intval($nologin)); if(count($r)) { @@ -93,7 +93,7 @@ function public_server_cron($a,$b) { } - $flagusers = Config::get('public_server','flagusers'); + $flagusers = get_config('public_server','flagusers'); if($flagusers) { $r = q("select uid from user where account_expired = 0 and login_date < UTC_TIMESTAMP() - INTERVAL %d DAY and account_expires_on = '0000-00-00 00:00:00' and `page-flags` = 0",intval($flagusers)); if(count($r)) { @@ -105,8 +105,8 @@ function public_server_cron($a,$b) { } } - $flagposts = Config::get('public_server','flagposts'); - $flagpostsexpire = Config::get('public_server','flagpostsexpire'); + $flagposts = get_config('public_server','flagposts'); + $flagpostsexpire = get_config('public_server','flagpostsexpire'); if ($flagposts && $flagpostsexpire) { $r = q("select uid from user where account_expired = 0 and login_date < UTC_TIMESTAMP() - INTERVAL %d DAY and account_expires_on = '0000-00-00 00:00:00' and expire = 0 and `page-flags` = 0",intval($flagposts)); if(count($r)) { @@ -123,17 +123,17 @@ function public_server_cron($a,$b) { } function public_server_enotify(&$a, &$b) { - if (x($b, 'params') && $b['params']['type'] == NOTIFY_SYSTEM + if (x($b, 'params') && $b['params']['type'] == NOTIFY_SYSTEM && x($b['params'], 'system_type') && $b['params']['system_type'] === 'public_server_expire') { $b['itemlink'] = $a->get_baseurl(); - $b['epreamble'] = $b['preamble'] = sprintf( t('Your account on %s will expire in a few days.'), Config::get('system','sitename')); + $b['epreamble'] = $b['preamble'] = sprintf( t('Your account on %s will expire in a few days.'), get_config('system','sitename')); $b['subject'] = t('Your Friendica account is about to expire.'); $b['body'] = sprintf( t("Hi %1\$s,\n\nYour account on %2\$s will expire in less than five days. You may keep your account by logging in at least once every 30 days"), $b['params']['to_name'], "[url=" . $app->config["system"]["url"] . "]" . $app->config["sitename"] . "[/url]"); } } function public_server_login($a,$b) { - $days = Config::get('public_server','expiredays'); + $days = get_config('public_server','expiredays'); if(! $days) return; $r = q("UPDATE user set account_expires_on = '%s' where uid = %d and account_expires_on > '0000-00-00 00:00:00'", @@ -150,27 +150,27 @@ function public_server_plugin_admin_post ( &$a ) { $flagusers = (( x($_POST, 'flagusers') ) ? notags(trim($_POST['flagusers'] )) : ''); $flagposts = (( x($_POST, 'flagposts') ) ? notags(trim($_POST['flagposts'] )) : ''); $flagpostsexpire = (( x($_POST, 'flagpostsexpire') ) ? notags(trim($_POST['flagpostsexpire'] )) : ''); - Config::set( 'public_server','expiredays',$expiredays ); - Config::set( 'public_server','expireposts',$expireposts ); - Config::set( 'public_server','nologin',$nologin ); - Config::set( 'public_server','flagusers',$flagusers); - Config::set( 'public_server','flagposts',$flagposts ); - Config::set( 'public_server','flagpostsexpire',$flagpostsexpire ); + set_config( 'public_server','expiredays',$expiredays ); + set_config( 'public_server','expireposts',$expireposts ); + set_config( 'public_server','nologin',$nologin ); + set_config( 'public_server','flagusers',$flagusers); + set_config( 'public_server','flagposts',$flagposts ); + set_config( 'public_server','flagpostsexpire',$flagpostsexpire ); info( t('Settings saved').EOL ); } function public_server_plugin_admin ( &$a, &$o) { $token = get_form_security_token("publicserver"); $t = get_markup_template( "admin.tpl", "addon/public_server"); - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Save Settings'), '$form_security_token' => $token, '$infotext' => t('Set any of these options to 0 to deactivate it.'), - '$expiredays' => [ "expiredays","Expire Days", intval(Config::get('public_server', 'expiredays')), "When an account is created on the site, it is given a hard "], - '$expireposts' => [ "expireposts", "Expire Posts", intval(Config::get('public_server','expireposts')), "Set the default days for posts to expire here"], - '$nologin' => [ "nologin", "No Login", intval(Config::get('public_server','nologin')), "Remove users who have never logged in after nologin days "], - '$flagusers' => [ "flagusers", "Flag users", intval(Config::get('public_server','flagusers')), "Remove users who last logged in over flagusers days ago"], - '$flagposts' => [ "flagposts", "Flag posts", intval(Config::get('public_server','flagposts')), "For users who last logged in over flagposts days ago set post expiry days to flagpostsexpire "], - '$flagpostsexpire' => [ "flagpostsexpire", "Flag posts expire", intval(Config::get('public_server','flagpostsexpire'))], - ]); + '$expiredays' => Array( "expiredays","Expire Days", intval(get_config('public_server', 'expiredays')), "When an account is created on the site, it is given a hard "), + '$expireposts' => Array( "expireposts", "Expire Posts", intval(get_config('public_server','expireposts')), "Set the default days for posts to expire here"), + '$nologin' => Array( "nologin", "No Login", intval(get_config('public_server','nologin')), "Remove users who have never logged in after nologin days "), + '$flagusers' => Array( "flagusers", "Flag users", intval(get_config('public_server','flagusers')), "Remove users who last logged in over flagusers days ago"), + '$flagposts' => Array( "flagposts", "Flag posts", intval(get_config('public_server','flagposts')), "For users who last logged in over flagposts days ago set post expiry days to flagpostsexpire "), + '$flagpostsexpire' => Array( "flagpostsexpire", "Flag posts expire", intval(get_config('public_server','flagpostsexpire'))), + )); } diff --git a/pumpio/pumpio.php b/pumpio/pumpio.php index d8538dcc..f70801a8 100644 --- a/pumpio/pumpio.php +++ b/pumpio/pumpio.php @@ -5,18 +5,12 @@ * Version: 0.2 * Author: Michael Vogel */ -use Friendica\Core\Config; -use Friendica\Core\PConfig; -use Friendica\Core\Worker; -use Friendica\Model\Contact; -use Friendica\Model\GContact; -use Friendica\Model\Group; -use Friendica\Model\User; - -require 'addon/pumpio/oauth/http.php'; -require 'addon/pumpio/oauth/oauth_client.php'; -require_once 'include/enotify.php'; -require_once "mod/share.php"; +require('addon/pumpio/oauth/http.php'); +require('addon/pumpio/oauth/oauth_client.php'); +require_once('include/enotify.php'); +require_once('include/socgraph.php'); +require_once("include/Photo.php"); +require_once("mod/share.php"); define('PUMPIO_DEFAULT_POLL_INTERVAL', 5); // given in minutes @@ -70,8 +64,8 @@ function pumpio_content(&$a) { } function pumpio_check_item_notification($a, &$notification_data) { - $hostname = PConfig::get($notification_data["uid"], 'pumpio','host'); - $username = PConfig::get($notification_data["uid"], "pumpio", "user"); + $hostname = get_pconfig($notification_data["uid"], 'pumpio','host'); + $username = get_pconfig($notification_data["uid"], "pumpio", "user"); $notification_data["profiles"][] = "https://".$hostname."/".$username; } @@ -81,9 +75,9 @@ function pumpio_registerclient(&$a, $host) { $url = "https://".$host."/api/client/register"; - $params = []; + $params = array(); - $application_name = Config::get('pumpio', 'application_name'); + $application_name = get_config('pumpio', 'application_name'); if ($application_name == "") $application_name = $a->get_hostname(); @@ -124,18 +118,18 @@ function pumpio_connect(&$a) { session_start(); // Define the needed keys - $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key'); - $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret'); - $hostname = PConfig::get(local_user(), 'pumpio','host'); + $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key'); + $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret'); + $hostname = get_pconfig(local_user(), 'pumpio','host'); if ((($consumer_key == "") || ($consumer_secret == "")) && ($hostname != "")) { logger("pumpio_connect: register client"); $clientdata = pumpio_registerclient($a, $hostname); - PConfig::set(local_user(), 'pumpio','consumer_key', $clientdata->client_id); - PConfig::set(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret); + set_pconfig(local_user(), 'pumpio','consumer_key', $clientdata->client_id); + set_pconfig(local_user(), 'pumpio','consumer_secret', $clientdata->client_secret); - $consumer_key = PConfig::get(local_user(), 'pumpio','consumer_key'); - $consumer_secret = PConfig::get(local_user(), 'pumpio','consumer_secret'); + $consumer_key = get_pconfig(local_user(), 'pumpio','consumer_key'); + $consumer_secret = get_pconfig(local_user(), 'pumpio','consumer_secret'); logger("pumpio_connect: ckey: ".$consumer_key." csecrect: ".$consumer_secret, LOGGER_DEBUG); } @@ -172,8 +166,8 @@ function pumpio_connect(&$a) { if (($success = $client->Process())) { if (strlen($client->access_token)) { logger("pumpio_connect: otoken: ".$client->access_token." osecrect: ".$client->access_token_secret, LOGGER_DEBUG); - PConfig::set(local_user(), "pumpio", "oauth_token", $client->access_token); - PConfig::set(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret); + set_pconfig(local_user(), "pumpio", "oauth_token", $client->access_token); + set_pconfig(local_user(), "pumpio", "oauth_token_secret", $client->access_token_secret); } } $success = $client->Finalize($success); @@ -197,9 +191,9 @@ function pumpio_jot_nets(&$a,&$b) { if(! local_user()) return; - $pumpio_post = PConfig::get(local_user(),'pumpio','post'); + $pumpio_post = get_pconfig(local_user(),'pumpio','post'); if(intval($pumpio_post) == 1) { - $pumpio_defpost = PConfig::get(local_user(),'pumpio','post_by_default'); + $pumpio_defpost = get_pconfig(local_user(),'pumpio','post_by_default'); $selected = ((intval($pumpio_defpost) == 1) ? ' checked="checked" ' : ''); $b .= '
    ' . t('Post to pumpio') . '
    '; @@ -218,24 +212,24 @@ function pumpio_settings(&$a,&$s) { /* Get the current state of our config variables */ - $import_enabled = PConfig::get(local_user(),'pumpio','import'); + $import_enabled = get_pconfig(local_user(),'pumpio','import'); $import_checked = (($import_enabled) ? ' checked="checked" ' : ''); - $enabled = PConfig::get(local_user(),'pumpio','post'); + $enabled = get_pconfig(local_user(),'pumpio','post'); $checked = (($enabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); - $def_enabled = PConfig::get(local_user(),'pumpio','post_by_default'); + $def_enabled = get_pconfig(local_user(),'pumpio','post_by_default'); $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); - $public_enabled = PConfig::get(local_user(),'pumpio','public'); + $public_enabled = get_pconfig(local_user(),'pumpio','public'); $public_checked = (($public_enabled) ? ' checked="checked" ' : ''); - $mirror_enabled = PConfig::get(local_user(),'pumpio','mirror'); + $mirror_enabled = get_pconfig(local_user(),'pumpio','mirror'); $mirror_checked = (($mirror_enabled) ? ' checked="checked" ' : ''); - $servername = PConfig::get(local_user(), "pumpio", "host"); - $username = PConfig::get(local_user(), "pumpio", "user"); + $servername = get_pconfig(local_user(), "pumpio", "host"); + $username = get_pconfig(local_user(), "pumpio", "user"); /* Add some HTML to the existing form */ @@ -259,8 +253,8 @@ function pumpio_settings(&$a,&$s) { if (($username != '') && ($servername != '')) { - $oauth_token = PConfig::get(local_user(), "pumpio", "oauth_token"); - $oauth_token_secret = PConfig::get(local_user(), "pumpio", "oauth_token_secret"); + $oauth_token = get_pconfig(local_user(), "pumpio", "oauth_token"); + $oauth_token_secret = get_pconfig(local_user(), "pumpio", "oauth_token_secret"); $s .= '
    '; if (($oauth_token == "") || ($oauth_token_secret == "")) { @@ -312,19 +306,19 @@ function pumpio_settings_post(&$a,&$b) { if(x($_POST,'pumpio-submit')) { if(x($_POST,'pumpio_delete')) { - PConfig::set(local_user(),'pumpio','consumer_key',''); - PConfig::set(local_user(),'pumpio','consumer_secret',''); - PConfig::set(local_user(),'pumpio','oauth_token',''); - PConfig::set(local_user(),'pumpio','oauth_token_secret',''); - PConfig::set(local_user(),'pumpio','post',false); - PConfig::set(local_user(),'pumpio','import',false); - PConfig::set(local_user(),'pumpio','host',''); - PConfig::set(local_user(),'pumpio','user',''); - PConfig::set(local_user(),'pumpio','public',false); - PConfig::set(local_user(),'pumpio','mirror',false); - PConfig::set(local_user(),'pumpio','post_by_default',false); - PConfig::set(local_user(),'pumpio','lastdate', 0); - PConfig::set(local_user(),'pumpio','last_id', ''); + set_pconfig(local_user(),'pumpio','consumer_key',''); + set_pconfig(local_user(),'pumpio','consumer_secret',''); + set_pconfig(local_user(),'pumpio','oauth_token',''); + set_pconfig(local_user(),'pumpio','oauth_token_secret',''); + set_pconfig(local_user(),'pumpio','post',false); + set_pconfig(local_user(),'pumpio','import',false); + set_pconfig(local_user(),'pumpio','host',''); + set_pconfig(local_user(),'pumpio','user',''); + set_pconfig(local_user(),'pumpio','public',false); + set_pconfig(local_user(),'pumpio','mirror',false); + set_pconfig(local_user(),'pumpio','post_by_default',false); + set_pconfig(local_user(),'pumpio','lastdate', 0); + set_pconfig(local_user(),'pumpio','last_id', ''); } else { // filtering the username if it is filled wrong $user = $_POST['pumpio_user']; @@ -337,18 +331,18 @@ function pumpio_settings_post(&$a,&$b) { // Filtering the hostname if someone is entering it with "http" $host = $_POST['pumpio_host']; $host = trim($host); - $host = str_replace(["https://", "http://"], ["", ""], $host); + $host = str_replace(array("https://", "http://"), array("", ""), $host); - PConfig::set(local_user(),'pumpio','post',intval($_POST['pumpio'])); - PConfig::set(local_user(),'pumpio','import',$_POST['pumpio_import']); - PConfig::set(local_user(),'pumpio','host',$host); - PConfig::set(local_user(),'pumpio','user',$user); - PConfig::set(local_user(),'pumpio','public',$_POST['pumpio_public']); - PConfig::set(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']); - PConfig::set(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault'])); + set_pconfig(local_user(),'pumpio','post',intval($_POST['pumpio'])); + set_pconfig(local_user(),'pumpio','import',$_POST['pumpio_import']); + set_pconfig(local_user(),'pumpio','host',$host); + set_pconfig(local_user(),'pumpio','user',$user); + set_pconfig(local_user(),'pumpio','public',$_POST['pumpio_public']); + set_pconfig(local_user(),'pumpio','mirror',$_POST['pumpio_mirror']); + set_pconfig(local_user(),'pumpio','post_by_default',intval($_POST['pumpio_bydefault'])); if (!$_POST['pumpio_mirror']) - PConfig::delete(local_user(),'pumpio','lastdate'); + del_pconfig(local_user(),'pumpio','lastdate'); //header("Location: ".$a->get_baseurl()."/pumpio/connect"); } @@ -361,11 +355,11 @@ function pumpio_post_local(&$a, &$b) { return; } - $pumpio_post = intval(PConfig::get(local_user(), 'pumpio', 'post')); + $pumpio_post = intval(get_pconfig(local_user(), 'pumpio', 'post')); $pumpio_enable = (($pumpio_post && x($_REQUEST,'pumpio_enable')) ? intval($_REQUEST['pumpio_enable']) : 0); - if ($b['api_source'] && intval(PConfig::get(local_user(), 'pumpio', 'post_by_default'))) { + if ($b['api_source'] && intval(get_pconfig(local_user(), 'pumpio', 'post_by_default'))) { $pumpio_enable = 1; } @@ -385,7 +379,7 @@ function pumpio_post_local(&$a, &$b) { function pumpio_send(&$a,&$b) { - if (!PConfig::get($b["uid"],'pumpio','import')) { + if (!get_pconfig($b["uid"],'pumpio','import')) { if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) return; } @@ -413,16 +407,8 @@ function pumpio_send(&$a,&$b) { logger("pumpio_send: receiver ".print_r($receiver, true)); - if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) { + if (!count($receiver) && ($b['private'] || !strstr($b['postopts'],'pumpio'))) return; - } - - // Dont't post if the post doesn't belong to us. - // This is a check for forum postings - $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]); - if ($b['contact-id'] != $self['id']) { - return; - } } if($b['verb'] == ACTIVITY_LIKE) { @@ -453,14 +439,14 @@ function pumpio_send(&$a,&$b) { // Support for native shares // http:///api//shares?id= - $oauth_token = PConfig::get($b['uid'], "pumpio", "oauth_token"); - $oauth_token_secret = PConfig::get($b['uid'], "pumpio", "oauth_token_secret"); - $consumer_key = PConfig::get($b['uid'], "pumpio","consumer_key"); - $consumer_secret = PConfig::get($b['uid'], "pumpio","consumer_secret"); + $oauth_token = get_pconfig($b['uid'], "pumpio", "oauth_token"); + $oauth_token_secret = get_pconfig($b['uid'], "pumpio", "oauth_token_secret"); + $consumer_key = get_pconfig($b['uid'], "pumpio","consumer_key"); + $consumer_secret = get_pconfig($b['uid'], "pumpio","consumer_secret"); - $host = PConfig::get($b['uid'], "pumpio", "host"); - $user = PConfig::get($b['uid'], "pumpio", "user"); - $public = PConfig::get($b['uid'], "pumpio", "public"); + $host = get_pconfig($b['uid'], "pumpio", "host"); + $user = get_pconfig($b['uid'], "pumpio", "user"); + $public = get_pconfig($b['uid'], "pumpio", "public"); if($oauth_token && $oauth_token_secret) { @@ -470,14 +456,14 @@ function pumpio_send(&$a,&$b) { $content = bbcode($b['body'], false, false, 4); - $params = []; + $params = array(); $params["verb"] = "post"; if (!$iscomment) { - $params["object"] = [ + $params["object"] = array( 'objectType' => "note", - 'content' => $content]; + 'content' => $content); if ($title != "") $params["object"]["displayName"] = $title; @@ -495,16 +481,16 @@ function pumpio_send(&$a,&$b) { $params["bcc"] = $receiver["bcc"]; } else { - $inReplyTo = ["id" => $orig_post["uri"], - "objectType" => "note"]; + $inReplyTo = array("id" => $orig_post["uri"], + "objectType" => "note"); if (($orig_post["object-type"] != "") && (strstr($orig_post["object-type"], NAMESPACE_ACTIVITY_SCHEMA))) $inReplyTo["objectType"] = str_replace(NAMESPACE_ACTIVITY_SCHEMA, '', $orig_post["object-type"]); - $params["object"] = [ + $params["object"] = array( 'objectType' => "comment", 'content' => $content, - 'inReplyTo' => $inReplyTo]; + 'inReplyTo' => $inReplyTo); if ($title != "") $params["object"]["displayName"] = $title; @@ -523,14 +509,14 @@ function pumpio_send(&$a,&$b) { $url = 'https://'.$host.'/api/user/'.$user.'/feed'; if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user); + $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user); else $success = false; if($success) { if ($user->generator->displayName) - PConfig::set($b["uid"], "pumpio", "application_name", $user->generator->displayName); + set_pconfig($b["uid"], "pumpio", "application_name", $user->generator->displayName); $post_id = $user->object->id; logger('pumpio_send '.$username.': success '.$post_id); @@ -548,7 +534,7 @@ function pumpio_send(&$a,&$b) { if (count($r)) $a->contact = $r[0]["id"]; - $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $params]); + $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $params)); require_once('include/queue_fn.php'); add_to_queue($a->contact,NETWORK_PUMPIO,$s); notice(t('Pump.io post failed. Queued for retry.').EOL); @@ -560,15 +546,15 @@ function pumpio_send(&$a,&$b) { function pumpio_action(&$a, $uid, $uri, $action, $content = "") { // Don't do likes and other stuff if you don't import the timeline - if (!PConfig::get($uid,'pumpio','import')) + if (!get_pconfig($uid,'pumpio','import')) return; - $ckey = PConfig::get($uid, 'pumpio', 'consumer_key'); - $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret'); - $otoken = PConfig::get($uid, 'pumpio', 'oauth_token'); - $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret'); - $hostname = PConfig::get($uid, 'pumpio','host'); - $username = PConfig::get($uid, "pumpio", "user"); + $ckey = get_pconfig($uid, 'pumpio', 'consumer_key'); + $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret'); + $otoken = get_pconfig($uid, 'pumpio', 'oauth_token'); + $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret'); + $hostname = get_pconfig($uid, 'pumpio','host'); + $username = get_pconfig($uid, "pumpio", "user"); $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), @@ -595,9 +581,9 @@ function pumpio_action(&$a, $uid, $uri, $action, $content = "") { $objectType = "image"; $params["verb"] = $action; - $params["object"] = ['id' => $uri, + $params["object"] = array('id' => $uri, "objectType" => $objectType, - "content" => $content]; + "content" => $content); $client = new oauth_client_class; $client->oauth_version = '1.0a'; @@ -612,7 +598,7 @@ function pumpio_action(&$a, $uid, $uri, $action, $content = "") { $url = 'https://'.$hostname.'/api/user/'.$username.'/feed'; if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'POST', $params, ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user); + $success = $client->CallAPI($url, 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user); else $success = false; @@ -625,7 +611,7 @@ function pumpio_action(&$a, $uid, $uri, $action, $content = "") { if (count($r)) $a->contact = $r[0]["id"]; - $s = serialize(['url' => $url, 'item' => $orig_post["id"], 'post' => $params]); + $s = serialize(array('url' => $url, 'item' => $orig_post["id"], 'post' => $params)); require_once('include/queue_fn.php'); add_to_queue($a->contact,NETWORK_PUMPIO,$s); notice(t('Pump.io like failed. Queued for retry.').EOL); @@ -639,9 +625,9 @@ function pumpio_sync(&$a) { if (!count($r)) return; - $last = Config::get('pumpio','last_poll'); + $last = get_config('pumpio','last_poll'); - $poll_interval = intval(Config::get('pumpio','poll_interval')); + $poll_interval = intval(get_config('pumpio','poll_interval')); if(! $poll_interval) $poll_interval = PUMPIO_DEFAULT_POLL_INTERVAL; @@ -662,7 +648,7 @@ function pumpio_sync(&$a) { } } - $abandon_days = intval(Config::get('system','account_abandon_days')); + $abandon_days = intval(get_config('system','account_abandon_days')); if ($abandon_days < 1) $abandon_days = 0; @@ -683,7 +669,7 @@ function pumpio_sync(&$a) { pumpio_fetchinbox($a, $rr['uid']); // check for new contacts once a day - $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check'); + $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check'); if($last_contact_check) $next_contact_check = $last_contact_check + 86400; else @@ -691,35 +677,36 @@ function pumpio_sync(&$a) { if($next_contact_check <= time()) { pumpio_getallusers($a, $rr["uid"]); - PConfig::set($rr['uid'],'pumpio','contact_check',time()); + set_pconfig($rr['uid'],'pumpio','contact_check',time()); } } } logger('pumpio: cron_end'); - Config::set('pumpio','last_poll', time()); + set_config('pumpio','last_poll', time()); } function pumpio_cron(&$a,$b) { - Worker::add(PRIORITY_MEDIUM,"addon/pumpio/pumpio_sync.php"); + //pumpio_sync($a); + proc_run("php","addon/pumpio/pumpio_sync.php"); } function pumpio_fetchtimeline(&$a, $uid) { - $ckey = PConfig::get($uid, 'pumpio', 'consumer_key'); - $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret'); - $otoken = PConfig::get($uid, 'pumpio', 'oauth_token'); - $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret'); - $lastdate = PConfig::get($uid, 'pumpio', 'lastdate'); - $hostname = PConfig::get($uid, 'pumpio','host'); - $username = PConfig::get($uid, "pumpio", "user"); + $ckey = get_pconfig($uid, 'pumpio', 'consumer_key'); + $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret'); + $otoken = get_pconfig($uid, 'pumpio', 'oauth_token'); + $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret'); + $lastdate = get_pconfig($uid, 'pumpio', 'lastdate'); + $hostname = get_pconfig($uid, 'pumpio','host'); + $username = get_pconfig($uid, "pumpio", "user"); // get the application name for the pump.io app // 1st try personal config, then system config and fallback to the // hostname of the node if neither one is set. - $application_name = PConfig::get( $uid, 'pumpio', 'application_name'); + $application_name = get_pconfig( $uid, 'pumpio', 'application_name'); if ($application_name == "") - $application_name = Config::get('pumpio', 'application_name'); + $application_name = get_config('pumpio', 'application_name'); if ($application_name == "") $application_name = $a->get_hostname(); @@ -742,7 +729,7 @@ function pumpio_fetchtimeline(&$a, $uid) { $username = $user.'@'.$host; if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user); + $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user); else $success = false; @@ -767,7 +754,7 @@ function pumpio_fetchtimeline(&$a, $uid) { if ($first_time) continue; - $receiptians = []; + $receiptians = array(); if (@is_array($post->cc)) $receiptians = array_merge($receiptians, $post->cc); @@ -822,7 +809,7 @@ function pumpio_fetchtimeline(&$a, $uid) { } if ($lastdate != 0) - PConfig::set($uid,'pumpio','lastdate', $lastdate); + set_pconfig($uid,'pumpio','lastdate', $lastdate); } function pumpio_dounlike(&$a, $uid, $self, $post, $own_id) { @@ -945,7 +932,7 @@ function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = tru return; } - $likedata = []; + $likedata = array(); $likedata['parent'] = $orig_post['id']; $likedata['verb'] = ACTIVITY_LIKE; $likedata['gravity'] = 3; @@ -977,11 +964,11 @@ function pumpio_dolike(&$a, $uid, $self, $post, $own_id, $threadcompletion = tru function pumpio_get_contact($uid, $contact, $no_insert = false) { - GContact::update(["url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2, + update_gcontact(array("url" => $contact->url, "network" => NETWORK_PUMPIO, "generation" => 2, "photo" => $contact->image->url, "name" => $contact->displayName, "hide" => true, "nick" => $contact->preferredUsername, "location" => $contact->location->displayName, - "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id)]); - $cid = Contact::getIdForURL($contact->url, $uid); + "about" => $contact->summary, "addr" => str_replace("acct:", "", $contact->id))); + $cid = get_contact($contact->url, $uid); if ($no_insert) return($cid); @@ -1025,7 +1012,14 @@ function pumpio_get_contact($uid, $contact, $no_insert = false) { $contact_id = $r[0]['id']; - Group::addMember(User::getDefaultGroup($uid), $contact_id); + $g = q("select def_gid from user where uid = %d limit 1", + intval($uid) + ); + + if($g && intval($g[0]['def_gid'])) { + require_once('include/group.php'); + group_add_member($uid,'',$contact_id,$g[0]['def_gid']); + } } else { $contact_id = $r[0]["id"]; @@ -1040,7 +1034,8 @@ function pumpio_get_contact($uid, $contact, $no_insert = false) { */ } - Contact::updateAvatar($contact->image->url, $uid, $contact_id); + if (function_exists("update_contact_avatar")) + update_contact_avatar($contact->image->url, $uid, $contact_id); return($contact_id); } @@ -1101,7 +1096,7 @@ function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcomplet if (!strstr("post|share|update", $post->verb)) return false; - $receiptians = []; + $receiptians = array(); if (@is_array($post->cc)) $receiptians = array_merge($receiptians, $post->cc); @@ -1113,7 +1108,7 @@ function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcomplet if ($receiver->id == "http://activityschema.org/collection/public") $public = true; - $postarray = []; + $postarray = array(); $postarray['network'] = NETWORK_PUMPIO; $postarray['gravity'] = 0; $postarray['uid'] = $uid; @@ -1214,7 +1209,7 @@ function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcomplet $postarray['edited'] = $postarray['created']; if ($post->verb == "share") { - if (!intval(Config::get('system','wall-to-wall_share'))) { + if (!intval(get_config('system','wall-to-wall_share'))) { if (isset($post->object->author->displayName) && ($post->object->author->displayName != "")) $share_author = $post->object->author->displayName; elseif (isset($post->object->author->preferredUsername) && ($post->object->author->preferredUsername != "")) @@ -1294,7 +1289,7 @@ function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcomplet $conv_parent = $conv['parent']; - notification([ + notification(array( 'type' => NOTIFY_COMMENT, 'notify_flags' => $user[0]['notify-flags'], 'language' => $user[0]['language'], @@ -1309,7 +1304,7 @@ function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcomplet 'verb' => ACTIVITY_POST, 'otype' => 'item', 'parent' => $conv_parent, - ]); + )); // only send one notification break; @@ -1323,13 +1318,13 @@ function pumpio_dopost(&$a, $client, $uid, $self, $post, $own_id, $threadcomplet function pumpio_fetchinbox(&$a, $uid) { - $ckey = PConfig::get($uid, 'pumpio', 'consumer_key'); - $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret'); - $otoken = PConfig::get($uid, 'pumpio', 'oauth_token'); - $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret'); - $lastdate = PConfig::get($uid, 'pumpio', 'lastdate'); - $hostname = PConfig::get($uid, 'pumpio','host'); - $username = PConfig::get($uid, "pumpio", "user"); + $ckey = get_pconfig($uid, 'pumpio', 'consumer_key'); + $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret'); + $otoken = get_pconfig($uid, 'pumpio', 'oauth_token'); + $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret'); + $lastdate = get_pconfig($uid, 'pumpio', 'lastdate'); + $hostname = get_pconfig($uid, 'pumpio','host'); + $username = get_pconfig($uid, "pumpio", "user"); $own_id = "https://".$hostname."/".$username; @@ -1354,7 +1349,7 @@ function pumpio_fetchinbox(&$a, $uid) { $client->access_token = $otoken; $client->access_token_secret = $osecret; - $last_id = PConfig::get($uid,'pumpio','last_id'); + $last_id = get_pconfig($uid,'pumpio','last_id'); $url = 'https://'.$hostname.'/api/user/'.$username.'/inbox'; @@ -1362,7 +1357,7 @@ function pumpio_fetchinbox(&$a, $uid) { $url .= '?since='.urlencode($last_id); if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $user); + $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $user); else $success = false; @@ -1379,16 +1374,16 @@ function pumpio_fetchinbox(&$a, $uid) { foreach ($lastitems AS $item) pumpio_fetchallcomments($a, $uid, $item["uri"]); - PConfig::set($uid,'pumpio','last_id', $last_id); + set_pconfig($uid,'pumpio','last_id', $last_id); } function pumpio_getallusers(&$a, $uid) { - $ckey = PConfig::get($uid, 'pumpio', 'consumer_key'); - $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret'); - $otoken = PConfig::get($uid, 'pumpio', 'oauth_token'); - $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret'); - $hostname = PConfig::get($uid, 'pumpio','host'); - $username = PConfig::get($uid, "pumpio", "user"); + $ckey = get_pconfig($uid, 'pumpio', 'consumer_key'); + $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret'); + $otoken = get_pconfig($uid, 'pumpio', 'oauth_token'); + $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret'); + $hostname = get_pconfig($uid, 'pumpio','host'); + $username = get_pconfig($uid, "pumpio", "user"); $client = new oauth_client_class; $client->oauth_version = '1.0a'; @@ -1403,7 +1398,7 @@ function pumpio_getallusers(&$a, $uid) { $url = 'https://'.$hostname.'/api/user/'.$username.'/following'; if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users); + $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users); else $success = false; @@ -1411,7 +1406,7 @@ function pumpio_getallusers(&$a, $uid) { $url = 'https://'.$hostname.'/api/user/'.$username.'/following?count='.$users->totalItems; if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $users); + $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $users); else $success = false; } @@ -1450,13 +1445,13 @@ function pumpio_queue_hook(&$a,&$b) { //logger('pumpio_queue: fetching userdata '.print_r($userdata, true)); - $oauth_token = PConfig::get($userdata['uid'], "pumpio", "oauth_token"); - $oauth_token_secret = PConfig::get($userdata['uid'], "pumpio", "oauth_token_secret"); - $consumer_key = PConfig::get($userdata['uid'], "pumpio","consumer_key"); - $consumer_secret = PConfig::get($userdata['uid'], "pumpio","consumer_secret"); + $oauth_token = get_pconfig($userdata['uid'], "pumpio", "oauth_token"); + $oauth_token_secret = get_pconfig($userdata['uid'], "pumpio", "oauth_token_secret"); + $consumer_key = get_pconfig($userdata['uid'], "pumpio","consumer_key"); + $consumer_secret = get_pconfig($userdata['uid'], "pumpio","consumer_secret"); - $host = PConfig::get($userdata['uid'], "pumpio", "host"); - $user = PConfig::get($userdata['uid'], "pumpio", "user"); + $host = get_pconfig($userdata['uid'], "pumpio", "host"); + $user = get_pconfig($userdata['uid'], "pumpio", "user"); $success = false; @@ -1478,7 +1473,7 @@ function pumpio_queue_hook(&$a,&$b) { $client->client_secret = $consumer_secret; if (pumpio_reachable($z['url'])) - $success = $client->CallAPI($z['url'], 'POST', $z['post'], ['FailOnAccessError'=>true, 'RequestContentType'=>'application/json'], $user); + $success = $client->CallAPI($z['url'], 'POST', $z['post'], array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user); else $success = false; @@ -1507,19 +1502,19 @@ function pumpio_queue_hook(&$a,&$b) { function pumpio_getreceiver(&$a, $b) { - $receiver = []; + $receiver = array(); if (!$b["private"]) { if(! strstr($b['postopts'],'pumpio')) return $receiver; - $public = PConfig::get($b['uid'], "pumpio", "public"); + $public = get_pconfig($b['uid'], "pumpio", "public"); if ($public) - $receiver["to"][] = [ + $receiver["to"][] = Array( "objectType" => "collection", - "id" => "http://activityschema.org/collection/public"]; + "id" => "http://activityschema.org/collection/public"); } else { $cids = explode("><", $b["allow_cid"]); $gids = explode("><", $b["allow_gid"]); @@ -1534,29 +1529,30 @@ function pumpio_getreceiver(&$a, $b) { ); if (count($r)) { - $receiver["bcc"][] = [ + $receiver["bcc"][] = Array( "displayName" => $r[0]["name"], "objectType" => "person", "preferredUsername" => $r[0]["nick"], - "url" => $r[0]["url"]]; + "url" => $r[0]["url"]); } } foreach ($gids AS $gid) { $gid = trim($gid, " <>"); $r = q("SELECT `contact`.`name`, `contact`.`nick`, `contact`.`url`, `contact`.`network` ". - "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d ". + "FROM `group_member`, `contact` WHERE `group_member`.`gid` = %d AND `group_member`.`uid` = %d ". "AND `contact`.`id` = `group_member`.`contact-id` AND `contact`.`network` = '%s'", intval($gid), + intval($b["uid"]), dbesc(NETWORK_PUMPIO) ); foreach ($r AS $row) - $receiver["bcc"][] = [ + $receiver["bcc"][] = Array( "displayName" => $row["name"], "objectType" => "person", "preferredUsername" => $row["nick"], - "url" => $row["url"]]; + "url" => $row["url"]); } } @@ -1577,11 +1573,11 @@ function pumpio_getreceiver(&$a, $b) { ); if (count($r)) { - $receiver["to"][] = [ + $receiver["to"][] = Array( "displayName" => $r[0]["name"], "objectType" => "person", "preferredUsername" => $r[0]["nick"], - "url" => $r[0]["url"]]; + "url" => $r[0]["url"]); } } } @@ -1590,12 +1586,12 @@ function pumpio_getreceiver(&$a, $b) { } function pumpio_fetchallcomments(&$a, $uid, $id) { - $ckey = PConfig::get($uid, 'pumpio', 'consumer_key'); - $csecret = PConfig::get($uid, 'pumpio', 'consumer_secret'); - $otoken = PConfig::get($uid, 'pumpio', 'oauth_token'); - $osecret = PConfig::get($uid, 'pumpio', 'oauth_token_secret'); - $hostname = PConfig::get($uid, 'pumpio','host'); - $username = PConfig::get($uid, "pumpio", "user"); + $ckey = get_pconfig($uid, 'pumpio', 'consumer_key'); + $csecret = get_pconfig($uid, 'pumpio', 'consumer_secret'); + $otoken = get_pconfig($uid, 'pumpio', 'oauth_token'); + $osecret = get_pconfig($uid, 'pumpio', 'oauth_token_secret'); + $hostname = get_pconfig($uid, 'pumpio','host'); + $username = get_pconfig($uid, "pumpio", "user"); logger("pumpio_fetchallcomments: completing comment for user ".$uid." post id ".$id); @@ -1628,7 +1624,7 @@ function pumpio_fetchallcomments(&$a, $uid, $id) { logger("pumpio_fetchallcomments: fetching comment for user ".$uid." url ".$url); if (pumpio_reachable($url)) - $success = $client->CallAPI($url, 'GET', [], ['FailOnAccessError'=>true], $item); + $success = $client->CallAPI($url, 'GET', array(), array('FailOnAccessError'=>true), $item); else $success = false; @@ -1697,7 +1693,7 @@ function pumpio_fetchallcomments(&$a, $uid, $id) { function pumpio_reachable($url) { - $data = z_fetch_url($url, false, $redirects, ['timeout'=>10]); + $data = z_fetch_url($url, false, $redirects, array('timeout'=>10)); return(intval($data['return_code']) != 0); } diff --git a/qcomment/qcomment.php b/qcomment/qcomment.php index f4b95184..2c98cba7 100644 --- a/qcomment/qcomment.php +++ b/qcomment/qcomment.php @@ -20,8 +20,6 @@ * */ -use Friendica\Core\PConfig; - function qcomment_install() { register_hook('plugin_settings', 'addon/qcomment/qcomment.php', 'qcomment_addon_settings'); register_hook('plugin_settings_post', 'addon/qcomment/qcomment.php', 'qcomment_addon_settings_post'); @@ -39,30 +37,32 @@ function qcomment_uninstall() { -function qcomment_addon_settings(&$a, &$s) -{ - if (! local_user()) { +function qcomment_addon_settings(&$a,&$s) { + + if(! local_user()) return; - } - /* Add our stylesheet to the page so we can make our settings look nice */ + /* Add our stylesheet to the page so we can make our settings look nice */ - $a->page['htmlhead'] .= '' . "\r\n"; + $a->page['htmlhead'] .= '' . "\r\n"; - $words = PConfig::get(local_user(), 'qcomment', 'words', t(':-)') . "\n" . t(':-(') . "\n" . t('lol')); + $words = get_pconfig(local_user(),'qcomment','words'); + if($words === false) + $words = t(':-)') . "\n" . t(':-(') . "\n" . t('lol'); - $s .= '
    '; - $s .= '

    ' . t('Quick Comment Settings') . '

    '; - $s .= '
    '; + $s .= '
    '; + $s .= '

    ' . t('Quick Comment Settings') . '

    '; + $s .= '
    '; $s .= '
    ' . t("Quick comments are found near comment boxes, sometimes hidden. Click them to provide simple replies.") . '
    '; - $s .= ''; - $s .= ''; - $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; - $s .= '
    '; + $s .= '
    '; $s .= '
    '; return; + } function qcomment_addon_settings_post(&$a,&$b) { @@ -71,7 +71,7 @@ function qcomment_addon_settings_post(&$a,&$b) { return; if($_POST['qcomment-submit']) { - PConfig::set(local_user(),'qcomment','words',xmlify($_POST['qcomment-words'])); + set_pconfig(local_user(),'qcomment','words',xmlify($_POST['qcomment-words'])); info( t('Quick Comment settings saved.') . EOL); } } diff --git a/randplace/randplace.php b/randplace/randplace.php index b696bed2..27589b1c 100644 --- a/randplace/randplace.php +++ b/randplace/randplace.php @@ -4,9 +4,9 @@ * Description: Sample Friendica plugin/addon. Set a random place when posting. * Version: 1.0 * Author: Mike Macgirvin - * - * - * + * + * + * * * Addons are registered with the system through the admin * panel. @@ -14,17 +14,16 @@ * When registration is detected, the system calls the plugin * name_install() function, located in 'addon/name/name.php', * where 'name' is the name of the addon. - * If the addon is removed from the configuration list, the + * If the addon is removed from the configuration list, the * system will call the name_uninstall() function. * */ -use Friendica\Core\PConfig; function randplace_install() { /** - * + * * Our demo plugin will attach in three places. * The first is just prior to storing a local post. * @@ -34,7 +33,7 @@ function randplace_install() { /** * - * Then we'll attach into the plugin settings page, and also the + * Then we'll attach into the plugin settings page, and also the * settings post hook so that we can create and update * user preferences. * @@ -91,7 +90,7 @@ function randplace_post_hook($a, &$item) { /* Retrieve our personal config setting */ - $active = PConfig::get(local_user(), 'randplace', 'enable'); + $active = get_pconfig(local_user(), 'randplace', 'enable'); if(! $active) return; @@ -105,7 +104,7 @@ function randplace_post_hook($a, &$item) { * */ - $cities = []; + $cities = array(); $zones = timezone_identifiers_list(); foreach($zones as $zone) { if((strpos($zone,'/')) && (! stristr($zone,'US/')) && (! stristr($zone,'Etc/'))) @@ -136,13 +135,13 @@ function randplace_settings_post($a,$post) { if(! local_user()) return; if($_POST['randplace-submit']) - PConfig::set(local_user(),'randplace','enable',intval($_POST['randplace'])); + set_pconfig(local_user(),'randplace','enable',intval($_POST['randplace'])); } /** * - * Called from the Plugin Setting form. + * Called from the Plugin Setting form. * Add our own settings info to the page. * */ @@ -160,7 +159,7 @@ function randplace_settings(&$a,&$s) { /* Get the current state of our config variable */ - $enabled = PConfig::get(local_user(),'randplace','enable'); + $enabled = get_pconfig(local_user(),'randplace','enable'); $checked = (($enabled) ? ' checked="checked" ' : ''); diff --git a/remote_permissions/remote_permissions.php b/remote_permissions/remote_permissions.php index c7e51286..5cba005a 100644 --- a/remote_permissions/remote_permissions.php +++ b/remote_permissions/remote_permissions.php @@ -4,11 +4,9 @@ * Description: Allow the recipients of private posts to see who else can see the post by clicking the lock icon * Version: 1.0 * Author: Zach - * + * */ -use Friendica\Core\Config; -use Friendica\Core\PConfig; function remote_permissions_install() { register_hook('lockview_content', 'addon/remote_permissions/remote_permissions.php', 'remote_permissions_content'); @@ -27,7 +25,7 @@ function remote_permissions_settings(&$a,&$o) { if(! local_user()) return; - $global = Config::get("remote_perms", "global"); + $global = get_config("remote_perms", "global"); if($global == 1) return; @@ -37,18 +35,18 @@ function remote_permissions_settings(&$a,&$o) { /* Get the current state of our config variable */ - $remote_perms = PConfig::get(local_user(),'remote_perms','show'); - + $remote_perms = get_pconfig(local_user(),'remote_perms','show'); + /* Add some HTML to the existing form */ // $t = file_get_contents("addon/remote_permissions/settings.tpl" ); $t = get_markup_template("settings.tpl", "addon/remote_permissions/" ); - $o .= replace_macros($t, [ + $o .= replace_macros($t, array( '$remote_perms_title' => t('Remote Permissions Settings'), '$remote_perms_label' => t('Allow recipients of your private posts to see the other recipients of the posts'), '$checked' => (($remote_perms == 1) ? 'checked="checked"' : ''), '$submit' => t('Save Settings') - ]); + )); } @@ -56,7 +54,7 @@ function remote_permissions_settings_post($a,$post) { if(! local_user() || (! x($_POST,'remote-perms-submit'))) return; - PConfig::set(local_user(),'remote_perms','show',intval($_POST['remote-perms'])); + set_pconfig(local_user(),'remote_perms','show',intval($_POST['remote-perms'])); info( t('Remote Permissions settings updated.') . EOL); } @@ -65,13 +63,13 @@ function remote_permissions_content($a, $item_copy) { if($item_copy['uid'] != local_user()) return; - if(Config::get('remote_perms','global') == 0) { + if(get_config('remote_perms','global') == 0) { // Admin has set Individual choice. We need to find // the original poster. First, get the contact's info $r = q("SELECT nick, url FROM contact WHERE id = %d LIMIT 1", intval($item_copy['contact-id']) ); - if(! $r) + if(! $r) return; // Find out if the contact lives here @@ -88,14 +86,14 @@ function remote_permissions_content($a, $item_copy) { if(! $r) return; - if(PConfig::get($r[0]['uid'],'remote_perms','show') == 0) + if(get_pconfig($r[0]['uid'],'remote_perms','show') == 0) return; } if(($item_copy['private'] == 1) && (! strlen($item_copy['allow_cid'])) && (! strlen($item_copy['allow_gid'])) && (! strlen($item_copy['deny_cid'])) && (! strlen($item_copy['deny_gid']))) { - $allow_names = []; + $allow_names = array(); // Check for the original post here -- that's the only way // to definitely get all of the recipients @@ -124,14 +122,14 @@ function remote_permissions_content($a, $item_copy) { $deny_groups = expand_acl($item['deny_gid']); $o = t('Visible to:') . '
    '; - $allow = []; - $deny = []; + $allow = array(); + $deny = array(); if(count($allowed_groups)) { $r = q("SELECT DISTINCT `contact-id` FROM group_member WHERE gid IN ( %s )", dbesc(implode(', ', $allowed_groups)) ); - foreach($r as $rr) + foreach($r as $rr) $allow[] = $rr['contact-id']; } $allow = array_unique($allow + $allowed_users); @@ -140,7 +138,7 @@ function remote_permissions_content($a, $item_copy) { $r = q("SELECT DISTINCT `contact-id` FROM group_member WHERE gid IN ( %s )", dbesc(implode(', ', $deny_groups)) ); - foreach($r as $rr) + foreach($r as $rr) $deny[] = $rr['contact-id']; } $deny = $deny + $deny_users; @@ -167,7 +165,7 @@ function remote_permissions_content($a, $item_copy) { if(! $r) return; - $allow = []; + $allow = array(); foreach($r as $rr) $allow[] = $rr['uid']; @@ -194,16 +192,16 @@ function remote_permissions_content($a, $item_copy) { function remote_permissions_plugin_admin(&$a, &$o){ $t = get_markup_template( "admin.tpl", "addon/remote_permissions/" ); - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Save Settings'), - '$global' => ['remotepermschoice', t('Global'), 1, t('The posts of every user on this server show the post recipients'), Config::get('remote_perms', 'global') == 1], - '$individual' => ['remotepermschoice', t('Individual'), 2, t('Each user chooses whether his/her posts show the post recipients'), Config::get('remote_perms', 'global') == 0] - ]); + '$global' => array('remotepermschoice', t('Global'), 1, t('The posts of every user on this server show the post recipients'), get_config('remote_perms', 'global') == 1), + '$individual' => array('remotepermschoice', t('Individual'), 2, t('Each user chooses whether his/her posts show the post recipients'), get_config('remote_perms', 'global') == 0) + )); } function remote_permissions_plugin_admin_post(&$a){ $choice = ((x($_POST,'remotepermschoice')) ? notags(trim($_POST['remotepermschoice'])) : ''); - Config::set('remote_perms','global',($choice == 1 ? 1 : 0)); + set_config('remote_perms','global',($choice == 1 ? 1 : 0)); info( t('Settings updated.'). EOL ); } diff --git a/rendertime/lang/fr/messages.po b/rendertime/lang/fr/messages.po deleted file mode 100644 index 42bd84a9..00000000 --- a/rendertime/lang/fr/messages.po +++ /dev/null @@ -1,27 +0,0 @@ -# ADDON rendertime -# Copyright (C) -# This file is distributed under the same license as the Friendica rendertime addon package. -# -# -# Translators: -# Thecross, 2017 -msgid "" -msgstr "" -"Project-Id-Version: friendica\n" -"Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2013-02-27 05:01-0500\n" -"PO-Revision-Date: 2017-12-04 22:24+0000\n" -"Last-Translator: Thecross\n" -"Language-Team: French (http://www.transifex.com/Friendica/friendica/language/fr/)\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Language: fr\n" -"Plural-Forms: nplurals=2; plural=(n > 1);\n" - -#: rendertime.php:29 -#, php-format -msgid "" -"Performance: Database: %s, Network: %s, Rendering: %s, Parser: %s, I/O: %s, " -"Other: %s, Total: %s" -msgstr "Performances: Base de données : %s, Réseau : %s, Rendu : %s, Parser : %s, Entrées/sorties : %s, Autre : %s, Total : %s" diff --git a/rendertime/lang/fr/strings.php b/rendertime/lang/fr/strings.php index b806c8f3..ab4fa67a 100644 --- a/rendertime/lang/fr/strings.php +++ b/rendertime/lang/fr/strings.php @@ -1,8 +1,2 @@ - 1);; -}} -; -$a->strings["Performance: Database: %s, Network: %s, Rendering: %s, Parser: %s, I/O: %s, Other: %s, Total: %s"] = "Performances: Base de données : %s, Réseau : %s, Rendu : %s, Parser : %s, Entrées/sorties : %s, Autre : %s, Total : %s"; +performance["start"]; - $ignored_modules = ["fbrowser"]; + $ignored_modules = array("fbrowser"); $ignored = in_array($a->module, $ignored_modules); if (is_site_admin() && ($_GET["mode"] != "minimal") && !$a->is_mobile && !$a->is_tablet && !$ignored) { @@ -47,7 +45,7 @@ function rendertime_page_end(&$a, &$o) { //round($a->performance["plugin"], 3) )."
    "; - if (Config::get("rendertime", "callstack")) { + if (get_config("rendertime", "callstack")) { $o .= "
    ";
     			$o .= "\nDatabase Read:\n";
     			foreach ($a->callstack["database"] AS $func => $time) {
    diff --git a/retriever/README b/retriever/README
    new file mode 100644
    index 00000000..b9728151
    --- /dev/null
    +++ b/retriever/README
    @@ -0,0 +1,5 @@
    +"retriever" is deactivated since it has side effects for all received posts.
    +
    +It was created in a time when the option 'Fetch further information for feeds' didn't exist.
    +
    +To activate it, please go to the list of your contacts, edit the contact and then select between the different options.
    diff --git a/retriever/database.sql b/retriever/database.sql
    new file mode 100644
    index 00000000..23cac120
    --- /dev/null
    +++ b/retriever/database.sql
    @@ -0,0 +1,36 @@
    +CREATE TABLE IF NOT EXISTS `retriever_rule` (
    +       `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    +       `uid` int(11) NOT NULL,
    +       `contact-id` int(11) NOT NULL,
    +       `data` mediumtext NOT NULL,
    +       PRIMARY KEY (`id`),
    +       KEY `uid` (`uid`),
    +       KEY `contact-id` (`contact-id`)
    +) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
    +
    +CREATE TABLE IF NOT EXISTS `retriever_item` (
    +       `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    +       `item-uri` varchar(800) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
    +       `item-uid` int(10) unsigned NOT NULL DEFAULT '0',
    +       `contact-id` int(10) unsigned NOT NULL DEFAULT '0',
    +       `resource` int(11) NOT NULL,
    +       `finished` tinyint(1) unsigned NOT NULL DEFAULT '0',
    +       KEY `resource` (`resource`),
    +       KEY `all` (`item-uri`, `item-uid`, `contact-id`),
    +       PRIMARY KEY (`id`)
    +) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
    +
    +CREATE TABLE IF NOT EXISTS `retriever_resource` (
    +       `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    +       `type` char(255) NOT NULL,
    +       `binary` int(1) NOT NULL DEFAULT 0,
    +       `url` varchar(800) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
    +       `created` timestamp NOT NULL DEFAULT now(),
    +       `completed` timestamp NULL DEFAULT NULL,
    +       `last-try` timestamp NULL DEFAULT NULL,
    +       `num-tries` int(11) NOT NULL DEFAULT 0,
    +       `data` mediumtext NOT NULL,
    +       `http-code` smallint(1) unsigned NULL DEFAULT NULL,
    +       `redirect-url` varchar(800) CHARACTER SET ascii COLLATE ascii_bin NULL DEFAULT NULL,
    +       PRIMARY KEY (`id`)
    +) DEFAULT CHARSET=utf8 COLLATE=utf8_bin
    diff --git a/retriever/lang/C/messages.po b/retriever/lang/C/messages.po
    new file mode 100644
    index 00000000..e9d20af2
    --- /dev/null
    +++ b/retriever/lang/C/messages.po
    @@ -0,0 +1,102 @@
    +# ADDON retriever
    +# Copyright (C) 
    +# This file is distributed under the same license as the Friendica retriever addon package.
    +# 
    +#
    +#, fuzzy
    +msgid ""
    +msgstr ""
    +"Project-Id-Version: \n"
    +"Report-Msgid-Bugs-To: \n"
    +"POT-Creation-Date: 2014-06-23 14:45+0200\n"
    +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
    +"Last-Translator: FULL NAME \n"
    +"Language-Team: LANGUAGE \n"
    +"Language: \n"
    +"MIME-Version: 1.0\n"
    +"Content-Type: text/plain; charset=UTF-8\n"
    +"Content-Transfer-Encoding: 8bit\n"
    +
    +#: retriever.php:445
    +msgid "Retrieved"
    +msgstr ""
    +
    +#: retriever.php:654
    +msgid "Enabled"
    +msgstr ""
    +
    +#: retriever.php:658
    +msgid "URL Pattern"
    +msgstr ""
    +
    +#: retriever.php:660
    +msgid "Regular expression matching part of the URL to replace"
    +msgstr ""
    +
    +#: retriever.php:663
    +msgid "URL Replace"
    +msgstr ""
    +
    +#: retriever.php:665
    +msgid "Text to replace matching part of above regular expression"
    +msgstr ""
    +
    +#: retriever.php:668
    +msgid "Download Images"
    +msgstr ""
    +
    +#: retriever.php:672
    +msgid "Retrospectively Apply"
    +msgstr ""
    +
    +#: retriever.php:674
    +msgid "Reapply the rules to this number of posts"
    +msgstr ""
    +
    +#: retriever.php:675
    +msgid "Retrieve Feed Content"
    +msgstr ""
    +
    +#: retriever.php:677 retriever.php:721
    +msgid "Save Settings"
    +msgstr ""
    +
    +#: retriever.php:679
    +msgid "Tag"
    +msgstr ""
    +
    +#: retriever.php:680
    +msgid "Attribute"
    +msgstr ""
    +
    +#: retriever.php:681
    +msgid "Value"
    +msgstr ""
    +
    +#: retriever.php:682
    +msgid "Add"
    +msgstr ""
    +
    +#: retriever.php:683
    +msgid "Remove"
    +msgstr ""
    +
    +#: retriever.php:684
    +msgid "Include"
    +msgstr ""
    +
    +#: retriever.php:686
    +msgid "Exclude"
    +msgstr ""
    +
    +#: retriever.php:697
    +msgid "Retriever"
    +msgstr ""
    +
    +#: retriever.php:722
    +msgid "Retriever Settings"
    +msgstr ""
    +
    +#: retriever.php:725
    +msgid "All Photos"
    +msgstr ""
    diff --git a/retriever/retriever.php b/retriever/retriever.php
    new file mode 100644
    index 00000000..72e327b3
    --- /dev/null
    +++ b/retriever/retriever.php
    @@ -0,0 +1,839 @@
    +
    + * Status: Unsupported
    + */
    +
    +require_once('include/html2bbcode.php');	
    +require_once('include/Photo.php');	
    +
    +function retriever_install() {
    +    register_hook('plugin_settings', 'addon/retriever/retriever.php', 'retriever_plugin_settings');
    +    register_hook('plugin_settings_post', 'addon/retriever/retriever.php', 'retriever_plugin_settings_post');
    +    register_hook('post_remote', 'addon/retriever/retriever.php', 'retriever_post_remote_hook');
    +    register_hook('contact_photo_menu', 'addon/retriever/retriever.php', 'retriever_contact_photo_menu');
    +    register_hook('cron', 'addon/retriever/retriever.php', 'retriever_cron');
    +
    +    $r = q("SELECT `id` FROM `pconfig` WHERE `cat` LIKE 'retriever_%%'");
    +    if (count($r) || (get_config('retriever', 'dbversion') == '0.1')) {
    +        $retrievers = array();
    +        $r = q("SELECT SUBSTRING(`cat`, 10) AS `contact`, `k`, `v` FROM `pconfig` WHERE `cat` LIKE 'retriever%%'");
    +        foreach ($r as $rr) {
    +            $retrievers[$rr['contact']][$rr['k']] = $rr['v'];
    +        }
    +        foreach ($retrievers as $k => $v) {
    +            $rr = q("SELECT `uid` FROM `contact` WHERE `id` = %d", intval($k));
    +            $uid = $rr[0]['uid'];
    +            $v['images'] = 'on';
    +            q("INSERT INTO `retriever_rule` (`uid`, `contact-id`, `data`) VALUES (%d, %d, '%s')",
    +              intval($uid), intval($k), dbesc(json_encode($v)));
    +        }
    +        q("DELETE FROM `pconfig` WHERE `cat` LIKE 'retriever_%%'");
    +        set_config('retriever', 'dbversion', '0.2');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.2') {
    +        q("ALTER TABLE `retriever_resource` DROP COLUMN `retriever`");
    +        set_config('retriever', 'dbversion', '0.3');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.3') {
    +        q("ALTER TABLE `retriever_item` MODIFY COLUMN `item-uri` varchar(800) CHARACTER SET ascii NOT NULL");
    +        q("ALTER TABLE `retriever_resource` MODIFY COLUMN `url` varchar(800) CHARACTER SET ascii NOT NULL");
    +        set_config('retriever', 'dbversion', '0.4');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.4') {
    +        q("ALTER TABLE `retriever_item` ADD COLUMN `finished` tinyint(1) unsigned NOT NULL DEFAULT '0'");
    +        set_config('retriever', 'dbversion', '0.5');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.5') {
    +        q('ALTER TABLE `retriever_resource` CHANGE `created` `created` timestamp NOT NULL DEFAULT now()');
    +        q('ALTER TABLE `retriever_resource` CHANGE `completed` `completed` timestamp NULL DEFAULT NULL');
    +        q('ALTER TABLE `retriever_resource` CHANGE `last-try` `last-try` timestamp NULL DEFAULT NULL');
    +        q('ALTER TABLE `retriever_item` DROP KEY `all`');
    +        q('ALTER TABLE `retriever_item` ADD KEY `all` (`item-uri`, `item-uid`, `contact-id`)');
    +        set_config('retriever', 'dbversion', '0.6');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.6') {
    +        q('ALTER TABLE `retriever_item` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
    +        q('ALTER TABLE `retriever_item` CHANGE `item-uri` `item-uri`  varchar(800) CHARACTER SET ascii COLLATE ascii_bin NOT NULL');
    +        q('ALTER TABLE `retriever_resource` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
    +        q('ALTER TABLE `retriever_resource` CHANGE `url` `url`  varchar(800) CHARACTER SET ascii COLLATE ascii_bin NOT NULL');
    +        q('ALTER TABLE `retriever_rule` CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin');
    +        set_config('retriever', 'dbversion', '0.7');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.7') {
    +        $r = q("SELECT `id`, `data` FROM `retriever_rule`");
    +        foreach ($r as $rr) {
    +            logger('retriever_install: retriever ' . $rr['id'] . ' old config ' . $rr['data'], LOGGER_DATA);
    +            $data = json_decode($rr['data'], true);
    +            if ($data['pattern']) {
    +                $matches = array();
    +                if (preg_match("/\/(.*)\//", $data['pattern'], $matches)) {
    +                    $data['pattern'] = $matches[1];
    +                }
    +            }
    +            if ($data['match']) {
    +                $include = array();
    +                foreach (explode('|', $data['match']) as $component) {
    +                    $matches = array();
    +                    if (preg_match("/([A-Za-z][A-Za-z0-9]*)\[@([A-Za-z][a-z0-9]*)='([^']*)'\]/", $component, $matches)) {
    +                        $include[] = array(
    +                            'element' => $matches[1],
    +                            'attribute' => $matches[2],
    +                            'value' => $matches[3]);
    +                    }
    +                    if (preg_match("/([A-Za-z][A-Za-z0-9]*)\[contains(concat(' ',normalize-space(@class),' '),' ([^ ']+) ')]/", $component, $matches)) {
    +                        $include[] = array(
    +                            'element' => $matches[1],
    +                            'attribute' => $matches[2],
    +                            'value' => $matches[3]);
    +                    }
    +                }
    +                $data['include'] = $include;
    +                unset($data['match']);
    +            }
    +            if ($data['remove']) {
    +                $exclude = array();
    +                foreach (explode('|', $data['remove']) as $component) {
    +                    $matches = array();
    +                    if (preg_match("/([A-Za-z][A-Za-z0-9]*)\[@([A-Za-z][a-z0-9]*)='([^']*)'\]/", $component, $matches)) {
    +                        $exclude[] = array(
    +                            'element' => $matches[1],
    +                            'attribute' => $matches[2],
    +                            'value' => $matches[3]);
    +                    }
    +                    if (preg_match("/([A-Za-z][A-Za-z0-9]*)\[contains(concat(' ',normalize-space(@class),' '),' ([^ ']+) ')]/", $component, $matches)) {
    +                        $exclude[] = array(
    +                            'element' => $matches[1],
    +                            'attribute' => $matches[2],
    +                            'value' => $matches[3]);
    +                    }
    +                }
    +                $data['exclude'] = $exclude;
    +                unset($data['remove']);
    +            }
    +            $r = q('UPDATE `retriever_rule` SET `data` = "%s" WHERE `id` = %d', dbesc(json_encode($data)), $rr['id']);
    +            logger('retriever_install: retriever ' . $rr['id'] . ' new config ' . json_encode($data), LOGGER_DATA);
    +        }
    +        set_config('retriever', 'dbversion', '0.8');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.8') {
    +        q("ALTER TABLE `retriever_resource` ADD COLUMN `http-code` smallint(1) unsigned NULL DEFAULT NULL");
    +        set_config('retriever', 'dbversion', '0.9');
    +    }
    +    if (get_config('retriever', 'dbversion') == '0.9') {
    +        q("ALTER TABLE `retriever_item` DROP COLUMN `parent`");
    +        q("ALTER TABLE `retriever_resource` ADD COLUMN `redirect-url` varchar(800) CHARACTER SET ascii COLLATE ascii_bin NULL DEFAULT NULL");
    +        set_config('retriever', 'dbversion', '0.10');
    +    }
    +
    +    if (get_config('retriever', 'dbversion') != '0.10') {
    +        $schema = file_get_contents(dirname(__file__).'/database.sql');
    +        $arr = explode(';', $schema);
    +        foreach ($arr as $a) {
    +            $r = q($a);
    +        }
    +        set_config('retriever', 'dbversion', '0.10');
    +    }
    +}
    +
    +function retriever_uninstall() {
    +    unregister_hook('plugin_settings', 'addon/retriever/retriever.php', 'retriever_plugin_settings');
    +    unregister_hook('plugin_settings_post', 'addon/retriever/retriever.php', 'retriever_plugin_settings_post');
    +    unregister_hook('post_remote', 'addon/retriever/retriever.php', 'retriever_post_remote_hook');
    +    unregister_hook('plugin_settings', 'addon/retriever/retriever.php', 'retriever_plugin_settings');
    +    unregister_hook('plugin_settings_post', 'addon/retriever/retriever.php', 'retriever_plugin_settings_post');
    +    unregister_hook('contact_photo_menu', 'addon/retriever/retriever.php', 'retriever_contact_photo_menu');
    +    unregister_hook('cron', 'addon/retriever/retriever.php', 'retriever_cron');
    +}
    +
    +function retriever_module() {}
    +
    +function retriever_cron($a, $b) {
    +    // 100 is a nice sane number.  Maybe this should be configurable.
    +    retriever_retrieve_items(100);
    +    retriever_tidy();
    +}
    +
    +$retriever_item_count = 0;
    +
    +function retriever_retrieve_items($max_items) {
    +    global $retriever_item_count;
    +
    +    $retriever_schedule = array(array(1,'minute'),
    +                                array(10,'minute'),
    +                                array(1,'hour'),
    +                                array(1,'day'),
    +                                array(2,'day'),
    +                                array(1,'week'),
    +                                array(1,'month'));
    +
    +    $schedule_clauses = array();
    +    for ($i = 0; $i < count($retriever_schedule); $i++) {
    +        $num = $retriever_schedule[$i][0];
    +        $unit = $retriever_schedule[$i][1];
    +        array_push($schedule_clauses,
    +                   '(`num-tries` = ' . $i . ' AND TIMESTAMPADD(' . dbesc($unit) .
    +                   ', ' . intval($num) . ', `last-try`) < now())');
    +    }
    +
    +    $retrieve_items = $max_items - $retriever_item_count;
    +    logger('retriever_retrieve_items: asked for maximum ' . $max_items . ', already retrieved ' . $retriever_item_count . ', retrieve ' . $retrieve_items, LOGGER_DEBUG);
    +    do {
    +        $r = q("SELECT * FROM `retriever_resource` WHERE `completed` IS NULL AND (`last-try` IS NULL OR %s) ORDER BY `last-try` ASC LIMIT %d",
    +               dbesc(implode($schedule_clauses, ' OR ')),
    +               intval($retrieve_items));
    +        if (!is_array($r)) {
    +            break;
    +        }
    +        if (count($r) == 0) {
    +            break;
    +        }
    +        logger('retriever_retrieve_items: found ' . count($r) . ' waiting resources in database', LOGGER_DEBUG);
    +        foreach ($r as $rr) {
    +            retrieve_resource($rr);
    +            $retriever_item_count++;
    +        }
    +        $retrieve_items = $max_items - $retriever_item_count;
    +    }
    +    while ($retrieve_items > 0);
    +
    +    /* Look for items that are waiting even though the resource has
    +     * completed.  This usually happens because we've been asked to
    +     * retrospectively apply a config change.  It could also happen
    +     * due to a cron job dying or something. */
    +    $r = q("SELECT retriever_resource.`id` as resource, retriever_item.`id` as item FROM retriever_resource, retriever_item, retriever_rule WHERE retriever_item.`finished` = 0 AND retriever_item.`resource` = retriever_resource.`id` AND retriever_resource.`completed` IS NOT NULL AND retriever_item.`contact-id` = retriever_rule.`contact-id` AND retriever_item.`item-uid` = retriever_rule.`uid` LIMIT %d",
    +           intval($retrieve_items));
    +    if (!$r) {
    +        $r = array();
    +    }
    +    logger('retriever_retrieve_items: items waiting even though resource has completed: ' . count($r), LOGGER_DEBUG);
    +    foreach ($r as $rr) {
    +        $resource = q("SELECT * FROM retriever_resource WHERE `id` = %d", $rr['resource']);
    +        $retriever_item = retriever_get_retriever_item($rr['item']);
    +        if (!$retriever_item) {
    +            logger('retriever_retrieve_items: no retriever item with id ' . $rr['item'], LOGGER_NORMAL);
    +            continue;
    +        }
    +        $item = retriever_get_item($retriever_item);
    +        if (!$item) {
    +            logger('retriever_retrieve_items: no item ' . $retriever_item['item-uri'], LOGGER_NORMAL);
    +            continue;
    +        }
    +        $retriever = get_retriever($item['contact-id'], $item['uid']);
    +        if (!$retriever) {
    +            logger('retriever_retrieve_items: no retriever for item ' .
    +                   $retriever_item['item-uri'] . ' ' . $retriever_item['uid'] . ' ' . $item['contact-id'],
    +                   LOGGER_NORMAL);
    +            continue;
    +        }
    +        retriever_apply_completed_resource_to_item($retriever, $item, $resource[0]);
    +        q("UPDATE `retriever_item` SET `finished` = 1 WHERE id = %d",
    +          intval($retriever_item['id']));
    +        retriever_check_item_completed($item);
    +    }
    +}
    +
    +function retriever_tidy() {
    +    q("DELETE FROM retriever_resource WHERE completed IS NOT NULL AND completed < DATE_SUB(now(), INTERVAL 1 WEEK)");
    +    q("DELETE FROM retriever_resource WHERE completed IS NULL AND created < DATE_SUB(now(), INTERVAL 3 MONTH)");
    +
    +    $r = q("SELECT retriever_item.id FROM retriever_item LEFT OUTER JOIN retriever_resource ON (retriever_item.resource = retriever_resource.id) WHERE retriever_resource.id is null");
    +    logger('retriever_tidy: found ' . count($r) . ' retriever_items with no retriever_resource');
    +    foreach ($r as $rr) {
    +        q('DELETE FROM retriever_item WHERE id = %d', intval($rr['id']));
    +    }
    +}
    +
    +function retrieve_resource($resource) {
    +    $a = get_app();
    +
    +    logger('retrieve_resource: ' . ($resource['num-tries'] + 1) .
    +           ' attempt at resource ' . $resource['id'] . ' ' . $resource['url'], LOGGER_DEBUG);
    +    $redirects;
    +    $cookiejar = tempnam(get_temppath(), 'cookiejar-retriever-');
    +    $fetch_result = z_fetch_url($resource['url'], $resource['binary'], $redirects, array('cookiejar' => $cookiejar));
    +    unlink($cookiejar);
    +    $resource['data'] = $fetch_result['body'];
    +    $resource['http-code'] = $a->get_curl_code();
    +    $resource['type'] = $a->get_curl_content_type();
    +    $resource['redirect-url'] = $fetch_result['redirect_url'];
    +    logger('retrieve_resource: got code ' . $resource['http-code'] .
    +           ' retrieving resource ' . $resource['id'] .
    +           ' final url ' . $resource['redirect-url'], LOGGER_DEBUG);
    +    q("UPDATE `retriever_resource` SET `last-try` = now(), `num-tries` = `num-tries` + 1, `http-code` = %d, `redirect-url` = '%s' WHERE id = %d",
    +      intval($resource['http-code']),
    +      dbesc($resource['redirect-url']),
    +      intval($resource['id']));
    +    if ($resource['data']) {
    +        q("UPDATE `retriever_resource` SET `completed` = now(), `data` = '%s', `type` = '%s' WHERE id = %d",
    +          dbesc($resource['data']),
    +          dbesc($resource['type']),
    +          intval($resource['id']));
    +        retriever_resource_completed($resource);
    +    }
    +}
    +
    +function get_retriever($contact_id, $uid, $create = false) {
    +    $r = q("SELECT * FROM `retriever_rule` WHERE `contact-id` = %d AND `uid` = %d",
    +           intval($contact_id), intval($uid));
    +    if (count($r)) {
    +        $r[0]['data'] = json_decode($r[0]['data'], true);
    +        return $r[0];
    +    }
    +    if ($create) {
    +        q("INSERT INTO `retriever_rule` (`uid`, `contact-id`) VALUES (%d, %d)",
    +          intval($uid), intval($contact_id));
    +        $r = q("SELECT * FROM `retriever_rule` WHERE `contact-id` = %d AND `uid` = %d",
    +               intval($contact_id), intval($uid));
    +        return $r[0];
    +    }
    +}
    +
    +function retriever_get_retriever_item($id) {
    +    $retriever_items = q("SELECT * FROM `retriever_item` WHERE id = %d", intval($id));
    +    if (count($retriever_items) != 1) {
    +        logger('retriever_get_retriever_item: unable to find retriever_item ' . $id, LOGGER_NORMAL);
    +        return;
    +    }
    +    return $retriever_items[0];
    +}
    +
    +function retriever_get_item($retriever_item) {
    +    $items = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d",
    +               dbesc($retriever_item['item-uri']),
    +               intval($retriever_item['item-uid']),
    +               intval($retriever_item['contact-id']));
    +    if (count($items) != 1) {
    +        logger('retriever_get_item: unexpected number of results ' .
    +               count($items) . " when searching for item $uri $uid $cid", LOGGER_NORMAL);
    +        return;
    +    }
    +    return $items[0];
    +}
    +
    +function retriever_item_completed($retriever_item_id, $resource) {
    +    logger('retriever_item_completed: id ' . $retriever_item_id . ' url ' . $resource['url'], LOGGER_DEBUG);
    +
    +    $retriever_item = retriever_get_retriever_item($retriever_item_id);
    +    if (!$retriever_item) {
    +        return;
    +    }
    +    // Note: the retriever might be null.  Doesn't matter.
    +    $retriever = get_retriever($retriever_item['contact-id'], $retriever_item['item-uid']);
    +    $item = retriever_get_item($retriever_item);
    +    if (!$item) {
    +        return;
    +    }
    +
    +    retriever_apply_completed_resource_to_item($retriever, $item, $resource);
    +
    +    q("UPDATE `retriever_item` SET `finished` = 1 WHERE id = %d",
    +      intval($retriever_item['id']));
    +    retriever_check_item_completed($item);
    +}
    +
    +function retriever_resource_completed($resource) {
    +    logger('retriever_resource_completed: id ' . $resource['id'] . ' url ' . $resource['url'], LOGGER_DEBUG);
    +    $r = q("SELECT `id` FROM `retriever_item` WHERE `resource` = %d", $resource['id']);
    +    foreach ($r as $rr) {
    +        retriever_item_completed($rr['id'], $resource);
    +    }
    +}
    +
    +function apply_retrospective($retriever, $num) {
    +    $r = q("SELECT * FROM `item` WHERE `contact-id` = %d ORDER BY `received` DESC LIMIT %d",
    +           intval($retriever['contact-id']), intval($num));
    +    foreach ($r as $item) {
    +        q('UPDATE `item` SET `visible` = 0 WHERE `id` = %d', $item['id']);
    +        q('UPDATE `thread` SET `visible` = 0 WHERE `iid` = %d', $item['id']);
    +        retriever_on_item_insert($retriever, $item);
    +    }
    +}
    +
    +function retriever_on_item_insert($retriever, &$item) {
    +    if (!$retriever || !$retriever['id']) {
    +        logger('retriever_on_item_insert: No retriever supplied', LOGGER_NORMAL);
    +        return;
    +    }
    +    if (!$retriever["data"]['enable'] == "on") {
    +        return;
    +    }
    +    if ($retriever["data"]['pattern']) {
    +        $url = preg_replace('/' . $retriever["data"]['pattern'] . '/', $retriever["data"]['replace'], $item['plink']);
    +        logger('retriever_on_item_insert: Changed ' . $item['plink'] . ' to ' . $url, LOGGER_DATA);
    +    }
    +    else {
    +        $url = $item['plink'];
    +    }
    +
    +    $resource = add_retriever_resource($url);
    +    $retriever_item_id = add_retriever_item($item, $resource);
    +}
    +
    +function add_retriever_resource($url, $binary = false) {
    +    logger('add_retriever_resource: ' . $url, LOGGER_DEBUG);
    +
    +    $scheme = parse_url($url, PHP_URL_SCHEME);
    +    if ($scheme == 'data') {
    +        $fp = fopen($url, 'r');
    +        $meta = stream_get_meta_data($fp);
    +        $type = $meta['mediatype'];
    +        $data = stream_get_contents($fp);
    +        fclose($fp);
    +
    +        $url = 'md5://' . hash('md5', $url);
    +        $r = q("SELECT * FROM `retriever_resource` WHERE `url` = '%s'", dbesc($url));
    +        $resource = $r[0];
    +        if (count($r)) {
    +            logger('add_retriever_resource: Resource ' . $url . ' already requested', LOGGER_DEBUG);
    +            return $resource;
    +        }
    +
    +        logger('retrieve_resource: got data URL type ' . $resource['type'], LOGGER_DEBUG);
    +        q("INSERT INTO `retriever_resource` (`type`, `binary`, `url`, `completed`, `data`) " .
    +          "VALUES ('%s', %d, '%s', now(), '%s')",
    +          dbesc($type),
    +          intval($binary ? 1 : 0),
    +          dbesc($url),
    +          dbesc($data));
    +        $r = q("SELECT * FROM `retriever_resource` WHERE `url` = '%s'", dbesc($url));
    +        $resource = $r[0];
    +        if (count($r)) {
    +            retriever_resource_completed($resource);
    +        }
    +        return $resource;
    +    }
    +
    +    if (strlen($url) > 800) {
    +        logger('add_retriever_resource: URL is longer than 800 characters', LOGGER_NORMAL);
    +    }
    +
    +    $r = q("SELECT * FROM `retriever_resource` WHERE `url` = '%s'", dbesc($url));
    +    $resource = $r[0];
    +    if (count($r)) {
    +        logger('add_retriever_resource: Resource ' . $url . ' already requested', LOGGER_DEBUG);
    +        return $resource;
    +    }
    +
    +    q("INSERT INTO `retriever_resource` (`binary`, `url`) " .
    +      "VALUES (%d, '%s')", intval($binary ? 1 : 0), dbesc($url));
    +    $r = q("SELECT * FROM `retriever_resource` WHERE `url` = '%s'", dbesc($url));
    +    return $r[0];
    +}
    +
    +function add_retriever_item(&$item, $resource) {
    +    logger('add_retriever_item: ' . $resource['url'] . ' for ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DEBUG);
    +
    +    q("INSERT INTO `retriever_item` (`item-uri`, `item-uid`, `contact-id`, `resource`) " .
    +      "VALUES ('%s', %d, %d, %d)",
    +      dbesc($item['uri']), intval($item['uid']), intval($item['contact-id']), intval($resource["id"]));
    +    $r = q("SELECT id FROM `retriever_item` WHERE " .
    +           "`item-uri` = '%s' AND `item-uid` = %d AND `contact-id` = %d AND `resource` = %d ORDER BY id DESC",
    +           dbesc($item['uri']), intval($item['uid']), intval($item['contact-id']), intval($resource['id']));
    +    if (!count($r)) {
    +        logger("add_retriever_item: couldn't create retriever item for " .
    +               $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id'],
    +               LOGGER_NORMAL);
    +        return;
    +    }
    +    logger('add_retriever_item: created retriever_item ' . $r[0]['id'] . ' for item ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DEBUG);
    +    return $r[0]['id'];
    +}
    +
    +function retriever_get_encoding($resource) {
    +    $matches = array();
    +    if (preg_match('/charset=(.*)/', $resource['type'], $matches)) {
    +        return trim(array_pop($matches));
    +    }
    +    return 'utf-8';
    +}
    +
    +function retriever_apply_xslt_text($xslt_text, $doc) {
    +    if (!$xslt_text) {
    +        logger('retriever_apply_xslt_text: empty XSLT text', LOGGER_NORMAL);
    +        return $doc;
    +    }
    +    $xslt_doc = new DOMDocument();
    +    if (!$xslt_doc->loadXML($xslt_text)) {
    +        logger('retriever_apply_xslt_text: could not load XML', LOGGER_NORMAL);
    +        return $doc;
    +    }
    +    $xp = new XsltProcessor();
    +    $xp->importStylesheet($xslt_doc);
    +    $result = $xp->transformToDoc($doc);
    +    return $result;
    +}
    +
    +function retriever_apply_dom_filter($retriever, &$item, $resource) {
    +    logger('retriever_apply_dom_filter: applying XSLT to ' . $item['id'] . ' ' . $item['uri'] . ' contact ' . $item['contact-id'], LOGGER_DEBUG);
    +
    +    if (!$retriever['data']['include'] && !$retriever['data']['customxslt']) {
    +        return;
    +    }
    +    if (!$resource['data']) {
    +        logger('retriever_apply_dom_filter: no text to work with', LOGGER_NORMAL);
    +        return;
    +    }
    +
    +    $encoding = retriever_get_encoding($resource);
    +    $content = mb_convert_encoding($resource['data'], 'HTML-ENTITIES', $encoding);
    +    $doc = new DOMDocument('1.0', 'UTF-8');
    +    if (strpos($resource['type'], 'html') !== false) {
    +        @$doc->loadHTML($content);
    +    }
    +    else {
    +        $doc->loadXML($content);
    +    }
    +
    +    $params = array('$spec' => $retriever['data']);
    +    $extract_template = get_markup_template('extract.tpl', 'addon/retriever/');
    +    $extract_xslt = replace_macros($extract_template, $params);
    +    if ($retriever['data']['include']) {
    +        $doc = retriever_apply_xslt_text($extract_xslt, $doc);
    +    }
    +    if ($retriever['data']['customxslt']) {
    +        $doc = retriever_apply_xslt_text($retriever['data']['customxslt'], $doc);
    +    }
    +    if (!$doc) {
    +        logger('retriever_apply_dom_filter: failed to apply extract XSLT template', LOGGER_NORMAL);
    +        return;
    +    }
    +
    +    $components = parse_url($resource['redirect-url']);
    +    $rooturl = $components['scheme'] . "://" . $components['host'];
    +    $dirurl = $rooturl . dirname($components['path']) . "/";
    +    $params = array('$dirurl' => $dirurl, '$rooturl' => $rooturl);
    +    $fix_urls_template = get_markup_template('fix-urls.tpl', 'addon/retriever/');
    +    $fix_urls_xslt = replace_macros($fix_urls_template, $params);
    +    $doc = retriever_apply_xslt_text($fix_urls_xslt, $doc);
    +    if (!$doc) {
    +        logger('retriever_apply_dom_filter: failed to apply fix urls XSLT template', LOGGER_NORMAL);
    +        return;
    +    }
    +
    +    $item['body'] = html2bbcode($doc->saveXML());
    +    if (!strlen($item['body'])) {
    +        logger('retriever_apply_dom_filter retriever ' . $retriever['id'] . ' item ' . $item['id'] . ': output was empty', LOGGER_NORMAL);
    +        return;
    +    }
    +    $item['body'] .= "\n\n" . t('Retrieved') . ' ' . date("Y-m-d") . ': [url=';
    +    $item['body'] .=  $item['plink'];
    +    $item['body'] .= ']' . $item['plink'] . '[/url]';
    +    q("UPDATE `item` SET `body` = '%s' WHERE `id` = %d",
    +      dbesc($item['body']), intval($item['id']));
    +}
    +
    +function retrieve_images(&$item) {
    +    $matches1 = array();
    +    preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", $item["body"], $matches1);
    +    $matches2 = array();
    +    preg_match_all("/\[img\](.*?)\[\/img\]/ism", $item["body"], $matches2);
    +    $matches = array_merge($matches1[3], $matches2[1]);
    +    logger('retrieve_images: found ' . count($matches) . ' images for item ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DEBUG);
    +    foreach ($matches as $url) {
    +        if (strpos($url, get_app()->get_baseurl()) === FALSE) {
    +            $resource = add_retriever_resource($url, true);
    +            if (!$resource['completed']) {
    +                add_retriever_item($item, $resource);
    +            }
    +            else {
    +                retriever_transform_images($item, $resource);
    +            }
    +        }
    +    }
    +}
    +
    +function retriever_check_item_completed(&$item)
    +{
    +    $r = q('SELECT count(*) FROM retriever_item WHERE `item-uri` = "%s" ' .
    +           'AND `item-uid` = %d AND `contact-id` = %d AND `finished` = 0',
    +           dbesc($item['uri']), intval($item['uid']),
    +           intval($item['contact-id']));
    +    $waiting = $r[0]['count(*)'];
    +    logger('retriever_check_item_completed: item ' . $item['uri'] . ' ' . $item['uid']
    +           . ' '. $item['contact-id'] . ' waiting for ' . $waiting . ' resources', LOGGER_DEBUG);
    +    $old_visible = $item['visible'];
    +    $item['visible'] = $waiting ? 0 : 1;
    +    if (($item['id'] > 0) && ($old_visible != $item['visible'])) {
    +        logger('retriever_check_item_completed: changing visible flag to ' . $item['visible'] . ' and invoking notifier ("edit_post", ' . $item['id'] . ')', LOGGER_DEBUG);
    +        q("UPDATE `item` SET `visible` = %d WHERE `id` = %d",
    +          intval($item['visible']),
    +          intval($item['id']));
    +        q("UPDATE `thread` SET `visible` = %d WHERE `iid` = %d",
    +          intval($item['visible']),
    +          intval($item['id']));
    +    }
    +}
    +
    +function retriever_apply_completed_resource_to_item($retriever, &$item, $resource) {
    +    logger('retriever_apply_completed_resource_to_item: retriever ' .
    +           ($retriever ? $retriever['id'] : 'none') .
    +           ' resource ' . $resource['url'] . ' plink ' . $item['plink'], LOGGER_DEBUG);
    +    if (strpos($resource['type'], 'image') !== false) {
    +        retriever_transform_images($item, $resource);
    +    }
    +    if (!$retriever) {
    +        return;
    +    }
    +    if ((strpos($resource['type'], 'html') !== false) ||
    +        (strpos($resource['type'], 'xml') !== false)) {
    +        retriever_apply_dom_filter($retriever, $item, $resource);
    +        if ($retriever["data"]['images'] ) {
    +            retrieve_images($item);
    +        }
    +    }
    +}
    +
    +function retriever_store_photo($item, &$resource) {
    +    $hash = photo_new_resource();
    +
    +    if (class_exists('Imagick')) {
    +        try {
    +            $image = new Imagick();
    +            $image->readImageBlob($resource['data']);
    +            $resource['width'] = $image->getImageWidth();
    +            $resource['height'] = $image->getImageHeight();
    +        }
    +        catch (Exception $e) {
    +            logger("ImageMagick couldn't process image " . $resource['id'] . " " . $resource['url'] . ' length ' . strlen($resource['data']) . ': ' . $e->getMessage(), LOGGER_DEBUG);
    +            return false;
    +        }
    +    }
    +    if (!array_key_exists('width', $resource)) {
    +        $image = @imagecreatefromstring($resource['data']);
    +        if ($image === false) {
    +            logger("Couldn't process image " . $resource['id'] . " " . $resource['url'], LOGGER_DEBUG);
    +            return false;
    +        }
    +        $resource['width']  = imagesx($image);
    +        $resource['height'] = imagesy($image);
    +        imagedestroy($image);
    +    }
    +
    +    $url_components = parse_url($resource['url']);
    +    $filename = basename($url_components['path']);
    +    if (!strlen($filename)) {
    +        $filename = 'image';
    +    }
    +    $r = q("INSERT INTO `photo`
    +                ( `uid`, `contact-id`, `guid`, `resource-id`, `created`, `edited`, `filename`, `type`, `album`, `height`, `width`, `datasize`, `data` )
    +                VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, '%s' )",
    +           intval($item['item-uid']),
    +           intval($item['contact-id']),
    +           dbesc(get_guid()),
    +           dbesc($hash),
    +           dbesc(datetime_convert()),
    +           dbesc(datetime_convert()),
    +           dbesc($filename),
    +           dbesc($resource['type']),
    +           dbesc('Retrieved Images'),
    +           intval($resource['height']),
    +           intval($resource['width']),
    +           intval(strlen($resource['data'])),
    +           dbesc($resource['data'])
    +        );
    +
    +    return $hash;
    +}
    +
    +function retriever_transform_images(&$item, $resource) {
    +    if (!$resource["data"]) {
    +        logger('retriever_transform_images: no data available for '
    +               . $resource['id'] . ' ' . $resource['url'], LOGGER_NORMAL);
    +        return;
    +    }
    +
    +    $hash = retriever_store_photo($item, $resource);
    +    if ($hash === false) {
    +        logger('retriever_transform_images: unable to store photo '
    +               . $resource['id'] . ' ' . $resource['url'], LOGGER_NORMAL);
    +        return;
    +    }
    +
    +    $new_url = get_app()->get_baseurl() . '/photo/' . $hash;
    +    logger('retriever_transform_images: replacing ' . $resource['url'] . ' with ' .
    +           $new_url . ' in item ' . $item['plink'], LOGGER_DEBUG);
    +    $transformed = str_replace($resource["url"], $new_url, $item['body']);
    +    if ($transformed === $item['body']) {
    +        return;
    +    }
    +
    +    $item['body'] = $transformed;
    +    q("UPDATE `item` SET `body` = '%s' WHERE `plink` = '%s' AND `uid` = %d AND `contact-id` = %d",
    +      dbesc($item['body']),
    +      dbesc($item['plink']),
    +      intval($item['uid']),
    +      intval($item['contact-id']));
    +}
    +
    +function retriever_content($a) {
    +    if (!local_user()) {
    +        $a->page['content'] .= "

    Please log in

    "; + return; + } + if ($a->argv[1] === 'help') { + $feeds = q("SELECT `id`, `name`, `thumb` FROM contact WHERE `uid` = %d AND `network` = 'feed'", + local_user()); + foreach ($feeds as $k=>$v) { + $feeds[$k]['url'] = $a->get_baseurl() . '/retriever/' . $v['id']; + } + $template = get_markup_template('/help.tpl', 'addon/retriever/'); + $a->page['content'] .= replace_macros($template, array( + '$config' => $a->get_baseurl() . '/settings/addon', + '$feeds' => $feeds)); + return; + } + if ($a->argv[1]) { + $retriever = get_retriever($a->argv[1], local_user(), false); + + if (x($_POST["id"])) { + $retriever = get_retriever($a->argv[1], local_user(), true); + $retriever["data"] = array(); + foreach (array('pattern', 'replace', 'enable', 'images', 'customxslt') as $setting) { + if (x($_POST['retriever_' . $setting])) { + $retriever["data"][$setting] = $_POST['retriever_' . $setting]; + } + } + foreach ($_POST as $k=>$v) { + if (preg_match("/retriever-(include|exclude)-(\d+)-(element|attribute|value)/", $k, $matches)) { + $retriever['data'][$matches[1]][intval($matches[2])][$matches[3]] = $v; + } + } + // You've gotta have an element, even if it's just "*" + foreach ($retriever['data']['include'] as $k=>$clause) { + if (!$clause['element']) { + unset($retriever['data']['include'][$k]); + } + } + foreach ($retriever['data']['exclude'] as $k=>$clause) { + if (!$clause['element']) { + unset($retriever['data']['exclude'][$k]); + } + } + q("UPDATE `retriever_rule` SET `data`='%s' WHERE `id` = %d", + dbesc(json_encode($retriever["data"])), intval($retriever["id"])); + $a->page['content'] .= "

    Settings Updated"; + if (x($_POST["retriever_retrospective"])) { + apply_retrospective($retriever, $_POST["retriever_retrospective"]); + $a->page['content'] .= " and retrospectively applied to " . $_POST["apply"] . " posts"; + } + $a->page['content'] .= ".

    "; + } + + $template = get_markup_template('/rule-config.tpl', 'addon/retriever/'); + $a->page['content'] .= replace_macros($template, array( + '$enable' => array( + 'retriever_enable', + t('Enabled'), + $retriever['data']['enable']), + '$pattern' => array( + 'retriever_pattern', + t('URL Pattern'), + $retriever["data"]['pattern'], + t('Regular expression matching part of the URL to replace')), + '$replace' => array( + 'retriever_replace', + t('URL Replace'), + $retriever["data"]['replace'], + t('Text to replace matching part of above regular expression')), + '$images' => array( + 'retriever_images', + t('Download Images'), + $retriever['data']['images']), + '$retrospective' => array( + 'retriever_retrospective', + t('Retrospectively Apply'), + '0', + t('Reapply the rules to this number of posts')), + '$customxslt' => array( + 'retriever_customxslt', + t('Custom XSLT'), + $retriever['data']['customxslt'], + t("When standard rules aren't enough, apply custom XSLT to the article")), + '$title' => t('Retrieve Feed Content'), + '$help' => $a->get_baseurl() . '/retriever/help', + '$help_t' => t('Get Help'), + '$submit_t' => t('Submit'), + '$submit' => t('Save Settings'), + '$id' => ($retriever["id"] ? $retriever["id"] : "create"), + '$tag_t' => t('Tag'), + '$attribute_t' => t('Attribute'), + '$value_t' => t('Value'), + '$add_t' => t('Add'), + '$remove_t' => t('Remove'), + '$include_t' => t('Include'), + '$include' => $retriever['data']['include'], + '$exclude_t' => t('Exclude'), + '$exclude' => $retriever["data"]['exclude'])); + return; + } +} + +function retriever_contact_photo_menu($a, &$args) { + if (!$args) { + return; + } + if ($args["contact"]["network"] == "feed") { + $args["menu"][ 'retriever' ] = array(t('Retriever'), $a->get_baseurl() . '/retriever/' . $args["contact"]['id']); + } +} + +function retriever_post_remote_hook(&$a, &$item) { + logger('retriever_post_remote_hook: ' . $item['uri'] . ' ' . $item['uid'] . ' ' . $item['contact-id'], LOGGER_DEBUG); + + $retriever = get_retriever($item['contact-id'], $item["uid"], false); + if ($retriever) { + retriever_on_item_insert($retriever, $item); + } + else { + if (get_pconfig($item["uid"], 'retriever', 'oembed')) { + // Convert to HTML and back to take advantage of bbcode's resolution of oembeds. + $body = html2bbcode(bbcode($item['body'])); + if ($body) { + $item['body'] = $body; + } + } + if (get_pconfig($item["uid"], 'retriever', 'all_photos')) { + retrieve_images($item, null); + } + } + retriever_check_item_completed($item); +} + +function retriever_plugin_settings(&$a,&$s) { + $all_photos = get_pconfig(local_user(), 'retriever', 'all_photos'); + $oembed = get_pconfig(local_user(), 'retriever', 'oembed'); + $template = get_markup_template('/settings.tpl', 'addon/retriever/'); + $s .= replace_macros($template, array( + '$allphotos' => array( + 'retriever_all_photos', + t('All Photos'), + $all_photos, + t('Check this to retrieve photos for all posts')), + '$oembed' => array( + 'retriever_oembed', + t('Resolve OEmbed'), + $oembed, + t('Check this to attempt to retrieve embedded content for all posts - useful e.g. for Facebook posts')), + '$submit' => t('Save Settings'), + '$title' => t('Retriever Settings'), + '$help' => $a->get_baseurl() . '/retriever/help')); +} + +function retriever_plugin_settings_post($a,$post) { + if ($_POST['retriever_all_photos']) { + set_pconfig(local_user(), 'retriever', 'all_photos', $_POST['retriever_all_photos']); + } + else { + del_pconfig(local_user(), 'retriever', 'all_photos'); + } + if ($_POST['retriever_oembed']) { + set_pconfig(local_user(), 'retriever', 'oembed', $_POST['retriever_oembed']); + } + else { + del_pconfig(local_user(), 'retriever', 'oembed'); + } +} diff --git a/retriever/templates/extract.tpl b/retriever/templates/extract.tpl new file mode 100644 index 00000000..fd38bde6 --- /dev/null +++ b/retriever/templates/extract.tpl @@ -0,0 +1,31 @@ + + + + + +{{function clause_xpath}} +{{if !$clause.attribute}} +{{$clause.element}}{{elseif $clause.attribute == 'class'}} +{{$clause.element}}[contains(concat(' ', normalize-space(@class), ' '), '{{$clause.value}}')]{{else}} +{{$clause.element}}[@{{$clause.attribute}}='{{$clause.value}}']{{/if}} +{{/function}} + +{{foreach $spec.include as $clause}} + + + + + +{{/foreach}} + +{{foreach $spec.exclude as $clause}} + +{{/foreach}} + + + + + + + + diff --git a/retriever/templates/fix-urls.tpl b/retriever/templates/fix-urls.tpl new file mode 100644 index 00000000..5bb665ab --- /dev/null +++ b/retriever/templates/fix-urls.tpl @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/retriever/templates/help.tpl b/retriever/templates/help.tpl new file mode 100644 index 00000000..10b421d0 --- /dev/null +++ b/retriever/templates/help.tpl @@ -0,0 +1,148 @@ +

    Retriever Plugin Help

    +

    +This plugin replaces the short excerpts you normally get in RSS feeds +with the full content of the article from the source website. You +specify which part of the page you're interested in with a set of +rules. When each item arrives, the plugin downloads the full page +from the website, extracts content using the rules, and replaces the +original article. +

    +

    +There's a few reasons you may want to do this. The source website +might be slow or overloaded. The source website might be +untrustworthy, in which case using Friendica to scrub the HTML is a +good idea. You might be on a LAN that blacklists certain websites. +It also works neatly with the mailstream plugin, allowing you to read +a news stream comfortably without needing continuous Internet +connectivity. +

    +

    +However, setting up retriever can be quite tricky since it depends on +the internal design of the website. That was designed to make life +easy for the website's developers, not for you. You'll need to have +some familiarity with HTML, and be willing to adapt when the website +suddenly changes everything without notice. +

    +

    Configuring Retriever for a feed

    +

    +To set up retriever for an RSS feed, go to the "Contacts" page and +find your feed. Then click on the drop-down menu on the contact. +Select "Retriever" to get to the retriever configuration. +

    +

    +The "Include" configuration section specifies parts of the page to +include in the article. Each row has three components: +

    +
      +
    • An HTML tag (e.g. "div", "span", "p")
    • +
    • An attribute (usually "class" or "id")
    • +
    • A value for the attribute
    • +
    +

    +A simple case is when the article is wrapped in a "div" element: +

    +
    +    ...
    +    <div class="ArticleWrapper">
    +      <h2>Man Bites Dog</h2>
    +      <img src="mbd.jpg">
    +      <p>
    +        Residents of the sleepy community of Nowheresville were
    +        shocked yesterday by the sight of creepy local weirdo Jim
    +        McOddman assaulting innocent local dog Snufflekins with his
    +        false teeth.
    +      </p>
    +      ...
    +    </div>
    +    ...
    +
    +

    +You then specify the tag "div", attribute "class", and value +"ArticleWrapper". Everything else in the page, such as navigation +panels and menus and footers and so on, will be discarded. If there +is more than one section of the page you want to include, specify each +one on a separate row. If the matching section contains some sections +you want to remove, specify those in the "Exclude" section in the same +way. +

    +

    +Once you've got a configuration that you think will work, you can try +it out on some existing articles. Type a number into the +"Retrospectively Apply" box and click "Submit". After a while +(exactly how long depends on your system's cron configuration) the new +articles should be available. +

    +

    Techniques

    +

    +You can leave the attribute and value blank to include all the +corresponding elements with the specified tag name. You can also use +a tag name of just an asterisk ("*"), which will match any element type with the +specified attribute regardless of the tag. +

    +

    +Note that the "class" attribute is a special case. Many web page +templates will put multiple different classes in the same element, +separated by spaces. If you specify an attribute of "class" it will +match an element if any of its classes matches the specified value. +For example: +

    +
    +    <div class="article breaking-news">
    +
    +

    +In this case you can specify a value of "article", or "breaking-news". +You can also specify "article breaking-news", but that won't match if +the website suddenly changes to "breaking-news article", so that's not +recommended. +

    +

    +One useful trick you can try is using the website's "print" pages. +Many news sites have print versions of all their articles. These are +usually drastically simplified compared to the live website page. +Sometimes this is a good way to get the whole article when it's +normally split across multiple pages. +

    +

    +Hopefully the URL for the print page is a predictable variant of the +normal article URL. For example, an article URL like: +

    +
    +    http://www.newssite.com/article-8636.html
    +
    +

    +...might have a print version at: +

    +
    +    http://www.newssite.com/print/article-8636.html
    +
    +

    +To change the URL used to retrieve the page, use the "URL Pattern" and +"URL Replace" fields. The pattern is a regular expression matching +part of the URL to replace. In this case, you might use a pattern of +"/article" and a replace string of "/print/article". A common pattern +is simply a dollar sign ("$"), used to add the replace string to the end of the URL. +

    +

    Background Processing

    +

    +Note that retrieving and processing the articles can take some time, +so it's done in the background. Incoming articles will be marked as +invisible while they're in the process of being downloaded. If a URL +fails, the plugin will keep trying at progressively longer intervals +for up to a month, in case the website is temporarily overloaded or +the network is down. +

    +

    Retrieving Images

    +

    +Retriever can also optionally download images and store them in the +local Friendica instance. Just check the "Download Images" box. You +can also download images in every item from your network, whether it's +an RSS feed or not. Go to the "Settings" page and +click "Plugin settings". Then check the "All +Photos" box in the "Retriever Settings" section and click "Submit". +

    +

    Configure Feeds:

    +
    +{{foreach $feeds as $feed}} +{{include file='contact_template.tpl' contact=$feed}} +{{/foreach}} +
    diff --git a/retriever/templates/rule-config.tpl b/retriever/templates/rule-config.tpl new file mode 100644 index 00000000..228d0326 --- /dev/null +++ b/retriever/templates/rule-config.tpl @@ -0,0 +1,112 @@ +
    + +

    {{$title}}

    +

    {{$help_t}}

    + + +{{include file="field_checkbox.tpl" field=$enable}} +{{include file="field_input.tpl" field=$pattern}} +{{include file="field_input.tpl" field=$replace}} +{{include file="field_checkbox.tpl" field=$images}} +{{include file="field_input.tpl" field=$retrospective}} +

    {{$include_t}}:

    +
    + + + + + +{{if $include}} + {{foreach $include as $k=>$m}} + + + + + + + {{/foreach}} +{{else}} + + + + + + +{{/if}} + +
    {{$tag_t}}{{$attribute_t}}{{$value_t}}
    + +
    +

    {{$exclude_t}}:

    +
    + + + + + +{{if $exclude}} + {{foreach $exclude as $k=>$r}} + + + + + + + {{/foreach}} +{{else}} + + + + + + +{{/if}} + +
    TagAttributeValue
    + +
    +{{include file="field_textarea.tpl" field=$customxslt}} + + +
    diff --git a/retriever/templates/settings.tpl b/retriever/templates/settings.tpl new file mode 100644 index 00000000..8bfe8db0 --- /dev/null +++ b/retriever/templates/settings.tpl @@ -0,0 +1,9 @@ +
    +

    {{$title}}

    +

    + Get Help +

    +{{include file="field_checkbox.tpl" field=$allphotos}} +{{include file="field_checkbox.tpl" field=$oembed}} + +
    diff --git a/securemail/securemail.php b/securemail/securemail.php index 68fc24ff..b20eab9c 100644 --- a/securemail/securemail.php +++ b/securemail/securemail.php @@ -7,8 +7,8 @@ */ use Friendica\App; -use Friendica\Core\PConfig; -use Friendica\Util\Emailer; + +require_once 'include/Emailer.php'; /* because the fraking openpgp-php is in composer, require libs in composer * and then don't use autoloader to load classes... */ @@ -55,18 +55,18 @@ function securemail_settings(App &$a, &$s){ return; } - $enable = intval(PConfig::get(local_user(), 'securemail', 'enable')); - $publickey = PConfig::get(local_user(), 'securemail', 'pkey'); + $enable = intval(get_pconfig(local_user(), 'securemail', 'enable')); + $publickey = get_pconfig(local_user(), 'securemail', 'pkey'); $t = get_markup_template('admin.tpl', 'addon/securemail/'); - $s .= replace_macros($t, [ + $s .= replace_macros($t, array( '$title' => t('"Secure Mail" Settings'), '$submit' => t('Save Settings'), '$test' => t('Save and send test'), //NOTE: update also in 'post' - '$enable' => ['securemail-enable', t('Enable Secure Mail'), $enable, ''], - '$publickey' => ['securemail-pkey', t('Public key'), $publickey, t('Your public PGP key, ascii armored format'), 'rows="10"'] - ]); + '$enable' => array('securemail-enable', t('Enable Secure Mail'), $enable, ''), + '$publickey' => array('securemail-pkey', t('Public key'), $publickey, t('Your public PGP key, ascii armored format'), 'rows="10"') + )); } /** @@ -86,9 +86,9 @@ function securemail_settings_post(App &$a, array &$b){ } if ($_POST['securemail-submit']) { - PConfig::set(local_user(), 'securemail', 'pkey', trim($_POST['securemail-pkey'])); + set_pconfig(local_user(), 'securemail', 'pkey', trim($_POST['securemail-pkey'])); $enable = ((x($_POST, 'securemail-enable')) ? 1 : 0); - PConfig::set(local_user(), 'securemail', 'enable', $enable); + set_pconfig(local_user(), 'securemail', 'enable', $enable); info(t('Secure Mail Settings saved.') . EOL); if ($_POST['securemail-submit'] == t('Save and send test')) { @@ -107,7 +107,7 @@ function securemail_settings_post(App &$a, array &$b){ $subject = 'Friendica - Secure Mail - Test'; $message = 'This is a test message from your Friendica Secure Mail addon.'; - $params = [ + $params = array( 'uid' => local_user(), 'fromName' => $sitename, 'fromEmail' => $sender_email, @@ -115,15 +115,15 @@ function securemail_settings_post(App &$a, array &$b){ 'messageSubject' => $subject, 'htmlVersion' => "

    {$message}

    ", 'textVersion' => $message, - ]; + ); // enable addon for test - PConfig::set(local_user(), 'securemail', 'enable', 1); + set_pconfig(local_user(), 'securemail', 'enable', 1); $res = Emailer::send($params); // revert to saved value - PConfig::set(local_user(), 'securemail', 'enable', $enable); + set_pconfig(local_user(), 'securemail', 'enable', $enable); if ($res) { info(t('Test email sent') . EOL); @@ -151,12 +151,12 @@ function securemail_emailer_send_prepare(App &$a, array &$b) { $uid = $b['uid']; - $enable_checked = PConfig::get($uid, 'securemail', 'enable'); + $enable_checked = get_pconfig($uid, 'securemail', 'enable'); if (!$enable_checked) { return; } - $public_key_ascii = PConfig::get($uid, 'securemail', 'pkey'); + $public_key_ascii = get_pconfig($uid, 'securemail', 'pkey'); preg_match('/-----BEGIN ([A-Za-z ]+)-----/', $public_key_ascii, $matches); $marker = (empty($matches[1])) ? 'MESSAGE' : $matches[1]; @@ -164,11 +164,11 @@ function securemail_emailer_send_prepare(App &$a, array &$b) { $key = OpenPGP_Message::parse($public_key); - $data = new OpenPGP_LiteralDataPacket($b['textVersion'], [ + $data = new OpenPGP_LiteralDataPacket($b['textVersion'], array( 'format' => 'u', 'filename' => 'encrypted.gpg' - ]); - $encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message([$data])); + )); + $encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message(array($data))); $armored_encrypted = wordwrap( OpenPGP::enarmor($encrypted->to_bytes(), 'PGP MESSAGE'), 64, diff --git a/showmore/showmore.php b/showmore/showmore.php index 9bddab63..a9d8334f 100644 --- a/showmore/showmore.php +++ b/showmore/showmore.php @@ -8,8 +8,6 @@ * */ -use Friendica\Core\PConfig; - function showmore_install() { register_hook('prepare_body', 'addon/showmore/showmore.php', 'showmore_prepare_body'); register_hook('plugin_settings', 'addon/showmore/showmore.php', 'showmore_addon_settings'); @@ -31,8 +29,8 @@ function showmore_addon_settings(&$a,&$s) { $a->page['htmlhead'] .= ''."\r\n"; - $enable_checked = (intval(PConfig::get(local_user(),'showmore','disable')) ? '' : ' checked="checked"'); - $chars = PConfig::get(local_user(),'showmore','chars'); + $enable_checked = (intval(get_pconfig(local_user(),'showmore','disable')) ? '' : ' checked="checked"'); + $chars = get_pconfig(local_user(),'showmore','chars'); if(!$chars) $chars = '1100'; @@ -66,10 +64,10 @@ function showmore_addon_settings_post(&$a,&$b) { return; if($_POST['showmore-submit']) { - PConfig::set(local_user(),'showmore','chars',trim($_POST['showmore-chars'])); + set_pconfig(local_user(),'showmore','chars',trim($_POST['showmore-chars'])); $enable = ((x($_POST,'showmore-enable')) ? intval($_POST['showmore-enable']) : 0); $disable = 1-$enable; - PConfig::set(local_user(),'showmore','disable', $disable); + set_pconfig(local_user(),'showmore','disable', $disable); info( t('Show More Settings saved.') . EOL); } } @@ -109,10 +107,10 @@ function get_body_length($body) { function showmore_prepare_body(&$a,&$b) { $words = null; - if(PConfig::get(local_user(),'showmore','disable')) + if(get_pconfig(local_user(),'showmore','disable')) return; - $chars = (int)PConfig::get(local_user(),'showmore','chars'); + $chars = (int)get_pconfig(local_user(),'showmore','chars'); if(!$chars) $chars = 1100; @@ -156,7 +154,7 @@ function showmore_cutitem($text, $limit) { @$doc->loadHTML($doctype."".$text.""); $text = $doc->saveHTML(); - $text = str_replace(["", "", $doctype], ["", "", ""], $text); + $text = str_replace(array("", "", $doctype), array("", "", ""), $text); return($text); } diff --git a/smileybutton/smileybutton.php b/smileybutton/smileybutton.php index d922a6b1..d8c15330 100644 --- a/smileybutton/smileybutton.php +++ b/smileybutton/smileybutton.php @@ -8,16 +8,16 @@ function smileybutton_install() { - //Register hooks + //Register hooks register_hook('jot_tool', 'addon/smileybutton/smileybutton.php', 'show_button'); - + logger("installed smileybutton"); } function smileybutton_uninstall() { //Delet registered hooks - unregister_hook('jot_tool', 'addon/smileybutton/smileybutton.php', 'show_button'); + unregister_hook('jot_tool', 'addon/smileybutton/smileybutton.php', 'show_button'); logger("removed smileybutton"); } @@ -41,34 +41,34 @@ function show_button($a, &$b) { * */ - $texts = [ - '<3', - '</3', - ':-)', - ';-)', - ':-(', - ':-P', - ':-X', - ':-D', - ':-O', - '\\\\o/', - 'O_o', - ":\'(", - ":-!", - ":-/", - ":-[", + $texts = array( + '<3', + '</3', + ':-)', + ';-)', + ':-(', + ':-P', + ':-X', + ':-D', + ':-O', + '\\\\o/', + 'O_o', + ":\'(", + ":-!", + ":-/", + ":-[", "8-)", - ':beer', - ':coffee', + ':beer', + ':coffee', ':facepalm', ':like', ':dislike', '~friendica', 'red#' - ]; + ); - $icons = [ + $icons = array( '<3', '</3', ':-)', @@ -77,7 +77,7 @@ function show_button($a, &$b) { ':-P', ':-X', ':-D', - ':-O', + ':-O', '\\o/', 'O_o', ':\'(', @@ -92,10 +92,10 @@ function show_button($a, &$b) { ':dislike', '~friendica', 'red' - ]; - + ); + // Call hooks to get aditional smileies from other addons - $params = ['texts' => $texts, 'icons' => $icons, 'string' => ""]; //changed + $params = array('texts' => $texts, 'icons' => $icons, 'string' => ""); //changed call_hooks('smilie', $params); //Generate html for smiley list @@ -113,16 +113,16 @@ function show_button($a, &$b) { //Add css to header $css_file = 'addon/smileybutton/view/'.current_theme().'.css'; - if (! file_exists($css_file)) + if (! file_exists($css_file)) $css_file = 'addon/smileybutton/view/default.css'; $css_url = $a->get_baseurl().'/'.$css_file; $a->page['htmlhead'] .= ''."\r\n"; - + //Get the correct image for the theme $image = 'addon/smileybutton/view/'.current_theme().'.png'; - if (! file_exists($image)) + if (! file_exists($image)) $image = 'addon/smileybutton/view/default.png'; $image_url = $a->get_baseurl().'/'.$image; diff --git a/snautofollow/lang/C/messages.po b/snautofollow/lang/C/messages.po new file mode 100644 index 00000000..1cfdbc5a --- /dev/null +++ b/snautofollow/lang/C/messages.po @@ -0,0 +1,34 @@ +# ADDON snautofollow +# Copyright (C) +# This file is distributed under the same license as the Friendica snautofollow addon package. +# +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2013-02-27 05:01-0500\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: snautofollow.php:32 +msgid "StatusNet AutoFollow settings updated." +msgstr "" + +#: snautofollow.php:56 +msgid "StatusNet AutoFollow Settings" +msgstr "" + +#: snautofollow.php:58 +msgid "Automatically follow any StatusNet followers/mentioners" +msgstr "" + +#: snautofollow.php:64 +msgid "Submit" +msgstr "" diff --git a/snautofollow/lang/ca/strings.php b/snautofollow/lang/ca/strings.php new file mode 100644 index 00000000..824361aa --- /dev/null +++ b/snautofollow/lang/ca/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = "Ajustos de AutoSeguiment a StatusNet actualitzats."; +$a->strings["StatusNet AutoFollow Settings"] = "Ajustos de AutoSeguiment a StatusNet"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Segueix Automaticament qualsevol seguidor/mencionador de StatusNet"; +$a->strings["Submit"] = "Enviar"; diff --git a/snautofollow/lang/cs/messages.po b/snautofollow/lang/cs/messages.po new file mode 100644 index 00000000..933478c2 --- /dev/null +++ b/snautofollow/lang/cs/messages.po @@ -0,0 +1,36 @@ +# ADDON snautofollow +# Copyright (C) +# This file is distributed under the same license as the Friendica snautofollow addon package. +# +# +# Translators: +# Michal Šupler , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2014-07-28 18:12+0000\n" +"Last-Translator: Michal Šupler \n" +"Language-Team: Czech (http://www.transifex.com/projects/p/friendica/language/cs/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: cs\n" +"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" + +#: snautofollow.php:32 +msgid "StatusNet AutoFollow settings updated." +msgstr "Nastavení automatického následování na StatusNet aktualizováno." + +#: snautofollow.php:56 snautofollow.php:60 +msgid "StatusNet AutoFollow" +msgstr "Nastavení StatusNet automatického následování (AutoFollow)" + +#: snautofollow.php:64 +msgid "Automatically follow any StatusNet followers/mentioners" +msgstr "Automaticky následovat jakékoliv StatusNet následníky/přispivatele" + +#: snautofollow.php:70 +msgid "Save Settings" +msgstr "Uložit Nastavení" diff --git a/snautofollow/lang/cs/strings.php b/snautofollow/lang/cs/strings.php new file mode 100644 index 00000000..144b8d8e --- /dev/null +++ b/snautofollow/lang/cs/strings.php @@ -0,0 +1,11 @@ +=2 && $n<=4) ? 1 : 2;; +}} +; +$a->strings["StatusNet AutoFollow settings updated."] = "Nastavení automatického následování na StatusNet aktualizováno."; +$a->strings["StatusNet AutoFollow"] = "Nastavení StatusNet automatického následování (AutoFollow)"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Automaticky následovat jakékoliv StatusNet následníky/přispivatele"; +$a->strings["Save Settings"] = "Uložit Nastavení"; diff --git a/snautofollow/lang/de/messages.po b/snautofollow/lang/de/messages.po new file mode 100644 index 00000000..fb19d4ff --- /dev/null +++ b/snautofollow/lang/de/messages.po @@ -0,0 +1,36 @@ +# ADDON snautofollow +# Copyright (C) +# This file is distributed under the same license as the Friendica snautofollow addon package. +# +# +# Translators: +# bavatar , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2014-10-02 14:39+0000\n" +"Last-Translator: bavatar \n" +"Language-Team: German (http://www.transifex.com/projects/p/friendica/language/de/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: de\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: snautofollow.php:32 +msgid "StatusNet AutoFollow settings updated." +msgstr "StatusNet AutoFollow Einstellungen aktualisiert." + +#: snautofollow.php:56 snautofollow.php:60 +msgid "StatusNet AutoFollow" +msgstr "StatusNet AutoFollow" + +#: snautofollow.php:64 +msgid "Automatically follow any StatusNet followers/mentioners" +msgstr "Automatisch allen StatusNet Followern/Erwähnungen folgen" + +#: snautofollow.php:70 +msgid "Save Settings" +msgstr "Einstellungen speichern" diff --git a/snautofollow/lang/de/strings.php b/snautofollow/lang/de/strings.php new file mode 100644 index 00000000..83e99b85 --- /dev/null +++ b/snautofollow/lang/de/strings.php @@ -0,0 +1,11 @@ +strings["StatusNet AutoFollow settings updated."] = "StatusNet AutoFollow Einstellungen aktualisiert."; +$a->strings["StatusNet AutoFollow"] = "StatusNet AutoFollow"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Automatisch allen StatusNet Followern/Erwähnungen folgen"; +$a->strings["Save Settings"] = "Einstellungen speichern"; diff --git a/snautofollow/lang/eo/strings.php b/snautofollow/lang/eo/strings.php new file mode 100644 index 00000000..8bd03fc4 --- /dev/null +++ b/snautofollow/lang/eo/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = "Ĝidatigis StatusNet AutoFollow agordojn."; +$a->strings["StatusNet AutoFollow Settings"] = "StatusNet AutoFollow agordoj"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Aŭtomate sekvu ĉiujn StatusNet sekvantojn/menciantojn."; +$a->strings["Submit"] = "Sendi"; diff --git a/snautofollow/lang/es/messages.po b/snautofollow/lang/es/messages.po new file mode 100644 index 00000000..afd88331 --- /dev/null +++ b/snautofollow/lang/es/messages.po @@ -0,0 +1,36 @@ +# ADDON snautofollow +# Copyright (C) +# This file is distributed under the same license as the Friendica snautofollow addon package. +# +# +# Translators: +# Albert, 2016 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2013-02-27 05:01-0500\n" +"PO-Revision-Date: 2016-11-17 22:37+0000\n" +"Last-Translator: Albert\n" +"Language-Team: Spanish (http://www.transifex.com/Friendica/friendica/language/es/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: es\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: snautofollow.php:32 +msgid "StatusNet AutoFollow settings updated." +msgstr "Ajustes de StatusNet AutoFollow actualizados." + +#: snautofollow.php:56 +msgid "StatusNet AutoFollow Settings" +msgstr "Ajustes de StatusNet AutoFollow" + +#: snautofollow.php:58 +msgid "Automatically follow any StatusNet followers/mentioners" +msgstr "Seguir automáticamente a cualquiera que te siga/mencione en StatusNet" + +#: snautofollow.php:64 +msgid "Submit" +msgstr "Enviar" diff --git a/snautofollow/lang/es/strings.php b/snautofollow/lang/es/strings.php new file mode 100644 index 00000000..2800360d --- /dev/null +++ b/snautofollow/lang/es/strings.php @@ -0,0 +1,11 @@ +strings["StatusNet AutoFollow settings updated."] = "Ajustes de StatusNet AutoFollow actualizados."; +$a->strings["StatusNet AutoFollow Settings"] = "Ajustes de StatusNet AutoFollow"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Seguir automáticamente a cualquiera que te siga/mencione en StatusNet"; +$a->strings["Submit"] = "Enviar"; diff --git a/snautofollow/lang/fr/strings.php b/snautofollow/lang/fr/strings.php new file mode 100644 index 00000000..f6791ffa --- /dev/null +++ b/snautofollow/lang/fr/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = "Réglages de suivi automatique sur StatusNet mis à jour."; +$a->strings["StatusNet AutoFollow Settings"] = "Réglages de suivi automatique sur StatusNet"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Suivre automatiquement les personnes qui vous suivent ou vous mentionnent sur Statusnet"; +$a->strings["Submit"] = "Envoyer"; diff --git a/snautofollow/lang/is/strings.php b/snautofollow/lang/is/strings.php new file mode 100644 index 00000000..73eda760 --- /dev/null +++ b/snautofollow/lang/is/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = ""; +$a->strings["StatusNet AutoFollow Settings"] = ""; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = ""; +$a->strings["Submit"] = "Senda inn"; diff --git a/snautofollow/lang/it/messages.po b/snautofollow/lang/it/messages.po new file mode 100644 index 00000000..b7b8d3f8 --- /dev/null +++ b/snautofollow/lang/it/messages.po @@ -0,0 +1,36 @@ +# ADDON snautofollow +# Copyright (C) +# This file is distributed under the same license as the Friendica snautofollow addon package. +# +# +# Translators: +# fabrixxm , 2014-2015 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2013-02-27 05:01-0500\n" +"PO-Revision-Date: 2015-08-31 10:23+0000\n" +"Last-Translator: fabrixxm \n" +"Language-Team: Italian (http://www.transifex.com/Friendica/friendica/language/it/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: it\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: snautofollow.php:32 +msgid "StatusNet AutoFollow settings updated." +msgstr "Impostazioni \"StatusNet AutoFollow\" aggiornate." + +#: snautofollow.php:56 +msgid "StatusNet AutoFollow Settings" +msgstr "Impostazioni StatusNet AutoFollow" + +#: snautofollow.php:58 +msgid "Automatically follow any StatusNet followers/mentioners" +msgstr "Segui automanticamente chiunque da StatusNet ti segua o ti menzioni" + +#: snautofollow.php:64 +msgid "Submit" +msgstr "Invia" diff --git a/snautofollow/lang/it/strings.php b/snautofollow/lang/it/strings.php new file mode 100644 index 00000000..b6fab060 --- /dev/null +++ b/snautofollow/lang/it/strings.php @@ -0,0 +1,11 @@ +strings["StatusNet AutoFollow settings updated."] = "Impostazioni \"StatusNet AutoFollow\" aggiornate."; +$a->strings["StatusNet AutoFollow Settings"] = "Impostazioni StatusNet AutoFollow"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Segui automanticamente chiunque da StatusNet ti segua o ti menzioni"; +$a->strings["Submit"] = "Invia"; diff --git a/snautofollow/lang/nb-no/strings.php b/snautofollow/lang/nb-no/strings.php new file mode 100644 index 00000000..6a25c730 --- /dev/null +++ b/snautofollow/lang/nb-no/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = ""; +$a->strings["StatusNet AutoFollow Settings"] = ""; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = ""; +$a->strings["Submit"] = "Lagre"; diff --git a/snautofollow/lang/pl/strings.php b/snautofollow/lang/pl/strings.php new file mode 100644 index 00000000..8ffa6d98 --- /dev/null +++ b/snautofollow/lang/pl/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = ""; +$a->strings["StatusNet AutoFollow Settings"] = ""; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = ""; +$a->strings["Submit"] = "Potwierdź"; diff --git a/snautofollow/lang/pt-br/strings.php b/snautofollow/lang/pt-br/strings.php new file mode 100644 index 00000000..c932de9a --- /dev/null +++ b/snautofollow/lang/pt-br/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = ""; +$a->strings["StatusNet AutoFollow Settings"] = ""; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = ""; +$a->strings["Submit"] = "Enviar"; diff --git a/snautofollow/lang/ro/messages.po b/snautofollow/lang/ro/messages.po new file mode 100644 index 00000000..108b6c87 --- /dev/null +++ b/snautofollow/lang/ro/messages.po @@ -0,0 +1,35 @@ +# ADDON snautofollow +# Copyright (C) +# This file is distributed under the same license as the Friendica snautofollow addon package. +# +# +# Translators: +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2014-07-08 12:07+0000\n" +"Last-Translator: Arian - Cazare Muncitori \n" +"Language-Team: Romanian (Romania) (http://www.transifex.com/projects/p/friendica/language/ro_RO/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: ro_RO\n" +"Plural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1));\n" + +#: snautofollow.php:32 +msgid "StatusNet AutoFollow settings updated." +msgstr "Configurări StatusNet AutoFollow actualizate." + +#: snautofollow.php:56 snautofollow.php:60 +msgid "StatusNet AutoFollow" +msgstr "StatusNet AutoFollow" + +#: snautofollow.php:64 +msgid "Automatically follow any StatusNet followers/mentioners" +msgstr "Urmărește automat orice susținător/pe cei ce vă menționează pe StatusNet" + +#: snautofollow.php:70 +msgid "Save Settings" +msgstr "Salvare Configurări" diff --git a/snautofollow/lang/ro/strings.php b/snautofollow/lang/ro/strings.php new file mode 100644 index 00000000..b8fb967f --- /dev/null +++ b/snautofollow/lang/ro/strings.php @@ -0,0 +1,11 @@ +19)||(($n%100==0)&&($n!=0)))?2:1));; +}} +; +$a->strings["StatusNet AutoFollow settings updated."] = "Configurări StatusNet AutoFollow actualizate."; +$a->strings["StatusNet AutoFollow"] = "StatusNet AutoFollow"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "Urmărește automat orice susținător/pe cei ce vă menționează pe StatusNet"; +$a->strings["Save Settings"] = "Salvare Configurări"; diff --git a/snautofollow/lang/ru/strings.php b/snautofollow/lang/ru/strings.php new file mode 100644 index 00000000..2f7dec45 --- /dev/null +++ b/snautofollow/lang/ru/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = ""; +$a->strings["StatusNet AutoFollow Settings"] = ""; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = ""; +$a->strings["Submit"] = "Подтвердить"; diff --git a/snautofollow/lang/sv/strings.php b/snautofollow/lang/sv/strings.php new file mode 100644 index 00000000..3ec569a7 --- /dev/null +++ b/snautofollow/lang/sv/strings.php @@ -0,0 +1,3 @@ +strings["Submit"] = "Spara"; diff --git a/snautofollow/lang/zh-cn/strings.php b/snautofollow/lang/zh-cn/strings.php new file mode 100644 index 00000000..1c704242 --- /dev/null +++ b/snautofollow/lang/zh-cn/strings.php @@ -0,0 +1,6 @@ +strings["StatusNet AutoFollow settings updated."] = "StatusNet自动关注设置更新了。"; +$a->strings["StatusNet AutoFollow Settings"] = "StatusNet自动关注设置"; +$a->strings["Automatically follow any StatusNet followers/mentioners"] = "自动关注所有的StatusGet关注者/提及"; +$a->strings["Submit"] = "提交"; diff --git a/snautofollow/snautofollow.css b/snautofollow/snautofollow.css new file mode 100644 index 00000000..243ecaa8 --- /dev/null +++ b/snautofollow/snautofollow.css @@ -0,0 +1,14 @@ + + + +#snautofollow-label { + float: left; + width: 200px; + margin-bottom: 25px; +} + +#snautofollow-checkbox { + float: left; +} + + diff --git a/snautofollow/snautofollow.php b/snautofollow/snautofollow.php new file mode 100644 index 00000000..2d953d5b --- /dev/null +++ b/snautofollow/snautofollow.php @@ -0,0 +1,71 @@ + + * Status: Unsupported + */ + + +function snautofollow_install() { + + register_hook('connector_settings', 'addon/snautofollow/snautofollow.php', 'snautofollow_settings'); + register_hook('connector_settings_post', 'addon/snautofollow/snautofollow.php', 'snautofollow_settings_post'); + +} + + +function snautofollow_uninstall() { + unregister_hook('connector_settings', 'addon/snautofollow/snautofollow.php', 'snautofollow_settings'); + unregister_hook('connector_settings_post', 'addon/snautofollow/snautofollow.php', 'snautofollow_settings_post'); + +} + + +function snautofollow_settings_post($a,$post) { + if(! local_user() || (! x($_POST,'snautofollow-submit'))) + return; + + set_pconfig(local_user(),'system','ostatus_autofriend',intval($_POST['snautofollow'])); + info( t('StatusNet AutoFollow settings updated.') . EOL); +} + +function snautofollow_settings(&$a,&$s) { + + if(! local_user()) + return; + + /* Add our stylesheet to the page so we can make our settings look nice */ + + $a->page['htmlhead'] .= '' . "\r\n"; + + /* Get the current state of our config variable */ + + $snautofollow = get_pconfig(local_user(),'system','ostatus_autofriend'); + if($snautofollow === false) + $snautofollow = false; + + $snautofollow_checked = (($snautofollow) ? ' checked="checked" ' : ''); + + + /* Add some HTML to the existing form */ + + $s .= ''; + $s .= '

    ' . t('StatusNet AutoFollow') . '

    '; + $s .= '
    '; + $s .= ''; + +} diff --git a/startpage/startpage.php b/startpage/startpage.php index b0ee04cb..e0d822ac 100644 --- a/startpage/startpage.php +++ b/startpage/startpage.php @@ -4,10 +4,9 @@ * Description: Set a preferred page to load on login from home page * Version: 1.0 * Author: Mike Macgirvin - * + * */ -use Friendica\Core\PConfig; function startpage_install() { register_hook('home_init', 'addon/startpage/startpage.php', 'startpage_home_init'); @@ -28,9 +27,12 @@ function startpage_home_init($a, $b) { if(! local_user()) return; - $page = PConfig::get(local_user(),'startpage','startpage'); + $page = get_pconfig(local_user(),'startpage','startpage'); if(strlen($page)) { - goaway($page); + $slash = ((strpos($page,'/') === 0) ? true : false); + if(stristr($page,'://')) + goaway($page); + goaway($a->get_baseurl() . (($slash) ? '' : '/') . $page); } return; } @@ -48,13 +50,13 @@ function startpage_settings_post($a,$post) { if(! local_user()) return; if($_POST['startpage-submit']) - PConfig::set(local_user(),'startpage','startpage',strip_tags(trim($_POST['startpage']))); + set_pconfig(local_user(),'startpage','startpage',strip_tags(trim($_POST['startpage']))); } /** * - * Called from the Plugin Setting form. + * Called from the Plugin Setting form. * Add our own settings info to the page. * */ @@ -72,7 +74,7 @@ function startpage_settings(&$a,&$s) { /* Get the current state of our config variable */ - $page = PConfig::get(local_user(),'startpage','startpage'); + $page = get_pconfig(local_user(),'startpage','startpage'); /* Add some HTML to the existing form */ diff --git a/statistics_json/README.md b/statistics_json/README.md new file mode 100644 index 00000000..a4d542cf --- /dev/null +++ b/statistics_json/README.md @@ -0,0 +1,14 @@ +With this addon you send some information about your friendica node to the +[the-federation.info](http://the-federation.info) page. It collects +statistical data about building blocks of *The Federation*, the decentralized +federated social networks (Diaspora*, ~friendica and red#matrix). + +The information includes + +* the name of your node +* friendica version +* registration policy +* total number of users of that node and the active user number +* total number of public postings +* which plugins are activated (only Facebook, Twitter, Tumblr and Wordpress + will be displayed on the statistics page at the moment). diff --git a/statistics_json/lang/C/messages.po b/statistics_json/lang/C/messages.po new file mode 100644 index 00000000..e69de29b diff --git a/statistics_json/statistics_json.php b/statistics_json/statistics_json.php new file mode 100644 index 00000000..2bd2f41f --- /dev/null +++ b/statistics_json/statistics_json.php @@ -0,0 +1,148 @@ + + * Status: Unsupported + */ + +function statistics_json_install() { + register_hook('cron', 'addon/statistics_json/statistics_json.php', 'statistics_json_cron'); +} + + +function statistics_json_uninstall() { + unregister_hook('cron', 'addon/statistics_json/statistics_json.php', 'statistics_json_cron'); +} + +function statistics_json_module() {} + +function statistics_json_plugin_enabled($plugin) { + $r = q("SELECT * FROM `addon` WHERE `installed` = 1 AND `name` = '%s'", $plugin); + return((bool)(count($r) > 0)); +} + +function statistics_json_init() { + global $a; + + $statistics = array( + "name" => $a->config["sitename"], + "network" => FRIENDICA_PLATFORM, + "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION, + "registrations_open" => ($a->config['register_policy'] != 0), + "total_users" => get_config('statistics_json','total_users'), + "active_users_halfyear" => get_config('statistics_json','active_users_halfyear'), + "active_users_monthly" => get_config('statistics_json','active_users_monthly'), + "local_posts" => get_config('statistics_json','local_posts') + ); + + $statistics["services"] = array(); + $statistics["services"]["appnet"] = statistics_json_plugin_enabled("appnet"); + $statistics["services"]["blogger"] = statistics_json_plugin_enabled("blogger"); + $statistics["services"]["buffer"] = statistics_json_plugin_enabled("buffer"); + $statistics["services"]["dreamwidth"] = statistics_json_plugin_enabled("dwpost"); + $statistics["services"]["facebook"] = statistics_json_plugin_enabled("fbpost"); + $statistics["services"]["gnusocial"] = statistics_json_plugin_enabled("statusnet"); + $statistics["services"]["googleplus"] = statistics_json_plugin_enabled("gpluspost"); + $statistics["services"]["libertree"] = statistics_json_plugin_enabled("libertree"); + $statistics["services"]["livejournal"] = statistics_json_plugin_enabled("ljpost"); + $statistics["services"]["pumpio"] = statistics_json_plugin_enabled("pumpio"); + $statistics["services"]["twitter"] = statistics_json_plugin_enabled("twitter"); + $statistics["services"]["tumblr"] = statistics_json_plugin_enabled("tumblr"); + $statistics["services"]["wordpress"] = statistics_json_plugin_enabled("wppost"); + + $statistics["appnet"] = $statistics["services"]["appnet"]; + $statistics["blogger"] = $statistics["services"]["blogger"]; + $statistics["buffer"] = $statistics["services"]["buffer"]; + $statistics["dreamwidth"] = $statistics["services"]["dreamwidth"]; + $statistics["facebook"] = $statistics["services"]["facebook"]; + $statistics["gnusocial"] = $statistics["services"]["gnusocial"]; + $statistics["googleplus"] = $statistics["services"]["googleplus"]; + $statistics["libertree"] = $statistics["services"]["libertree"]; + $statistics["livejournal"] = $statistics["services"]["livejournal"]; + $statistics["pumpio"] = $statistics["services"]["pumpio"]; + $statistics["twitter"] = $statistics["services"]["twitter"]; + $statistics["tumblr"] = $statistics["services"]["tumblr"]; + $statistics["wordpress"] = $statistics["services"]["wordpress"]; + + header("Content-Type: application/json"); + echo json_encode($statistics); + logger("statistics_init: printed ".print_r($statistics, true)); + killme(); +} + +function statistics_json_cron($a,$b) { + $last = get_config('statistics_json','last_calucation'); + + if($last) { + // Calculate every 24 hours + $next = $last + (24 * 60 * 60); + if($next > time()) { + logger('statistics_json_cron: calculation intervall not reached'); + return; + } + } + logger('statistics_json_cron: cron_start'); + + + $users = q("SELECT profile.*, `user`.`login_date`, `lastitem`.`lastitem_date` + FROM (SELECT MAX(`item`.`changed`) as `lastitem_date`, `item`.`uid` + FROM `item` + WHERE `item`.`type` = 'wall' + GROUP BY `item`.`uid`) AS `lastitem` + RIGHT OUTER JOIN `user` ON `user`.`uid` = `lastitem`.`uid`, `contact`, `profile` + WHERE + `user`.`uid` = `contact`.`uid` AND `profile`.`uid` = `user`.`uid` + AND `profile`.`is-default` AND (`profile`.`publish` OR `profile`.`net-publish`) + AND `user`.`verified` AND `contact`.`self` + AND NOT `user`.`blocked` + AND NOT `user`.`account_removed` + AND NOT `user`.`account_expired`"); + + if (is_array($users)) { + $total_users = count($users); + $active_users_halfyear = 0; + $active_users_monthly = 0; + + $halfyear = time() - (180 * 24 * 60 * 60); + $month = time() - (30 * 24 * 60 * 60); + + foreach ($users AS $user) { + if ((strtotime($user['login_date']) > $halfyear) || + (strtotime($user['lastitem_date']) > $halfyear)) + ++$active_users_halfyear; + + if ((strtotime($user['login_date']) > $month) || + (strtotime($user['lastitem_date']) > $month)) + ++$active_users_monthly; + + } + set_config('statistics_json','total_users', $total_users); + logger('statistics_json_cron: total_users: '.$total_users, LOGGER_DEBUG); + + set_config('statistics_json','active_users_halfyear', $active_users_halfyear); + set_config('statistics_json','active_users_monthly', $active_users_monthly); + } + + $posts = q("SELECT COUNT(*) AS local_posts FROM `item` WHERE `wall` AND `uid` != 0 AND `id` = `parent` AND left(body, 6) != '[share'"); + + if (!is_array($posts)) + $local_posts = -1; + else + $local_posts = $posts[0]["local_posts"]; + + set_config('statistics_json','local_posts', $local_posts); + + logger('statistics_json_cron: local_posts: '.$local_posts, LOGGER_DEBUG); + + // Now trying to register + $url = "http://the-federation.info/register/".$a->get_hostname(); + logger('statistics_json_cron: registering url: '.$url, LOGGER_DEBUG); + $ret = fetch_url($url); + logger('statistics_json_cron: registering answer: '.$ret, LOGGER_DEBUG); + + logger('statistics_json_cron: cron_end'); + set_config('statistics_json','last_calucation', time()); +} diff --git a/statusnet/statusnet.php b/statusnet/statusnet.php index 9158052a..a004a624 100644 --- a/statusnet/statusnet.php +++ b/statusnet/statusnet.php @@ -1,5 +1,4 @@ get($this->host . 'statusnet/config.json'); - return $config->site->textlimit; - } - - function accessTokenURL() - { - return $this->host . 'oauth/access_token'; - } - - function authenticateURL() - { - return $this->host . 'oauth/authenticate'; - } - - function authorizeURL() - { - return $this->host . 'oauth/authorize'; - } - - function requestTokenURL() - { - return $this->host . 'oauth/request_token'; - } - - function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) - { - parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret); - $this->host = $apipath; - } - - /** - * Make an HTTP request - * - * @return API results - * - * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica - */ - function http($url, $method, $postfields = NULL) - { - $this->http_info = []; - $ci = curl_init(); - /* Curl settings */ - $prx = Config::get('system', 'proxy'); - if (strlen($prx)) { - curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1); - curl_setopt($ci, CURLOPT_PROXY, $prx); - $prxusr = Config::get('system', 'proxyuser'); - if (strlen($prxusr)) { - curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr); - } - } - curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); - curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); - curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); - curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); - curl_setopt($ci, CURLOPT_HTTPHEADER, ['Expect:']); - curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); - curl_setopt($ci, CURLOPT_HEADERFUNCTION, [$this, 'getHeader']); - curl_setopt($ci, CURLOPT_HEADER, FALSE); - - switch ($method) { - case 'POST': - curl_setopt($ci, CURLOPT_POST, TRUE); - if (!empty($postfields)) { - curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); - } - break; - case 'DELETE': - curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); - if (!empty($postfields)) { - $url = "{$url}?{$postfields}"; - } - } - - curl_setopt($ci, CURLOPT_URL, $url); - $response = curl_exec($ci); - $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); - $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); - $this->url = $url; - curl_close($ci); - return $response; - } +require_once('library/twitteroauth.php'); +require_once('include/enotify.php'); +require_once("include/socgraph.php"); + +class StatusNetOAuth extends TwitterOAuth { + function get_maxlength() { + $config = $this->get($this->host . 'statusnet/config.json'); + return $config->site->textlimit; + } + function accessTokenURL() { return $this->host.'oauth/access_token'; } + function authenticateURL() { return $this->host.'oauth/authenticate'; } + function authorizeURL() { return $this->host.'oauth/authorize'; } + function requestTokenURL() { return $this->host.'oauth/request_token'; } + function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) { + parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret); + $this->host = $apipath; + } + /** + * Make an HTTP request + * + * @return API results + * + * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica + */ + function http($url, $method, $postfields = NULL) { + $this->http_info = array(); + $ci = curl_init(); + /* Curl settings */ + $prx = get_config('system','proxy'); + if(strlen($prx)) { + curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1); + curl_setopt($ci, CURLOPT_PROXY, $prx); + $prxusr = get_config('system','proxyuser'); + if(strlen($prxusr)) + curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr); + } + curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); + curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); + curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); + curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); + curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:')); + curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer); + curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); + curl_setopt($ci, CURLOPT_HEADER, FALSE); + + switch ($method) { + case 'POST': + curl_setopt($ci, CURLOPT_POST, TRUE); + if (!empty($postfields)) { + curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); + } + break; + case 'DELETE': + curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); + if (!empty($postfields)) { + $url = "{$url}?{$postfields}"; + } + } + + curl_setopt($ci, CURLOPT_URL, $url); + $response = curl_exec($ci); + $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); + $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); + $this->url = $url; + curl_close ($ci); + return $response; + } } -function statusnet_install() -{ +function statusnet_install() { // we need some hooks, for the configuration and for sending tweets register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post'); register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook'); register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local'); - register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets'); + register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets'); register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron'); register_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body'); - register_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification'); + register_hook('check_item_notification','addon/statusnet/statusnet.php', 'statusnet_check_item_notification'); logger("installed GNU Social"); } -function statusnet_uninstall() -{ + +function statusnet_uninstall() { unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post'); unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook'); unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local'); - unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets'); + unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets'); unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron'); unregister_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body'); - unregister_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification'); + unregister_hook('check_item_notification','addon/statusnet/statusnet.php', 'statusnet_check_item_notification'); // old setting - remove only unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook'); unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post'); + } -function statusnet_check_item_notification(App $a, &$notification_data) -{ - $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url'); +function statusnet_check_item_notification($a, &$notification_data) { + $notification_data["profiles"][] = get_pconfig($notification_data["uid"], 'statusnet', 'own_url'); } -function statusnet_jot_nets(App $a, &$b) -{ - if (!local_user()) { +function statusnet_jot_nets(&$a,&$b) { + if(! local_user()) return; - } - $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post'); - if (intval($statusnet_post) == 1) { - $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default'); + $statusnet_post = get_pconfig(local_user(),'statusnet','post'); + if(intval($statusnet_post) == 1) { + $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default'); $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : ''); $b .= '
    ' . t('Post to GNU Social') . '
    '; } } -function statusnet_settings_post(App $a, $post) -{ - if (!local_user()) { +function statusnet_settings_post ($a,$post) { + if(! local_user()) return; - } // don't check GNU Social settings if GNU Social submit button is not clicked - if (!x($_POST, 'statusnet-submit')) { + if (!x($_POST,'statusnet-submit')) return; - } if (isset($_POST['statusnet-disconnect'])) { - /* * * + /*** * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration */ - PConfig::delete(local_user(), 'statusnet', 'consumerkey'); - PConfig::delete(local_user(), 'statusnet', 'consumersecret'); - PConfig::delete(local_user(), 'statusnet', 'post'); - PConfig::delete(local_user(), 'statusnet', 'post_by_default'); - PConfig::delete(local_user(), 'statusnet', 'oauthtoken'); - PConfig::delete(local_user(), 'statusnet', 'oauthsecret'); - PConfig::delete(local_user(), 'statusnet', 'baseapi'); - PConfig::delete(local_user(), 'statusnet', 'lastid'); - PConfig::delete(local_user(), 'statusnet', 'mirror_posts'); - PConfig::delete(local_user(), 'statusnet', 'import'); - PConfig::delete(local_user(), 'statusnet', 'create_user'); - PConfig::delete(local_user(), 'statusnet', 'own_id'); + del_pconfig(local_user(), 'statusnet', 'consumerkey'); + del_pconfig(local_user(), 'statusnet', 'consumersecret'); + del_pconfig(local_user(), 'statusnet', 'post'); + del_pconfig(local_user(), 'statusnet', 'post_by_default'); + del_pconfig(local_user(), 'statusnet', 'oauthtoken'); + del_pconfig(local_user(), 'statusnet', 'oauthsecret'); + del_pconfig(local_user(), 'statusnet', 'baseapi'); + del_pconfig(local_user(), 'statusnet', 'lastid'); + del_pconfig(local_user(), 'statusnet', 'mirror_posts'); + del_pconfig(local_user(), 'statusnet', 'import'); + del_pconfig(local_user(), 'statusnet', 'create_user'); + del_pconfig(local_user(), 'statusnet', 'own_id'); } else { - if (isset($_POST['statusnet-preconf-apiurl'])) { - /* * * - * If the user used one of the preconfigured GNU Social server credentials - * use them. All the data are available in the global config. - * Check the API Url never the less and blame the admin if it's not working ^^ - */ - $globalsn = Config::get('statusnet', 'sites'); - foreach ($globalsn as $asn) { - if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) { - $apibase = $asn['apiurl']; - $c = fetch_url($apibase . 'statusnet/version.xml'); - if (strlen($c) > 0) { - PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']); - PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']); - PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']); - //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] ); - } else { - notice(t('Please contact your site administrator.
    The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL); - } - } - } - goaway('settings/connectors'); - } else { - if (isset($_POST['statusnet-consumersecret'])) { - // check if we can reach the API of the GNU Social server - // we'll check the API Version for that, if we don't get one we'll try to fix the path but will - // resign quickly after this one try to fix the path ;-) - $apibase = $_POST['statusnet-baseapi']; - $c = fetch_url($apibase . 'statusnet/version.xml'); + if (isset($_POST['statusnet-preconf-apiurl'])) { + /*** + * If the user used one of the preconfigured GNU Social server credentials + * use them. All the data are available in the global config. + * Check the API Url never the less and blame the admin if it's not working ^^ + */ + $globalsn = get_config('statusnet', 'sites'); + foreach ( $globalsn as $asn) { + if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) { + $apibase = $asn['apiurl']; + $c = fetch_url( $apibase . 'statusnet/version.xml' ); if (strlen($c) > 0) { - // ok the API path is correct, let's save the settings - PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']); - PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']); - PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase); - //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] ); + set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] ); + set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] ); + set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] ); + //set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] ); } else { - // the API path is not correct, maybe missing trailing / ? - $apibase = $apibase . '/'; - $c = fetch_url($apibase . 'statusnet/version.xml'); - if (strlen($c) > 0) { - // ok the API path is now correct, let's save the settings - PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']); - PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']); - PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase); - } else { - // still not the correct API base, let's do noting - notice(t('We could not contact the GNU Social API with the Path you entered.') . EOL); - } + notice( t('Please contact your site administrator.
    The provided API URL is not valid.').EOL.$asn['apiurl'].EOL ); } - goaway('settings/connectors'); + } + } + goaway($a->get_baseurl().'/settings/connectors'); + } else { + if (isset($_POST['statusnet-consumersecret'])) { + // check if we can reach the API of the GNU Social server + // we'll check the API Version for that, if we don't get one we'll try to fix the path but will + // resign quickly after this one try to fix the path ;-) + $apibase = $_POST['statusnet-baseapi']; + $c = fetch_url( $apibase . 'statusnet/version.xml' ); + if (strlen($c) > 0) { + // ok the API path is correct, let's save the settings + set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']); + set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']); + set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase ); + //set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] ); + } else { + // the API path is not correct, maybe missing trailing / ? + $apibase = $apibase . '/'; + $c = fetch_url( $apibase . 'statusnet/version.xml' ); + if (strlen($c) > 0) { + // ok the API path is now correct, let's save the settings + set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']); + set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']); + set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase ); } else { - if (isset($_POST['statusnet-pin'])) { - // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen - $api = PConfig::get(local_user(), 'statusnet', 'baseapi'); - $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey'); - $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret'); - // the token and secret for which the PIN was generated were hidden in the settings - // form as token and token2, we need a new connection to GNU Social using these token - // and secret to request a Access Token with the PIN - $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']); - $token = $connection->getAccessToken($_POST['statusnet-pin']); - // ok, now that we have the Access Token, save them in the user config - PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']); - PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']); - PConfig::set(local_user(), 'statusnet', 'post', 1); - PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1); - // reload the Addon Settings page, if we don't do it see Bug #42 - goaway('settings/connectors'); - } else { - // if no PIN is supplied in the POST variables, the user has changed the setting - // to post a dent for every new __public__ posting to the wall - PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable'])); - PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default'])); - PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror'])); - PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import'])); - PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user'])); - - if (!intval($_POST['statusnet-mirror'])) - PConfig::delete(local_user(), 'statusnet', 'lastid'); - - info(t('GNU Social settings updated.') . EOL); - } + // still not the correct API base, let's do noting + notice( t('We could not contact the GNU Social API with the Path you entered.').EOL ); } } - } + goaway($a->get_baseurl().'/settings/connectors'); + } else { + if (isset($_POST['statusnet-pin'])) { + // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen + $api = get_pconfig(local_user(), 'statusnet', 'baseapi'); + $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' ); + $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' ); + // the token and secret for which the PIN was generated were hidden in the settings + // form as token and token2, we need a new connection to GNU Social using these token + // and secret to request a Access Token with the PIN + $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']); + $token = $connection->getAccessToken( $_POST['statusnet-pin'] ); + // ok, now that we have the Access Token, save them in the user config + set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']); + set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']); + set_pconfig(local_user(),'statusnet', 'post', 1); + set_pconfig(local_user(),'statusnet', 'post_taglinks', 1); + // reload the Addon Settings page, if we don't do it see Bug #42 + goaway($a->get_baseurl().'/settings/connectors'); + } else { + // if no PIN is supplied in the POST variables, the user has changed the setting + // to post a dent for every new __public__ posting to the wall + set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable'])); + set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default'])); + set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror'])); + set_pconfig(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import'])); + set_pconfig(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user'])); + + if (!intval($_POST['statusnet-mirror'])) + del_pconfig(local_user(),'statusnet','lastid'); + + info( t('GNU Social settings updated.') . EOL); + }}}} } - -function statusnet_settings(App $a, &$s) -{ - if (!local_user()) { +function statusnet_settings(&$a,&$s) { + if(! local_user()) return; - } $a->page['htmlhead'] .= '' . "\r\n"; - /* * * + /*** * 1) Check that we have a base api url and a consumer key & secret * 2) If no OAuthtoken & stuff is present, generate button to get some * allow the user to cancel the connection process at this step * 3) Checkbox for "Send public notices (respect size limitation) */ - $api = PConfig::get(local_user(), 'statusnet', 'baseapi'); - $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey'); - $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret'); - $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken'); - $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret'); - $enabled = PConfig::get(local_user(), 'statusnet', 'post'); + $api = get_pconfig(local_user(), 'statusnet', 'baseapi'); + $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey'); + $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret'); + $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken'); + $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret'); + $enabled = get_pconfig(local_user(), 'statusnet', 'post'); $checked = (($enabled) ? ' checked="checked" ' : ''); - $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default'); + $defenabled = get_pconfig(local_user(),'statusnet','post_by_default'); $defchecked = (($defenabled) ? ' checked="checked" ' : ''); - $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts'); + $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts'); $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : ''); - $import = PConfig::get(local_user(), 'statusnet', 'import'); - $importselected = ["", "", ""]; + $import = get_pconfig(local_user(),'statusnet','import'); + $importselected = array("", "", ""); $importselected[$import] = ' selected="selected"'; - //$importenabled = PConfig::get(local_user(),'statusnet','import'); + //$importenabled = get_pconfig(local_user(),'statusnet','import'); //$importchecked = (($importenabled) ? ' checked="checked" ' : ''); - $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user'); + $create_userenabled = get_pconfig(local_user(),'statusnet','create_user'); $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); $s .= ''; - $s .= '

    ' . t('GNU Social Import/Export/Mirror') . '

    '; + $s .= '

    '. t('GNU Social Import/Export/Mirror').'

    '; $s .= '
    '; $s .= '
    '; } -function statusnet_post_local(App $a, &$b) -{ + +function statusnet_post_local(&$a, &$b) { if ($b['edit']) { return; } @@ -479,11 +437,11 @@ function statusnet_post_local(App $a, &$b) return; } - $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post'); - $statusnet_enable = (($statusnet_post && x($_REQUEST, 'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0); + $statusnet_post = get_pconfig(local_user(),'statusnet','post'); + $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0); // if API is used, default to the chosen settings - if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) { + if ($b['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default'))) { $statusnet_enable = 1; } @@ -498,61 +456,64 @@ function statusnet_post_local(App $a, &$b) $b['postopts'] .= 'statusnet'; } -function statusnet_action(App $a, $uid, $pid, $action) -{ - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); +function statusnet_action($a, $uid, $pid, $action) { + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); - $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret); - logger("statusnet_action '" . $action . "' ID: " . $pid, LOGGER_DATA); + logger("statusnet_action '".$action."' ID: ".$pid, LOGGER_DATA); switch ($action) { case "delete": - $result = $connection->post("statuses/destroy/" . $pid); + $result = $connection->post("statuses/destroy/".$pid); break; case "like": - $result = $connection->post("favorites/create/" . $pid); + $result = $connection->post("favorites/create/".$pid); break; case "unlike": - $result = $connection->post("favorites/destroy/" . $pid); + $result = $connection->post("favorites/destroy/".$pid); break; } - logger("statusnet_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG); + logger("statusnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG); } -function statusnet_post_hook(App $a, &$b) -{ +function statusnet_post_hook(&$a,&$b) { + /** * Post to GNU Social */ - if (!PConfig::get($b["uid"], 'statusnet', 'import')) { - if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) + + if (!get_pconfig($b["uid"],'statusnet','import')) { + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) return; } - $api = PConfig::get($b["uid"], 'statusnet', 'baseapi'); + $api = get_pconfig($b["uid"], 'statusnet', 'baseapi'); $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api); - if ($b['parent'] != $b['id']) { - logger("statusnet_post_hook: parameter " . print_r($b, true), LOGGER_DATA); + if($b['parent'] != $b['id']) { + logger("statusnet_post_hook: parameter ".print_r($b, true), LOGGER_DATA); // Looking if its a reply to a GNU Social post $hostlength = strlen($hostname) + 2; - if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) { - logger("statusnet_post_hook: no GNU Social post " . $b["parent"]); + if ((substr($b["parent-uri"], 0, $hostlength) != $hostname."::") && (substr($b["extid"], 0, $hostlength) != $hostname."::") + && (substr($b["thr-parent"], 0, $hostlength) != $hostname."::")) { + logger("statusnet_post_hook: no GNU Social post ".$b["parent"]); return; } $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` - WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1", dbesc($b["thr-parent"]), intval($b["uid"])); + WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1", + dbesc($b["thr-parent"]), + intval($b["uid"])); - if (!count($r)) { - logger("statusnet_post_hook: no parent found " . $b["thr-parent"]); + if(!count($r)) { + logger("statusnet_post_hook: no parent found ".$b["thr-parent"]); return; } else { $iscomment = true; @@ -564,36 +525,26 @@ function statusnet_post_hook(App $a, &$b) $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]); - $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]"; - $nicknameplain = "@" . $nick; + $nickname = "@[url=".$orig_post["author-link"]."]".$nick."[/url]"; + $nicknameplain = "@".$nick; - logger("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG); - if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) { - $b["body"] = $nickname . " " . $b["body"]; - } + logger("statusnet_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG); + if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) + $b["body"] = $nickname." ".$b["body"]; - logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG); + logger("statusnet_post_hook: parent found ".print_r($orig_post, true), LOGGER_DEBUG); } else { $iscomment = false; - if ($b['private'] || !strstr($b['postopts'], 'statusnet')) { + if($b['private'] || !strstr($b['postopts'],'statusnet')) return; - } - - // Dont't post if the post doesn't belong to us. - // This is a check for forum postings - $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]); - if ($b['contact-id'] != $self['id']) { - return; - } } - if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) { + if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete"); - } - if ($b['verb'] == ACTIVITY_LIKE) { - logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG); + if($b['verb'] == ACTIVITY_LIKE) { + logger("statusnet_post_hook: parameter 2 ".substr($b["thr-parent"], $hostlength), LOGGER_DEBUG); if ($b['deleted']) statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike"); else @@ -601,45 +552,42 @@ function statusnet_post_hook(App $a, &$b) return; } - if ($b['deleted'] || ($b['created'] !== $b['edited'])) { + if($b['deleted'] || ($b['created'] !== $b['edited'])) return; - } // if posts comes from GNU Social don't send it back - if ($b['extid'] == NETWORK_STATUSNET) { + if($b['extid'] == NETWORK_STATUSNET) return; - } - if ($b['app'] == "StatusNet") { + if($b['app'] == "StatusNet") return; - } logger('GNU Socialpost invoked'); - PConfig::load($b['uid'], 'statusnet'); + load_pconfig($b['uid'], 'statusnet'); + + $api = get_pconfig($b['uid'], 'statusnet', 'baseapi'); + $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey'); + $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret'); + $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret'); - $api = PConfig::get($b['uid'], 'statusnet', 'baseapi'); - $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey'); - $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret'); - $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret'); + if($ckey && $csecret && $otoken && $osecret) { - if ($ckey && $csecret && $otoken && $osecret) { // If it's a repeated message from GNU Social then do a native retweet and exit - if (statusnet_is_retweet($a, $b['uid'], $b['body'])) { + if (statusnet_is_retweet($a, $b['uid'], $b['body'])) return; - } - require_once 'include/bbcode.php'; - $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + require_once('include/bbcode.php'); + $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret); $max_char = $dent->get_maxlength(); // max. length for a dent - PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char); + set_pconfig($b['uid'], 'statusnet', 'max_char', $max_char); $tempfile = ""; - require_once "include/plaintext.php"; - require_once "include/network.php"; - $msgarr = plaintext($b, $max_char, true, 7); + require_once("include/plaintext.php"); + require_once("include/network.php"); + $msgarr = plaintext($a, $b, $max_char, true, 7); $msg = $msgarr["text"]; if (($msg == "") && isset($msgarr["title"])) @@ -649,143 +597,136 @@ function statusnet_post_hook(App $a, &$b) if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) { if ((strlen($msgarr["url"]) > 20) && - ((strlen($msg . " \n" . $msgarr["url"]) > $max_char))) { - $msg .= " \n" . short_link($msgarr["url"]); - } else { - $msg .= " \n" . $msgarr["url"]; - } - } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) { + ((strlen($msg." \n".$msgarr["url"]) > $max_char))) + $msg .= " \n".short_link($msgarr["url"]); + else + $msg .= " \n".$msgarr["url"]; + } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) $image = $msgarr["image"]; - } if ($image != "") { $img_str = fetch_url($image); $tempfile = tempnam(get_temppath(), "cache"); file_put_contents($tempfile, $img_str); - $postdata = ["status" => $msg, "media[]" => $tempfile]; - } else { - $postdata = ["status" => $msg]; - } + $postdata = array("status" => $msg, "media[]" => $tempfile); + } else + $postdata = array("status"=>$msg); // and now dent it :-) - if (strlen($msg)) { + if(strlen($msg)) { + if ($iscomment) { $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength); - logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG); + logger('statusnet_post send reply '.print_r($postdata, true), LOGGER_DEBUG); } // New code that is able to post pictures - require_once "addon/statusnet/codebird.php"; + require_once("addon/statusnet/codebird.php"); $cb = \CodebirdSN\CodebirdSN::getInstance(); $cb->setAPIEndpoint($api); $cb->setConsumerKey($ckey, $csecret); $cb->setToken($otoken, $osecret); $result = $cb->statuses_update($postdata); //$result = $dent->post('statuses/update', $postdata); - logger('statusnet_post send, result: ' . print_r($result, true) . - "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true)); + logger('statusnet_post send, result: ' . print_r($result, true). + "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true)); - if ($result->source) { - PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source)); - } + if ($result->source) + set_pconfig($b["uid"], "statusnet", "application_name", strip_tags($result->source)); if ($result->error) { - logger('Send to GNU Social failed: "' . $result->error . '"'); + logger('Send to GNU Social failed: "'.$result->error.'"'); } elseif ($iscomment) { - logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']); + logger('statusnet_post: Update extid '.$result->id." for post id ".$b['id']); q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d", - dbesc($hostname . "::" . $result->id), + dbesc($hostname."::".$result->id), dbesc($result->text), intval($b['id']) ); } } - if ($tempfile != "") { + if ($tempfile != "") unlink($tempfile); - } } } -function statusnet_plugin_admin_post(App $a) -{ - $sites = []; +function statusnet_plugin_admin_post(&$a){ - foreach ($_POST['sitename'] as $id => $sitename) { - $sitename = trim($sitename); - $apiurl = trim($_POST['apiurl'][$id]); - if (!(substr($apiurl, -1) == '/')) { - $apiurl = $apiurl . '/'; - } - $secret = trim($_POST['secret'][$id]); - $key = trim($_POST['key'][$id]); + $sites = array(); + + foreach($_POST['sitename'] as $id=>$sitename){ + $sitename=trim($sitename); + $apiurl=trim($_POST['apiurl'][$id]); + if (! (substr($apiurl, -1)=='/')) + $apiurl=$apiurl.'/'; + $secret=trim($_POST['secret'][$id]); + $key=trim($_POST['key'][$id]); //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):''); - if ($sitename != "" && - $apiurl != "" && - $secret != "" && - $key != "" && - !x($_POST['delete'][$id])) { - - $sites[] = [ - 'sitename' => $sitename, - 'apiurl' => $apiurl, - 'consumersecret' => $secret, - 'consumerkey' => $key, - //'applicationname' => $applicationname - ]; + if ($sitename!="" && + $apiurl!="" && + $secret!="" && + $key!="" && + !x($_POST['delete'][$id])){ + + $sites[] = Array( + 'sitename' => $sitename, + 'apiurl' => $apiurl, + 'consumersecret' => $secret, + 'consumerkey' => $key, + //'applicationname' => $applicationname + ); } } - $sites = Config::set('statusnet', 'sites', $sites); + $sites = set_config('statusnet','sites', $sites); + } -function statusnet_plugin_admin(App $a, &$o) -{ - $sites = Config::get('statusnet', 'sites'); - $sitesform = []; - if (is_array($sites)) { - foreach ($sites as $id => $s) { - $sitesform[] = [ - 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""], - 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")], - 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""], - 'key' => ["key[$id]", "Key", $s['consumerkey'], ""], +function statusnet_plugin_admin(&$a, &$o){ + + $sites = get_config('statusnet','sites'); + $sitesform=array(); + if (is_array($sites)){ + foreach($sites as $id=>$s){ + $sitesform[] = Array( + 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""), + 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ), + 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""), + 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""), //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""), - 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"], - ]; + 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"), + ); } } /* empty form to add new site */ $id++; - $sitesform[] = [ - 'sitename' => ["sitename[$id]", t("Site name"), "", ""], - 'apiurl' => ["apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")], - 'secret' => ["secret[$id]", t("Consumer Secret"), "", ""], - 'key' => ["key[$id]", t("Consumer Key"), "", ""], + $sitesform[] = Array( + 'sitename' => Array("sitename[$id]", t("Site name"), "", ""), + 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ), + 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""), + 'key' => Array("key[$id]", t("Consumer Key"), "", ""), //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""), - ]; + ); - $t = get_markup_template("admin.tpl", "addon/statusnet/"); - $o = replace_macros($t, [ + $t = get_markup_template( "admin.tpl", "addon/statusnet/" ); + $o = replace_macros($t, array( '$submit' => t('Save Settings'), '$sites' => $sitesform, - ]); + )); } -function statusnet_prepare_body(App $a, &$b) -{ - if ($b["item"]["network"] != NETWORK_STATUSNET) { - return; - } +function statusnet_prepare_body(&$a,&$b) { + if ($b["item"]["network"] != NETWORK_STATUSNET) + return; - if ($b["preview"]) { - $max_char = PConfig::get(local_user(), 'statusnet', 'max_char'); - if (intval($max_char) == 0) { + if ($b["preview"]) { + $max_char = get_pconfig(local_user(),'statusnet','max_char'); + if (intval($max_char) == 0) $max_char = 140; - } - require_once "include/plaintext.php"; - $item = $b["item"]; - $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"]; + require_once("include/plaintext.php"); + $item = $b["item"]; + $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"]; $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id` @@ -793,48 +734,44 @@ function statusnet_prepare_body(App $a, &$b) dbesc($item["thr-parent"]), intval(local_user())); - if (count($r)) { - $orig_post = $r[0]; + if(count($r)) { + $orig_post = $r[0]; //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]"; //$nicknameplain = "@".$orig_post["contact_nick"]; $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]); - $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]"; - $nicknameplain = "@" . $nick; + $nickname = "@[url=".$orig_post["author-link"]."]".$nick."[/url]"; + $nicknameplain = "@".$nick; - if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) { - $item["body"] = $nickname . " " . $item["body"]; - } - } + if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) + $item["body"] = $nickname." ".$item["body"]; + } - $msgarr = plaintext($item, $max_char, true, 7); - $msg = $msgarr["text"]; - if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) { - $msg .= " " . $msgarr["url"]; - } + $msgarr = plaintext($a, $item, $max_char, true, 7); + $msg = $msgarr["text"]; - if (isset($msgarr["image"])) { - $msg .= " " . $msgarr["image"]; - } + if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) + $msg .= " ".$msgarr["url"]; - $b['html'] = nl2br(htmlspecialchars($msg)); - } + if (isset($msgarr["image"])) + $msg .= " ".$msgarr["image"]; + + $b['html'] = nl2br(htmlspecialchars($msg)); + } } -function statusnet_cron(App $a, $b) -{ - $last = Config::get('statusnet', 'last_poll'); +function statusnet_cron($a,$b) { + $last = get_config('statusnet','last_poll'); - $poll_interval = intval(Config::get('statusnet', 'poll_interval')); - if (!$poll_interval) { + $poll_interval = intval(get_config('statusnet','poll_interval')); + if(! $poll_interval) $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL; - } - if ($last) { + if($last) { $next = $last + ($poll_interval * 60); - if ($next > time()) { + if($next > time()) { logger('statusnet: poll intervall not reached'); return; } @@ -842,188 +779,171 @@ function statusnet_cron(App $a, $b) logger('statusnet: cron_start'); $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() "); - if (count($r)) { - foreach ($r as $rr) { - logger('statusnet: fetching for user ' . $rr['uid']); + if(count($r)) { + foreach($r as $rr) { + logger('statusnet: fetching for user '.$rr['uid']); statusnet_fetchtimeline($a, $rr['uid']); } } - $abandon_days = intval(Config::get('system', 'account_abandon_days')); - if ($abandon_days < 1) { + $abandon_days = intval(get_config('system','account_abandon_days')); + if ($abandon_days < 1) $abandon_days = 0; - } $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400); $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()"); - if (count($r)) { - foreach ($r as $rr) { + if(count($r)) { + foreach($r as $rr) { if ($abandon_days != 0) { $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit); if (!count($user)) { - logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported'); + logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported'); continue; } } - logger('statusnet: importing timeline from user ' . $rr['uid']); + logger('statusnet: importing timeline from user '.$rr['uid']); statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]); } } logger('statusnet: cron_end'); - Config::set('statusnet', 'last_poll', time()); + set_config('statusnet','last_poll', time()); } -function statusnet_fetchtimeline(App $a, $uid) -{ - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); - $lastid = PConfig::get($uid, 'statusnet', 'lastid'); +function statusnet_fetchtimeline($a, $uid) { + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); + $lastid = get_pconfig($uid, 'statusnet', 'lastid'); - require_once 'mod/item.php'; - require_once 'include/items.php'; + require_once('mod/item.php'); + require_once('include/items.php'); // get the application name for the SN app // 1st try personal config, then system config and fallback to the // hostname of the node if neither one is set. - $application_name = PConfig::get($uid, 'statusnet', 'application_name'); - if ($application_name == "") { - $application_name = Config::get('statusnet', 'application_name'); - } - if ($application_name == "") { + $application_name = get_pconfig( $uid, 'statusnet', 'application_name'); + if ($application_name == "") + $application_name = get_config('statusnet', 'application_name'); + if ($application_name == "") $application_name = $a->get_hostname(); - } - $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret); - $parameters = ["exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false]; + $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false); $first_time = ($lastid == ""); - if ($lastid <> "") { + if ($lastid <> "") $parameters["since_id"] = $lastid; - } $items = $connection->get('statuses/user_timeline', $parameters); - if (!is_array($items)) { + if (!is_array($items)) return; - } $posts = array_reverse($items); if (count($posts)) { - foreach ($posts as $post) { - if ($post->id > $lastid) - $lastid = $post->id; + foreach ($posts as $post) { + if ($post->id > $lastid) + $lastid = $post->id; - if ($first_time) { - continue; - } + if ($first_time) + continue; - if ($post->source == "activity") { - continue; - } + if ($post->source == "activity") + continue; - if (is_object($post->retweeted_status)) { - continue; - } + if (is_object($post->retweeted_status)) + continue; - if ($post->in_reply_to_status_id != "") { - continue; - } + if ($post->in_reply_to_status_id != "") + continue; - if (!stristr($post->source, $application_name)) { - $_SESSION["authenticated"] = true; - $_SESSION["uid"] = $uid; + if (!stristr($post->source, $application_name)) { + $_SESSION["authenticated"] = true; + $_SESSION["uid"] = $uid; - unset($_REQUEST); - $_REQUEST["type"] = "wall"; - $_REQUEST["api_source"] = true; - $_REQUEST["profile_uid"] = $uid; - //$_REQUEST["source"] = "StatusNet"; - $_REQUEST["source"] = $post->source; - $_REQUEST["extid"] = NETWORK_STATUSNET; + unset($_REQUEST); + $_REQUEST["type"] = "wall"; + $_REQUEST["api_source"] = true; + $_REQUEST["profile_uid"] = $uid; + //$_REQUEST["source"] = "StatusNet"; + $_REQUEST["source"] = $post->source; + $_REQUEST["extid"] = NETWORK_STATUSNET; - if (isset($post->id)) { - $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET . ":" . $post->id); - } + if (isset($post->id)) { + $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET.":".$post->id); + } - //$_REQUEST["date"] = $post->created_at; + //$_REQUEST["date"] = $post->created_at; - $_REQUEST["title"] = ""; + $_REQUEST["title"] = ""; - $_REQUEST["body"] = add_page_info_to_body($post->text, true); - if (is_string($post->place->name)) { - $_REQUEST["location"] = $post->place->name; - } + $_REQUEST["body"] = add_page_info_to_body($post->text, true); + if (is_string($post->place->name)) + $_REQUEST["location"] = $post->place->name; - if (is_string($post->place->full_name)) { - $_REQUEST["location"] = $post->place->full_name; - } + if (is_string($post->place->full_name)) + $_REQUEST["location"] = $post->place->full_name; - if (is_array($post->geo->coordinates)) { - $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1]; - } + if (is_array($post->geo->coordinates)) + $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1]; - if (is_array($post->coordinates->coordinates)) { - $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0]; - } + if (is_array($post->coordinates->coordinates)) + $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0]; - //print_r($_REQUEST); - if ($_REQUEST["body"] != "") { - logger('statusnet: posting for user ' . $uid); + //print_r($_REQUEST); + if ($_REQUEST["body"] != "") { + logger('statusnet: posting for user '.$uid); - item_post($a); - } + item_post($a); } } + } } - PConfig::set($uid, 'statusnet', 'lastid', $lastid); + set_pconfig($uid, 'statusnet', 'lastid', $lastid); } -function statusnet_address($contact) -{ +function statusnet_address($contact) { $hostname = normalise_link($contact->statusnet_profile_url); $nickname = $contact->screen_name; $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url); - $address = $contact->screen_name . "@" . $hostname; + $address = $contact->screen_name."@".$hostname; - return $address; + return($address); } -function statusnet_fetch_contact($uid, $contact, $create_user) -{ - if ($contact->statusnet_profile_url == "") { - return -1; - } +function statusnet_fetch_contact($uid, $contact, $create_user) { + if ($contact->statusnet_profile_url == "") + return(-1); - GContact::update(["url" => $contact->statusnet_profile_url, - "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url, - "name" => $contact->name, "nick" => $contact->screen_name, - "location" => $contact->location, "about" => $contact->description, - "addr" => statusnet_address($contact), "generation" => 3]); + update_gcontact(array("url" => $contact->statusnet_profile_url, + "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url, + "name" => $contact->name, "nick" => $contact->screen_name, + "location" => $contact->location, "about" => $contact->description, + "addr" => statusnet_address($contact), "generation" => 3)); - $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET)); + $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", + intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET)); - if (!count($r) && !$create_user) { - return 0; - } + if(!count($r) && !$create_user) + return(0); if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) { - logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG); - return -1; + logger("statusnet_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG); + return(-1); } - if (!count($r)) { + if(!count($r)) { // create contact record q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`, `name`, `nick`, `photo`, `network`, `rel`, `priority`, @@ -1053,15 +973,23 @@ function statusnet_fetch_contact($uid, $contact, $create_user) intval($uid), dbesc(NETWORK_STATUSNET)); - if (!count($r)) { - return false; - } + if(! count($r)) + return(false); - $contact_id = $r[0]['id']; + $contact_id = $r[0]['id']; - Group::addMember(User::getDefaultGroup($uid), $contact_id); + $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1", + intval($uid) + ); + + if($g && intval($g[0]['def_gid'])) { + require_once('include/group.php'); + group_add_member($uid,'',$contact_id,$g[0]['def_gid']); + } - $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id); + require_once("Photo.php"); + + $photos = import_profile_photo($contact->profile_image_url,$uid,$contact_id); q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', @@ -1076,14 +1004,19 @@ function statusnet_fetch_contact($uid, $contact, $create_user) ); } else { // update profile photos once every two weeks as we have no notification of when they change. + //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false); - $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours')); + $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours')); // check that we have all the photos, this has been known to fail on occasion - if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) { - logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG); - $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']); + if((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) { + + logger("statusnet_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG); + + require_once("Photo.php"); + + $photos = import_profile_photo($contact->profile_image_url, $uid, $r[0]['id']); q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', @@ -1117,18 +1050,17 @@ function statusnet_fetch_contact($uid, $contact, $create_user) } } - return $r[0]["id"]; + return($r[0]["id"]); } -function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") -{ - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); +function statusnet_fetchuser($a, $uid, $screen_name = "", $user_id = "") { + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); - require_once "addon/statusnet/codebird.php"; + require_once("addon/statusnet/codebird.php"); $cb = \Codebird\Codebird::getInstance(); $cb->setConsumerKey($ckey, $csecret); @@ -1137,44 +1069,40 @@ function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); - if (count($r)) { + if(count($r)) { $self = $r[0]; - } else { + } else return; - } - $parameters = []; + $parameters = array(); - if ($screen_name != "") { + if ($screen_name != "") $parameters["screen_name"] = $screen_name; - } - if ($user_id != "") { + if ($user_id != "") $parameters["user_id"] = $user_id; - } // Fetching user data $user = $cb->users_show($parameters); - if (!is_object($user)) { + if (!is_object($user)) return; - } $contact_id = statusnet_fetch_contact($uid, $user, true); return $contact_id; } -function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact) -{ - require_once "include/html2bbcode.php"; +function statusnet_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) { + + require_once("include/html2bbcode.php"); logger("statusnet_createpost: start", LOGGER_DEBUG); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api); - $postarray = []; + $postarray = array(); $postarray['network'] = NETWORK_STATUSNET; $postarray['gravity'] = 0; $postarray['uid'] = $uid; @@ -1183,31 +1111,29 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex if (is_object($post->retweeted_status)) { $content = $post->retweeted_status; statusnet_fetch_contact($uid, $content->user, false); - } else { + } else $content = $post; - } - $postarray['uri'] = $hostname . "::" . $content->id; + $postarray['uri'] = $hostname."::".$content->id; $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", dbesc($postarray['uri']), intval($uid) - ); + ); - if (count($r)) { - return []; - } + if (count($r)) + return(array()); $contactid = 0; if ($content->in_reply_to_status_id != "") { - $parent = $hostname . "::" . $content->in_reply_to_status_id; + $parent = $hostname."::".$content->in_reply_to_status_id; $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent), intval($uid) - ); + ); if (count($r)) { $postarray['thr-parent'] = $r[0]["uri"]; $postarray['parent-uri'] = $r[0]["parent-uri"]; @@ -1217,7 +1143,7 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent), intval($uid) - ); + ); if (count($r)) { $postarray['thr-parent'] = $r[0]['uri']; $postarray['parent-uri'] = $r[0]['parent-uri']; @@ -1231,21 +1157,20 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex } // Is it me? - $own_url = PConfig::get($uid, 'statusnet', 'own_url'); + $own_url = get_pconfig($uid, 'statusnet', 'own_url'); if ($content->user->id == $own_url) { $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); - if (count($r)) { + if(count($r)) { $contactid = $r[0]["id"]; - $postarray['owner-name'] = $r[0]["name"]; + $postarray['owner-name'] = $r[0]["name"]; $postarray['owner-link'] = $r[0]["url"]; - $postarray['owner-avatar'] = $r[0]["photo"]; - } else { - return []; - } + $postarray['owner-avatar'] = $r[0]["photo"]; + } else + return(array()); } // Don't create accounts of people who just comment something $create_user = false; @@ -1260,11 +1185,10 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex $postarray['owner-link'] = $post->user->statusnet_profile_url; $postarray['owner-avatar'] = $post->user->profile_image_url; } - if (($contactid == 0) && !$only_existing_contact) { + if(($contactid == 0) && !$only_existing_contact) $contactid = $self['id']; - } elseif ($contactid <= 0) { - return []; - } + elseif ($contactid <= 0) + return(array()); $postarray['contact-id'] = $contactid; @@ -1275,9 +1199,9 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex $postarray['author-avatar'] = $content->user->profile_image_url; // To-Do: Maybe unreliable? Can the api be entered without trailing "/"? - $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi')); + $hostname = str_replace("/api/", "/notice/", get_pconfig($uid, 'statusnet', 'baseapi')); - $postarray['plink'] = $hostname . $content->id; + $postarray['plink'] = $hostname.$content->id; $postarray['app'] = strip_tags($content->source); if ($content->user->protected) { @@ -1291,92 +1215,99 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex $postarray['body'] = $converted["body"]; $postarray['tag'] = $converted["tags"]; - $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at); - $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at); + $postarray['created'] = datetime_convert('UTC','UTC',$content->created_at); + $postarray['edited'] = datetime_convert('UTC','UTC',$content->created_at); - if (is_string($content->place->name)) { + if (is_string($content->place->name)) $postarray["location"] = $content->place->name; - } - if (is_string($content->place->full_name)) { + if (is_string($content->place->full_name)) $postarray["location"] = $content->place->full_name; - } - if (is_array($content->geo->coordinates)) { - $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1]; - } + if (is_array($content->geo->coordinates)) + $postarray["coord"] = $content->geo->coordinates[0]." ".$content->geo->coordinates[1]; - if (is_array($content->coordinates->coordinates)) { - $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0]; - } + if (is_array($content->coordinates->coordinates)) + $postarray["coord"] = $content->coordinates->coordinates[1]." ".$content->coordinates->coordinates[0]; - logger("statusnet_createpost: end", LOGGER_DEBUG); + /*if (is_object($post->retweeted_status)) { + $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html); + + $converted = statusnet_convertmsg($a, $postarray['body'], false); + $postarray['body'] = $converted["body"]; + $postarray['tag'] = $converted["tags"]; - return $postarray; + statusnet_fetch_contact($uid, $post->retweeted_status->user, false); + + // Let retweets look like wall-to-wall posts + $postarray['author-name'] = $post->retweeted_status->user->name; + $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url; + $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url; + }*/ + logger("statusnet_createpost: end", LOGGER_DEBUG); + return($postarray); } -function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray) -{ +function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) { + // This function necer worked and need cleanup + $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($uid) - ); + ); - if (!count($user)) { + if(!count($user)) return; - } // Is it me? - if (link_compare($user[0]["url"], $postarray['author-link'])) { + if (link_compare($user[0]["url"], $postarray['author-link'])) return; - } $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", intval($uid), dbesc($own_url) - ); + ); - if (!count($own_user)) { + if(!count($own_user)) return; - } // Is it me from GNU Social? - if (link_compare($own_user[0]["url"], $postarray['author-link'])) { + if (link_compare($own_user[0]["url"], $postarray['author-link'])) return; - } $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", dbesc($postarray['parent-uri']), intval($uid) - ); + ); + + if(count($myconv)) { - if (count($myconv)) { - foreach ($myconv as $conv) { + foreach($myconv as $conv) { // now if we find a match, it means we're in this conversation - if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) { + + if(!link_compare($conv['author-link'],$user[0]["url"]) && !link_compare($conv['author-link'],$own_user[0]["url"])) continue; - } - require_once 'include/enotify.php'; + require_once('include/enotify.php'); $conv_parent = $conv['parent']; - notification([ - 'type' => NOTIFY_COMMENT, + notification(array( + 'type' => NOTIFY_COMMENT, 'notify_flags' => $user[0]['notify-flags'], - 'language' => $user[0]['language'], - 'to_name' => $user[0]['username'], - 'to_email' => $user[0]['email'], - 'uid' => $user[0]['uid'], - 'item' => $postarray, - 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)), - 'source_name' => $postarray['author-name'], - 'source_link' => $postarray['author-link'], + 'language' => $user[0]['language'], + 'to_name' => $user[0]['username'], + 'to_email' => $user[0]['email'], + 'uid' => $user[0]['uid'], + 'item' => $postarray, + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)), + 'source_name' => $postarray['author-name'], + 'source_link' => $postarray['author-link'], 'source_photo' => $postarray['author-avatar'], - 'verb' => ACTIVITY_POST, - 'otype' => 'item', - 'parent' => $conv_parent, - ]); + 'verb' => ACTIVITY_POST, + 'otype' => 'item', + 'parent' => $conv_parent, + )); // only send one notification break; @@ -1384,26 +1315,25 @@ function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarr } } -function statusnet_fetchhometimeline(App $a, $uid, $mode = 1) -{ - $conversations = []; +function statusnet_fetchhometimeline($a, $uid, $mode = 1) { + $conversations = array(); - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); - $create_user = PConfig::get($uid, 'statusnet', 'create_user'); + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); + $create_user = get_pconfig($uid, 'statusnet', 'create_user'); // "create_user" is deactivated, since currently you cannot add users manually by now $create_user = true; - logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG); - require_once 'library/twitteroauth.php'; - require_once 'include/items.php'; + require_once('library/twitteroauth.php'); + require_once('include/items.php'); - $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret); $own_contact = statusnet_fetch_own_contact($a, $uid); @@ -1411,75 +1341,71 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1) intval($own_contact), intval($uid)); - if (count($r)) { + if(count($r)) { $nick = $r[0]["nick"]; } else { - logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user ".$uid, LOGGER_DEBUG); return; } $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); - if (count($r)) { + if(count($r)) { $self = $r[0]; } else { - logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG); return; } $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1", intval($uid)); - if (!count($u)) { - logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG); + if(!count($u)) { + logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG); return; } - $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true]; + $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true); //$parameters["count"] = 200; if ($mode == 1) { // Fetching timeline - $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid'); + $lastid = get_pconfig($uid, 'statusnet', 'lasthometimelineid'); //$lastid = 1; $first_time = ($lastid == ""); - if ($lastid != "") { + if ($lastid <> "") $parameters["since_id"] = $lastid; - } $items = $connection->get('statuses/home_timeline', $parameters); if (!is_array($items)) { - if (is_object($items) && isset($items->error)) { + if (is_object($items) && isset($items->error)) $errormsg = $items->error; - } elseif (is_object($items)) { + elseif (is_object($items)) $errormsg = print_r($items, true); - } elseif (is_string($items) || is_float($items) || is_int($items)) { + elseif (is_string($items) || is_float($items) || is_int($items)) $errormsg = $items; - } else { + else $errormsg = "Unknown error"; - } - logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Error fetching home timeline: ".$errormsg, LOGGER_DEBUG); return; } $posts = array_reverse($items); - logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG); if (count($posts)) { foreach ($posts as $post) { - if ($post->id > $lastid) { + if ($post->id > $lastid) $lastid = $post->id; - } - if ($first_time) { + if ($first_time) continue; - } if (isset($post->statusnet_conversation_id)) { if (!isset($conversations[$post->statusnet_conversation_id])) { @@ -1489,52 +1415,48 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1) } else { $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true); - if (trim($postarray['body']) == "") { + if (trim($postarray['body']) == "") continue; - } $item = item_store($postarray); $postarray["id"] = $item; - logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item); + logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item); - if ($item && !function_exists("check_item_notification")) { + if ($item && !function_exists("check_item_notification")) statusnet_checknotification($a, $uid, $nick, $item, $postarray); - } } + } } - PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid); + set_pconfig($uid, 'statusnet', 'lasthometimelineid', $lastid); } // Fetching mentions - $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid'); + $lastid = get_pconfig($uid, 'statusnet', 'lastmentionid'); $first_time = ($lastid == ""); - if ($lastid != "") { + if ($lastid <> "") $parameters["since_id"] = $lastid; - } $items = $connection->get('statuses/mentions_timeline', $parameters); if (!is_array($items)) { - logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG); return; } $posts = array_reverse($items); - logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG); + logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG); if (count($posts)) { foreach ($posts as $post) { - if ($post->id > $lastid) { + if ($post->id > $lastid) $lastid = $post->id; - } - if ($first_time) { + if ($first_time) continue; - } $postarray = statusnet_createpost($a, $uid, $post, $self, false, false); @@ -1544,17 +1466,16 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1) $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id; } } else { - if (trim($postarray['body']) == "") { + if (trim($postarray['body']) != "") { continue; - } - $item = item_store($postarray); - $postarray["id"] = $item; + $item = item_store($postarray); + $postarray["id"] = $item; - logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item); + logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item); - if ($item && function_exists("check_item_notification")) { - check_item_notification($item, $uid, NOTIFY_TAGSELF); + if ($item && function_exists("check_item_notification")) + check_item_notification($item, $uid, NOTIFY_TAGSELF); } } @@ -1568,8 +1489,8 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1) } if (($item != 0) && !function_exists("check_item_notification")) { - require_once 'include/enotify.php'; - notification([ + require_once('include/enotify.php'); + notification(array( 'type' => NOTIFY_TAGSELF, 'notify_flags' => $u[0]['notify-flags'], 'language' => $u[0]['language'], @@ -1577,68 +1498,67 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1) 'to_email' => $u[0]['email'], 'uid' => $u[0]['uid'], 'item' => $postarray, - 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)), + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), 'source_name' => $postarray['author-name'], 'source_link' => $postarray['author-link'], 'source_photo' => $postarray['author-avatar'], 'verb' => ACTIVITY_TAG, 'otype' => 'item', 'parent' => $parent_id, - ]); + )); } } } - PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid); + set_pconfig($uid, 'statusnet', 'lastmentionid', $lastid); } -function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation) -{ - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); - $own_url = PConfig::get($uid, 'statusnet', 'own_url'); +function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) { + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); + $own_url = get_pconfig($uid, 'statusnet', 'own_url'); - require_once 'library/twitteroauth.php'; + require_once('library/twitteroauth.php'); - $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret); $parameters["count"] = 200; - $items = $connection->get('statusnet/conversation/' . $conversation, $parameters); + $items = $connection->get('statusnet/conversation/'.$conversation, $parameters); if (is_array($items)) { $posts = array_reverse($items); - foreach ($posts AS $post) { + foreach($posts AS $post) { $postarray = statusnet_createpost($a, $uid, $post, $self, false, false); - if (trim($postarray['body']) == "") { + if (trim($postarray['body']) == "") continue; - } + //print_r($postarray); $item = item_store($postarray); $postarray["id"] = $item; - logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item); + logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item); - if ($item && !function_exists("check_item_notification")) { + if ($item && !function_exists("check_item_notification")) statusnet_checknotification($a, $uid, $nick, $item, $postarray); - } } } } -function statusnet_convertmsg(App $a, $body, $no_tags = false) -{ - require_once "include/items.php"; - require_once "include/network.php"; +function statusnet_convertmsg($a, $body, $no_tags = false) { + + require_once("include/oembed.php"); + require_once("include/items.php"); + require_once("include/network.php"); - $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body); + $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism","$1.$2.$3.$4/$5",$body); $URLSearchString = "^\[\]"; - $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER); + $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER); $footer = ""; $footerurl = ""; @@ -1647,34 +1567,32 @@ function statusnet_convertmsg(App $a, $body, $no_tags = false) if ($links) { foreach ($matches AS $match) { - $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]"; + $search = "[url=".$match[1]."]".$match[2]."[/url]"; - logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG); + logger("statusnet_convertmsg: expanding url ".$match[1], LOGGER_DEBUG); $expanded_url = original_url($match[1]); - logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG); + logger("statusnet_convertmsg: fetching data for ".$expanded_url, LOGGER_DEBUG); - $oembed_data = OEmbed::fetchURL($expanded_url, true); + $oembed_data = oembed_fetch_url($expanded_url, true); logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG); - if ($type == "") { + if ($type == "") $type = $oembed_data->type; - } - if ($oembed_data->type == "video") { //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body); $type = $oembed_data->type; $footerurl = $expanded_url; - $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]"; + $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]"; $body = str_replace($search, $footerlink, $body); - } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) { - $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body); - } elseif ($oembed_data->type != "link") { - $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body); - } else { + } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) + $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body); + elseif ($oembed_data->type != "link") + $body = str_replace($search, "[url=".$expanded_url."]".$expanded_url."[/url]", $body); + else { $img_str = fetch_url($expanded_url, true, $redirects, 4); $tempfile = tempnam(get_temppath(), "cache"); @@ -1684,150 +1602,138 @@ function statusnet_convertmsg(App $a, $body, $no_tags = false) if (substr($mime, 0, 6) == "image/") { $type = "photo"; - $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body); + $body = str_replace($search, "[img]".$expanded_url."[/img]", $body); } else { $type = $oembed_data->type; $footerurl = $expanded_url; - $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]"; + $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]"; $body = str_replace($search, $footerlink, $body); } } } - if ($footerurl != "") { + if ($footerurl != "") $footer = add_page_info($footerurl); - } if (($footerlink != "") && (trim($footer) != "")) { $removedlink = trim(str_replace($footerlink, "", $body)); - if (($removedlink == "") || strstr($body, $removedlink)) { + if (($removedlink == "") || strstr($body, $removedlink)) $body = $removedlink; - } $body .= $footer; } } - if ($no_tags) { - return ["body" => $body, "tags" => ""]; - } + if ($no_tags) + return(array("body" => $body, "tags" => "")); $str_tags = ''; - $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER); - if ($cnt) { - foreach ($matches as $mtch) { - if (strlen($str_tags)) { + $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER); + if($cnt) { + foreach($matches as $mtch) { + if(strlen($str_tags)) $str_tags .= ','; - } if ($mtch[1] == "#") { // Replacing the hash tags that are directed to the GNU Social server with internal links - $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]"; - $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]'; + $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]"; + $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]'; $body = str_replace($snhash, $frdchash, $body); $str_tags .= $frdchash; - } else { - $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]"; - } - // To-Do: - // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups - //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]"; + } else + $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]"; + // To-Do: + // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups + //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]"; } } - return ["body" => $body, "tags" => $str_tags]; + return(array("body"=>$body, "tags"=>$str_tags)); + } -function statusnet_fetch_own_contact(App $a, $uid) -{ - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); - $own_url = PConfig::get($uid, 'statusnet', 'own_url'); +function statusnet_fetch_own_contact($a, $uid) { + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); + $own_url = get_pconfig($uid, 'statusnet', 'own_url'); $contact_id = 0; if ($own_url == "") { - require_once 'library/twitteroauth.php'; + require_once('library/twitteroauth.php'); - $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret); // Fetching user data $user = $connection->get('account/verify_credentials'); - PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url)); + set_pconfig($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url)); $contact_id = statusnet_fetch_contact($uid, $user, true); + } else { $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", intval($uid), dbesc($own_url)); - if (count($r)) { + if(count($r)) $contact_id = $r[0]["id"]; - } else { - PConfig::delete($uid, 'statusnet', 'own_url'); - } + else + del_pconfig($uid, 'statusnet', 'own_url'); + } - return $contact_id; + return($contact_id); } -function statusnet_is_retweet(App $a, $uid, $body) -{ +function statusnet_is_retweet($a, $uid, $body) { $body = trim($body); // Skip if it isn't a pure repeated messages // Does it start with a share? - if (strpos($body, "[share") > 0) { - return false; - } + if (strpos($body, "[share") > 0) + return(false); // Does it end with a share? - if (strlen($body) > (strrpos($body, "[/share]") + 8)) { - return false; - } + if (strlen($body) > (strrpos($body, "[/share]") + 8)) + return(false); - $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body); + $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body); // Skip if there is no shared message in there - if ($body == $attributes) { - return false; - } + if ($body == $attributes) + return(false); $link = ""; preg_match("/link='(.*?)'/ism", $attributes, $matches); - if ($matches[1] != "") { + if ($matches[1] != "") $link = $matches[1]; - } preg_match('/link="(.*?)"/ism', $attributes, $matches); - if ($matches[1] != "") { + if ($matches[1] != "") $link = $matches[1]; - } - $ckey = PConfig::get($uid, 'statusnet', 'consumerkey'); - $csecret = PConfig::get($uid, 'statusnet', 'consumersecret'); - $api = PConfig::get($uid, 'statusnet', 'baseapi'); - $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken'); - $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret'); + $ckey = get_pconfig($uid, 'statusnet', 'consumerkey'); + $csecret = get_pconfig($uid, 'statusnet', 'consumersecret'); + $api = get_pconfig($uid, 'statusnet', 'baseapi'); + $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken'); + $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret'); $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api); - $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link); - - if ($id == $link) { - return false; - } + $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link); - logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG); + if ($id == $link) + return(false); - $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret); + logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG); - $result = $connection->post('statuses/retweet/' . $id); + $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret); - logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG); + $result = $connection->post('statuses/retweet/'.$id); - return isset($result->id); + logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG); + return(isset($result->id)); } diff --git a/superblock/lang/es/messages.po b/superblock/lang/es/messages.po index 3bbdeb90..5f81fef8 100644 --- a/superblock/lang/es/messages.po +++ b/superblock/lang/es/messages.po @@ -4,15 +4,15 @@ # # # Translators: -# Albert, 2016-2017 +# Albert, 2016 # juanman , 2017 msgid "" msgstr "" "Project-Id-Version: friendica\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-04-21 08:45+0200\n" -"PO-Revision-Date: 2017-10-26 18:00+0000\n" -"Last-Translator: Albert\n" +"PO-Revision-Date: 2017-07-04 16:27+0000\n" +"Last-Translator: juanman \n" "Language-Team: Spanish (http://www.transifex.com/Friendica/friendica/language/es/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" @@ -22,7 +22,7 @@ msgstr "" #: superblock.php:53 superblock.php:57 msgid "\"Superblock\"" -msgstr "«Superbloque»" +msgstr "" #: superblock.php:60 msgid "Comma separated profile URLS to block" @@ -34,7 +34,7 @@ msgstr "Guardar configuración" #: superblock.php:76 msgid "SUPERBLOCK Settings saved." -msgstr "Ajustes de SUPERBLOQUE guardados." +msgstr "" #: superblock.php:148 msgid "Block Completely" @@ -42,4 +42,4 @@ msgstr "Bloquear completamente" #: superblock.php:168 msgid "superblock settings updated" -msgstr "ajustes de superbloque actualizados" +msgstr "" diff --git a/superblock/lang/es/strings.php b/superblock/lang/es/strings.php index 1b40975f..cb80c96e 100644 --- a/superblock/lang/es/strings.php +++ b/superblock/lang/es/strings.php @@ -5,9 +5,9 @@ function string_plural_select_es($n){ return ($n != 1);; }} ; -$a->strings["\"Superblock\""] = "«Superbloque»"; +$a->strings["\"Superblock\""] = ""; $a->strings["Comma separated profile URLS to block"] = "Perfil de URLS a bloque separado por comas"; $a->strings["Save Settings"] = "Guardar configuración"; -$a->strings["SUPERBLOCK Settings saved."] = "Ajustes de SUPERBLOQUE guardados."; +$a->strings["SUPERBLOCK Settings saved."] = ""; $a->strings["Block Completely"] = "Bloquear completamente"; -$a->strings["superblock settings updated"] = "ajustes de superbloque actualizados"; +$a->strings["superblock settings updated"] = ""; diff --git a/superblock/superblock.php b/superblock/superblock.php index c33c699d..c86c6aad 100644 --- a/superblock/superblock.php +++ b/superblock/superblock.php @@ -9,8 +9,6 @@ * */ -use Friendica\Core\PConfig; - function superblock_install() { register_hook('plugin_settings', 'addon/superblock/superblock.php', 'superblock_addon_settings'); @@ -46,7 +44,7 @@ function superblock_addon_settings(&$a,&$s) { $a->page['htmlhead'] .= '' . "\r\n"; - $words = PConfig::get(local_user(),'system','blocked'); + $words = get_pconfig(local_user(),'system','blocked'); if(! $words) { $words = ''; } @@ -74,14 +72,14 @@ function superblock_addon_settings_post(&$a,&$b) { return; if($_POST['superblock-submit']) { - PConfig::set(local_user(),'system','blocked',trim($_POST['superblock-words'])); + set_pconfig(local_user(),'system','blocked',trim($_POST['superblock-words'])); info( t('SUPERBLOCK Settings saved.') . EOL); } } function superblock_enotify_store(&$a,&$b) { - $words = PConfig::get($b['uid'],'system','blocked'); + $words = get_pconfig($b['uid'],'system','blocked'); if($words) { $arr = explode(',',$words); } @@ -113,7 +111,7 @@ function superblock_conversation_start(&$a,&$b) { if(! local_user()) return; - $words = PConfig::get(local_user(),'system','blocked'); + $words = get_pconfig(local_user(),'system','blocked'); if($words) { $a->data['superblock'] = explode(',',$words); } @@ -158,7 +156,7 @@ function superblock_init(&$a) { if(! local_user()) return; - $words = PConfig::get(local_user(),'system','blocked'); + $words = get_pconfig(local_user(),'system','blocked'); if(array_key_exists('block',$_GET) && $_GET['block']) { if(strlen($words)) @@ -166,7 +164,7 @@ function superblock_init(&$a) { $words .= trim($_GET['block']); } - PConfig::set(local_user(),'system','blocked',$words); + set_pconfig(local_user(),'system','blocked',$words); info( t('superblock settings updated') . EOL ); killme(); } diff --git a/testdrive/testdrive.php b/testdrive/testdrive.php index 6203f3cd..9bbeb1d8 100644 --- a/testdrive/testdrive.php +++ b/testdrive/testdrive.php @@ -7,8 +7,7 @@ * Author: Mike Macgirvin */ -use Friendica\Core\Config; -use Friendica\Model\User; + function testdrive_install() { @@ -38,7 +37,7 @@ function testdrive_register_account($a,$b) { $uid = $b; - $days = Config::get('testdrive','expiredays'); + $days = get_config('testdrive','expiredays'); if(! $days) return; @@ -58,7 +57,7 @@ function testdrive_cron($a,$b) { if(count($r)) { foreach($r as $rr) { - notification([ + notification(array( 'uid' => $rr['uid'], 'type' => NOTIFY_SYSTEM, 'system_type' => 'testdrive_expire', @@ -68,7 +67,7 @@ function testdrive_cron($a,$b) { 'source_name' => t('Administrator'), 'source_link' => $a->get_baseurl(), 'source_photo' => $a->get_baseurl() . '/images/person-80.jpg', - ]); + )); q("update user set expire_notification_sent = '%s' where uid = %d", dbesc(datetime_convert()), @@ -80,17 +79,19 @@ function testdrive_cron($a,$b) { $r = q("select * from user where account_expired = 1 and account_expires_on < UTC_TIMESTAMP() - INTERVAL 5 DAY "); if(count($r)) { - foreach($r as $rr) { - User::remove($rr['uid']); - } + require_once('include/Contact.php'); + foreach($r as $rr) + user_remove($rr['uid']); + } + } function testdrive_enotify(&$a, &$b) { if (x($b, 'params') && $b['params']['type'] == NOTIFY_SYSTEM && x($b['params'], 'system_type') && $b['params']['system_type'] === 'testdrive_expire') { $b['itemlink'] = $a->get_baseurl(); - $b['epreamble'] = $b['preamble'] = sprintf( t('Your account on %s will expire in a few days.'), Config::get('system','sitename')); + $b['epreamble'] = $b['preamble'] = sprintf( t('Your account on %s will expire in a few days.'), get_config('system','sitename')); $b['subject'] = t('Your Friendica test account is about to expire.'); $b['body'] = sprintf( t("Hi %1\$s,\n\nYour test account on %2\$s will expire in less than five days. We hope you enjoyed this test drive and use this opportunity to find a permanent Friendica website for your integrated social communications. A list of public sites is available at %s/siteinfo - and for more information on setting up your own Friendica server please see the Friendica project website at http://friendica.com."), $b['params']['to_name'], "[url=".$app->config["system"]["url"]."]".$app->config["sitename"]."[/url]", get_server()); } diff --git a/tictac/tictac.php b/tictac/tictac.php index 99737841..1dd1ccb0 100644 --- a/tictac/tictac.php +++ b/tictac/tictac.php @@ -17,7 +17,7 @@ function tictac_uninstall() { } function tictac_app_menu($a,&$b) { - $b['app_menu'][] = ''; + $b['app_menu'][] = ''; } @@ -39,7 +39,7 @@ function tictac_content(&$a) { $dimen = $a->argv[3]; $yours = $a->argv[4]; $mine = $a->argv[5]; - + $yours .= $_POST['move']; } elseif($a->argc > 1) { @@ -59,7 +59,7 @@ function tictac_content(&$a) { $o .= '' . t('New game with handicap') . '
    '; $o .= '

    ' . t('Three dimensional tic-tac-toe is just like the traditional game except that it is played on multiple levels simultaneously. '); $o .= t('In this case there are three levels. You win by getting three in a row on any level, as well as up, down, and diagonally across the different levels.'); - $o .= '

    '; + $o .= '

    '; $o .= t('The handicap game disables the center position on the middle level because the player claiming this square often has an unfair advantage.'); $o .= '

    '; @@ -73,11 +73,11 @@ class tictac { private $handicap = 0; private $yours; private $mine; - private $winning_play; + private $winning_play; private $you; private $me; private $debug = 1; - private $crosses = ['011','101','110','112','121','211']; + private $crosses = array('011','101','110','112','121','211'); /* '001','010','011','012','021', @@ -85,82 +85,82 @@ class tictac { '201','210','211','212','221'); */ - private $corners = [ + private $corners = array( '000','002','020','022', - '200','202','220','222']; - - private $planes = [ - ['000','001','002','010','011','012','020','021','022'], // horiz 1 - ['100','101','102','110','111','112','120','121','122'], // 2 - ['200','201','202','210','211','212','220','221','222'], // 3 - ['000','010','020','100','110','120','200','210','220'], // vert left - ['000','001','002','100','101','102','200','201','202'], // vert top - ['002','012','022','102','112','122','202','212','222'], // vert right - ['020','021','022','120','121','122','220','221','222'], // vert bot - ['010','011','012','110','111','112','210','211','212'], // left vertx - ['001','011','021','101','111','221','201','211','221'], // top vertx - ['000','001','002','110','111','112','220','221','222'], // diag top - ['020','021','022','110','111','112','200','201','202'], // diag bot - ['000','010','020','101','111','121','202','212','222'], // diag left - ['002','012','022','101','111','121','200','210','220'], // diag right - ['002','011','020','102','111','120','202','211','220'], // diag x - ['000','011','022','100','111','122','200','211','222'] // diag x - - ]; - - - private $winner = [ - ['000','001','002'], // board 0 winners - left corner across - ['000','010','020'], // down - ['000','011','022'], // diag - ['001','011','021'], // middle-top down - ['010','011','012'], // middle-left across - ['002','011','020'], // right-top diag - ['002','012','022'], // right-top down - ['020','021','022'], // bottom-left across - ['100','101','102'], // board 1 winners - ['100','110','120'], - ['100','111','122'], - ['101','111','121'], - ['110','111','112'], - ['102','111','120'], - ['102','112','122'], - ['120','121','122'], - ['200','201','202'], // board 2 winners - ['200','210','220'], - ['200','211','222'], - ['201','211','221'], - ['210','211','212'], - ['202','211','220'], - ['202','212','222'], - ['220','221','222'], - ['000','100','200'], // top-left corner 3d - ['000','101','202'], - ['000','110','220'], - ['000','111','222'], - ['001','101','201'], // top-middle 3d - ['001','111','221'], - ['002','102','202'], // top-right corner 3d - ['002','101','200'], - ['002','112','222'], - ['002','111','220'], - ['010','110','210'], // left-middle 3d - ['010','111','212'], - ['011','111','211'], // middle-middle 3d - ['012','112','212'], // right-middle 3d - ['012','111','210'], - ['020','120','220'], // bottom-left corner 3d - ['020','110','200'], - ['020','121','222'], - ['020','111','202'], - ['021','121','221'], // bottom-middle 3d - ['021','111','201'], - ['022','122','222'], // bottom-right corner 3d - ['022','121','220'], - ['022','112','202'], - ['022','111','200'] - - ]; + '200','202','220','222'); + + private $planes = array( + array('000','001','002','010','011','012','020','021','022'), // horiz 1 + array('100','101','102','110','111','112','120','121','122'), // 2 + array('200','201','202','210','211','212','220','221','222'), // 3 + array('000','010','020','100','110','120','200','210','220'), // vert left + array('000','001','002','100','101','102','200','201','202'), // vert top + array('002','012','022','102','112','122','202','212','222'), // vert right + array('020','021','022','120','121','122','220','221','222'), // vert bot + array('010','011','012','110','111','112','210','211','212'), // left vertx + array('001','011','021','101','111','221','201','211','221'), // top vertx + array('000','001','002','110','111','112','220','221','222'), // diag top + array('020','021','022','110','111','112','200','201','202'), // diag bot + array('000','010','020','101','111','121','202','212','222'), // diag left + array('002','012','022','101','111','121','200','210','220'), // diag right + array('002','011','020','102','111','120','202','211','220'), // diag x + array('000','011','022','100','111','122','200','211','222') // diag x + + ); + + + private $winner = array( + array('000','001','002'), // board 0 winners - left corner across + array('000','010','020'), // down + array('000','011','022'), // diag + array('001','011','021'), // middle-top down + array('010','011','012'), // middle-left across + array('002','011','020'), // right-top diag + array('002','012','022'), // right-top down + array('020','021','022'), // bottom-left across + array('100','101','102'), // board 1 winners + array('100','110','120'), + array('100','111','122'), + array('101','111','121'), + array('110','111','112'), + array('102','111','120'), + array('102','112','122'), + array('120','121','122'), + array('200','201','202'), // board 2 winners + array('200','210','220'), + array('200','211','222'), + array('201','211','221'), + array('210','211','212'), + array('202','211','220'), + array('202','212','222'), + array('220','221','222'), + array('000','100','200'), // top-left corner 3d + array('000','101','202'), + array('000','110','220'), + array('000','111','222'), + array('001','101','201'), // top-middle 3d + array('001','111','221'), + array('002','102','202'), // top-right corner 3d + array('002','101','200'), + array('002','112','222'), + array('002','111','220'), + array('010','110','210'), // left-middle 3d + array('010','111','212'), + array('011','111','211'), // middle-middle 3d + array('012','112','212'), // right-middle 3d + array('012','111','210'), + array('020','120','220'), // bottom-left corner 3d + array('020','110','200'), + array('020','121','222'), + array('020','111','202'), + array('021','121','221'), // bottom-middle 3d + array('021','111','201'), + array('022','122','222'), // bottom-right corner 3d + array('022','121','220'), + array('022','112','202'), + array('022','111','200') + + ); function __construct($dimen,$handicap,$mefirst,$yours,$mine) { $this->dimen = 3; @@ -209,7 +209,7 @@ class tictac { $this->mine .= $move; $this->me = $this->parse_moves('me'); } - else { + else { $move = $this->offensive_move(); if(strlen($move)) { $this->mine .= $move; @@ -231,7 +231,7 @@ class tictac { $str = $this->mine; if($player == 'you') $str = $this->yours; - $ret = []; + $ret = array(); while(strlen($str)) { $ret[] = substr($str,0,3); $str = substr($str,3); @@ -299,7 +299,7 @@ function winning_move() { if($this->handicap) { $p = $this->uncontested_plane(); foreach($this->corners as $c) - if((in_array($c,$p)) + if((in_array($c,$p)) && (! $this->is_yours($c)) && (! $this->is_mine($c))) return($c); } @@ -320,11 +320,11 @@ function winning_move() { if(in_array($this->me[0],$this->corners)) { $p = $this->my_best_plane(); foreach($this->winner as $w) { - if((in_array($w[0],$this->you)) + if((in_array($w[0],$this->you)) || (in_array($w[1],$this->you)) || (in_array($w[2],$this->you))) - continue; - if(in_array($w[0],$this->corners) + continue; + if(in_array($w[0],$this->corners) && in_array($w[2],$this->corners) && in_array($w[0],$p) && in_array($w[2],$p)) { if($this->me[0] == $w[0]) @@ -338,7 +338,7 @@ function winning_move() { else { $r = $this->get_corners($this->me); if(count($r) > 1) { - $w1 = []; $w2 = []; + $w1 = array(); $w2 = array(); foreach($this->winner as $w) { if(in_array('111',$w)) continue; @@ -350,13 +350,13 @@ function winning_move() { if(count($w1) && count($w2)) { foreach($w1 as $a) { foreach($w2 as $b) { - if((in_array($a[0],$this->you)) + if((in_array($a[0],$this->you)) || (in_array($a[1],$this->you)) || (in_array($a[2],$this->you)) || (in_array($b[0],$this->you)) || (in_array($b[1],$this->you)) || (in_array($b[2],$this->you))) - continue; + continue; if(($a[0] == $b[0]) && ! $this->is_mine($a[0])) { return $a[0]; } @@ -375,8 +375,8 @@ function winning_move() { // && in_array($this->you[0],$this->corners) // && $this->is_neighbor($this->me[0],$this->you[0])) { - // Yuck. You foiled my plan. Since you obviously aren't playing to win, - // I'll try again. You may keep me busy for a few rounds, but I'm + // Yuck. You foiled my plan. Since you obviously aren't playing to win, + // I'll try again. You may keep me busy for a few rounds, but I'm // gonna' get you eventually. // $p = $this->uncontested_plane(); @@ -388,14 +388,14 @@ function winning_move() { // find all the winners containing my points. - $mywinners = []; + $mywinners = array(); foreach($this->winner as $w) foreach($this->me as $m) if((in_array($m,$w)) && (! in_array($w,$mywinners))) $mywinners[] = $w; // find all the rules where my points are in the center. - $trythese = []; + $trythese = array(); if(count($mywinners)) { foreach($mywinners as $w) { foreach($this->me as $m) { @@ -406,19 +406,19 @@ function winning_move() { } } - $myplanes = []; + $myplanes = array(); for($p = 0; $p < count($this->planes); $p ++) { if($this->handicap && in_array('111',$this->planes[$p])) continue; foreach($this->me as $m) - if((in_array($m,$this->planes[$p])) + if((in_array($m,$this->planes[$p])) && (! in_array($this->planes[$p],$myplanes))) $myplanes[] = $this->planes[$p]; } shuffle($myplanes); // find all winners which share an endpoint, and which are uncontested - $candidates = []; + $candidates = array(); if(count($trythese) && count($myplanes)) { foreach($trythese as $t) { foreach($this->winner as $w) { @@ -436,7 +436,7 @@ function winning_move() { // Find out if we are about to force a win. // Looking for two winning vectors with a common endpoint - // and where we own the middle of both - we are now going to + // and where we own the middle of both - we are now going to // grab the endpoint. The game isn't yet over but we've already won. if(count($candidates)) { @@ -452,7 +452,7 @@ function winning_move() { } // find opponents planes - $yourplanes = []; + $yourplanes = array(); for($p = 0; $p < count($this->planes); $p ++) { if($this->handicap && in_array('111',$this->planes[$p])) continue; @@ -466,7 +466,7 @@ function winning_move() { // We now have a list of winning strategy vectors for our second point // Pick one that will force you into defensive mode. // Pick a point close to you so we don't risk giving you two - // in a row when you block us. That would force *us* into + // in a row when you block us. That would force *us* into // defensive mode. // We want: or: not: // X|O| X| | X| | @@ -475,41 +475,41 @@ function winning_move() { if(count($this->you) == 1) { foreach($this->winner as $w) { - if(in_array($this->me[0], $w) && in_array($c[1],$w) - && $this->uncontested_winner($w) + if(in_array($this->me[0], $w) && in_array($c[1],$w) + && $this->uncontested_winner($w) && $this->is_neighbor($this->you[0],$c[1])) { return($c[1]); - } + } } } - } + } - // You're somewhere else entirely or have made more than one move + // You're somewhere else entirely or have made more than one move // - any strategy vector which puts you on the defense will have to do foreach($candidates as $c) { foreach($this->winner as $w) { - if(in_array($this->me[0], $w) && in_array($c[1],$w) + if(in_array($this->me[0], $w) && in_array($c[1],$w) && $this->uncontested_winner($w)) { return($c[1]); - } + } } } } - // worst case scenario, no strategy we can play, + // worst case scenario, no strategy we can play, // just find an empty space and take it for($x = 0; $x < $this->dimen; $x ++) for($y = 0; $y < $this->dimen; $y ++) for($z = 0; $z < $this->dimen; $z ++) - if((! $this->marked_yours($x,$y,$z)) + if((! $this->marked_yours($x,$y,$z)) && (! $this->marked_mine($x,$y,$z))) { if($this->handicap && $x == 1 && $y == 1 && $z == 1) continue; return(sprintf("%d%d%d",$x,$y,$z)); } - + return ''; } @@ -540,7 +540,7 @@ function winning_move() { } function get_corners($a) { - $total = []; + $total = array(); if(count($a)) foreach($a as $b) if(in_array($b,$this->corners)) @@ -575,7 +575,7 @@ function winning_move() { function my_best_plane() { - $second_choice = []; + $second_choice = array(); shuffle($this->planes); for($p = 0; $p < count($this->planes); $p ++ ) { $contested = 0; @@ -585,7 +585,7 @@ function winning_move() { continue; foreach($this->you as $m) { if(in_array($m,$this->planes[$p])) - $contested ++; + $contested ++; } if(! $contested) return($this->planes[$p]); @@ -610,8 +610,8 @@ function winning_move() { if($this->handicap && in_array('111',$pl[$p])) continue; foreach($this->you as $m) { - if(in_array($m,$pl[$p])) - $freeplane = false; + if(in_array($m,$pl[$p])) + $freeplane = false; } if(! $freeplane) { $freeplane = true; @@ -620,7 +620,7 @@ function winning_move() { if($freeplane) return($pl[$p]); } - return []; + return array(); } function fullboard() { @@ -641,7 +641,7 @@ function winning_move() { $bordertop = (($y != 0) ? " border-top: 2px solid #000;" : ""); $borderleft = (($z != 0) ? " border-left: 2px solid #000;" : ""); if($this->handicap && $x == 1 && $y == 1 && $z == 1) - $o .= " "; + $o .= " "; elseif($this->marked_yours($x,$y,$z)) $o .= "X"; elseif($this->marked_mine($x,$y,$z)) diff --git a/tumblr/tumblr.php b/tumblr/tumblr.php index a056bd09..50530401 100644 --- a/tumblr/tumblr.php +++ b/tumblr/tumblr.php @@ -11,9 +11,6 @@ require_once('library/OAuth1.php'); require_once('addon/tumblr/tumblroauth/tumblroauth.php'); -use Friendica\Core\Config; -use Friendica\Core\PConfig; - function tumblr_install() { register_hook('post_local', 'addon/tumblr/tumblr.php', 'tumblr_post_local'); register_hook('notifier_normal', 'addon/tumblr/tumblr.php', 'tumblr_send'); @@ -60,19 +57,19 @@ function tumblr_content(&$a) { function tumblr_plugin_admin(&$a, &$o){ $t = get_markup_template( "admin.tpl", "addon/tumblr/" ); - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Save Settings'), // name, label, value, help, [extra values] - '$consumer_key' => ['consumer_key', t('Consumer Key'), Config::get('tumblr', 'consumer_key' ), ''], - '$consumer_secret' => ['consumer_secret', t('Consumer Secret'), Config::get('tumblr', 'consumer_secret' ), ''], - ]); + '$consumer_key' => array('consumer_key', t('Consumer Key'), get_config('tumblr', 'consumer_key' ), ''), + '$consumer_secret' => array('consumer_secret', t('Consumer Secret'), get_config('tumblr', 'consumer_secret' ), ''), + )); } function tumblr_plugin_admin_post(&$a){ $consumer_key = ((x($_POST,'consumer_key')) ? notags(trim($_POST['consumer_key'])) : ''); $consumer_secret = ((x($_POST,'consumer_secret')) ? notags(trim($_POST['consumer_secret'])): ''); - Config::set('tumblr','consumer_key',$consumer_key); - Config::set('tumblr','consumer_secret',$consumer_secret); + set_config('tumblr','consumer_key',$consumer_key); + set_config('tumblr','consumer_secret',$consumer_secret); info( t('Settings updated.'). EOL ); } @@ -84,8 +81,8 @@ function tumblr_connect($a) { //require_once('addon/tumblr/tumblroauth/tumblroauth.php'); // Define the needed keys - $consumer_key = Config::get('tumblr','consumer_key'); - $consumer_secret = Config::get('tumblr','consumer_secret'); + $consumer_key = get_config('tumblr','consumer_key'); + $consumer_secret = get_config('tumblr','consumer_secret'); // The callback URL is the script that gets called after the user authenticates with tumblr // In this example, it would be the included callback.php @@ -134,8 +131,8 @@ function tumblr_callback($a) { //require_once('addon/tumblr/tumblroauth/tumblroauth.php'); // Define the needed keys - $consumer_key = Config::get('tumblr','consumer_key'); - $consumer_secret = Config::get('tumblr','consumer_secret'); + $consumer_key = get_config('tumblr','consumer_key'); + $consumer_secret = get_config('tumblr','consumer_secret'); // Once the user approves your app at Tumblr, they are sent back to this script. // This script is passed two parameters in the URL, oauth_token (our Request Token) @@ -161,8 +158,8 @@ function tumblr_callback($a) { } // What's next? Now that we have an Access Token and Secret, we can make an API call. - PConfig::set(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']); - PConfig::set(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']); + set_pconfig(local_user(), "tumblr", "oauth_token", $access_token['oauth_token']); + set_pconfig(local_user(), "tumblr", "oauth_token_secret", $access_token['oauth_token_secret']); $o = t("You are now authenticated to tumblr."); $o .= '
    '.t("return to the connector page").''; @@ -173,9 +170,9 @@ function tumblr_jot_nets(&$a,&$b) { if(! local_user()) return; - $tmbl_post = PConfig::get(local_user(),'tumblr','post'); + $tmbl_post = get_pconfig(local_user(),'tumblr','post'); if(intval($tmbl_post) == 1) { - $tmbl_defpost = PConfig::get(local_user(),'tumblr','post_by_default'); + $tmbl_defpost = get_pconfig(local_user(),'tumblr','post_by_default'); $selected = ((intval($tmbl_defpost) == 1) ? ' checked="checked" ' : ''); $b .= '
    ' . t('Post to Tumblr') . '
    '; @@ -194,11 +191,11 @@ function tumblr_settings(&$a,&$s) { /* Get the current state of our config variables */ - $enabled = PConfig::get(local_user(),'tumblr','post'); + $enabled = get_pconfig(local_user(),'tumblr','post'); $checked = (($enabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); - $def_enabled = PConfig::get(local_user(),'tumblr','post_by_default'); + $def_enabled = get_pconfig(local_user(),'tumblr','post_by_default'); $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); @@ -226,26 +223,26 @@ function tumblr_settings(&$a,&$s) { $s .= ''; $s .= '
    '; - $oauth_token = PConfig::get(local_user(), "tumblr", "oauth_token"); - $oauth_token_secret = PConfig::get(local_user(), "tumblr", "oauth_token_secret"); + $oauth_token = get_pconfig(local_user(), "tumblr", "oauth_token"); + $oauth_token_secret = get_pconfig(local_user(), "tumblr", "oauth_token_secret"); $s .= '
    '; if (($oauth_token != "") && ($oauth_token_secret != "")) { - $page = PConfig::get(local_user(),'tumblr','page'); - $consumer_key = Config::get('tumblr','consumer_key'); - $consumer_secret = Config::get('tumblr','consumer_secret'); + $page = get_pconfig(local_user(),'tumblr','page'); + $consumer_key = get_config('tumblr','consumer_key'); + $consumer_secret = get_config('tumblr','consumer_secret'); $tum_oauth = new TumblrOAuth($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret); $userinfo = $tum_oauth->get('user/info'); - $blogs = []; + $blogs = array(); $s .= ''; $s .= ' ' . t('Post to Twitter') . '
    '; } } -function twitter_settings_post(App $a, $post) -{ - if (!local_user()) { +function twitter_settings_post ($a,$post) { + if(! local_user()) return; - } // don't check twitter settings if twitter submit button is not clicked - if (!x($_POST, 'twitter-submit')) { + if (!x($_POST,'twitter-submit')) return; - } if (isset($_POST['twitter-disconnect'])) { - /* * * + /*** * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair * from the user configuration */ - PConfig::delete(local_user(), 'twitter', 'consumerkey'); - PConfig::delete(local_user(), 'twitter', 'consumersecret'); - PConfig::delete(local_user(), 'twitter', 'oauthtoken'); - PConfig::delete(local_user(), 'twitter', 'oauthsecret'); - PConfig::delete(local_user(), 'twitter', 'post'); - PConfig::delete(local_user(), 'twitter', 'post_by_default'); - PConfig::delete(local_user(), 'twitter', 'lastid'); - PConfig::delete(local_user(), 'twitter', 'mirror_posts'); - PConfig::delete(local_user(), 'twitter', 'import'); - PConfig::delete(local_user(), 'twitter', 'create_user'); - PConfig::delete(local_user(), 'twitter', 'own_id'); + del_pconfig(local_user(), 'twitter', 'consumerkey'); + del_pconfig(local_user(), 'twitter', 'consumersecret'); + del_pconfig(local_user(), 'twitter', 'oauthtoken'); + del_pconfig(local_user(), 'twitter', 'oauthsecret'); + del_pconfig(local_user(), 'twitter', 'post'); + del_pconfig(local_user(), 'twitter', 'post_by_default'); + del_pconfig(local_user(), 'twitter', 'lastid'); + del_pconfig(local_user(), 'twitter', 'mirror_posts'); + del_pconfig(local_user(), 'twitter', 'import'); + del_pconfig(local_user(), 'twitter', 'create_user'); + del_pconfig(local_user(), 'twitter', 'own_id'); } else { - if (isset($_POST['twitter-pin'])) { - // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen - logger('got a Twitter PIN'); - require_once 'library/twitteroauth.php'; - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - // the token and secret for which the PIN was generated were hidden in the settings - // form as token and token2, we need a new connection to Twitter using these token - // and secret to request a Access Token with the PIN - $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']); - $token = $connection->getAccessToken($_POST['twitter-pin']); - // ok, now that we have the Access Token, save them in the user config - PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']); - PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']); - PConfig::set(local_user(), 'twitter', 'post', 1); - // reload the Addon Settings page, if we don't do it see Bug #42 - goaway('settings/connectors'); - } else { - // if no PIN is supplied in the POST variables, the user has changed the setting - // to post a tweet for every new __public__ posting to the wall - PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable'])); - PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default'])); - PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror'])); - PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import'])); - PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user'])); - - if (!intval($_POST['twitter-mirror'])) { - PConfig::delete(local_user(), 'twitter', 'lastid'); - } - - info(t('Twitter settings updated.') . EOL); - } - } + if (isset($_POST['twitter-pin'])) { + // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen + logger('got a Twitter PIN'); + require_once('library/twitteroauth.php'); + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + // the token and secret for which the PIN was generated were hidden in the settings + // form as token and token2, we need a new connection to Twitter using these token + // and secret to request a Access Token with the PIN + $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']); + $token = $connection->getAccessToken( $_POST['twitter-pin'] ); + // ok, now that we have the Access Token, save them in the user config + set_pconfig(local_user(),'twitter', 'oauthtoken', $token['oauth_token']); + set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']); + set_pconfig(local_user(),'twitter', 'post', 1); + // reload the Addon Settings page, if we don't do it see Bug #42 + goaway($a->get_baseurl().'/settings/connectors'); + } else { + // if no PIN is supplied in the POST variables, the user has changed the setting + // to post a tweet for every new __public__ posting to the wall + set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable'])); + set_pconfig(local_user(),'twitter','post_by_default',intval($_POST['twitter-default'])); + set_pconfig(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror'])); + set_pconfig(local_user(), 'twitter', 'import', intval($_POST['twitter-import'])); + set_pconfig(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user'])); + + if (!intval($_POST['twitter-mirror'])) + del_pconfig(local_user(),'twitter','lastid'); + + info(t('Twitter settings updated.') . EOL); + }} } - -function twitter_settings(App $a, &$s) -{ - if (!local_user()) { +function twitter_settings(&$a,&$s) { + if(! local_user()) return; - } $a->page['htmlhead'] .= '' . "\r\n"; - /* * * + /*** * 1) Check that we have global consumer key & secret * 2) If no OAuthtoken & stuff is present, generate button to get some - * 3) Checkbox for "Send public notices (280 chars only) + * 3) Checkbox for "Send public notices (140 chars only) */ - $ckey = Config::get('twitter', 'consumerkey' ); - $csecret = Config::get('twitter', 'consumersecret' ); - $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken' ); - $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret' ); - - $enabled = intval(PConfig::get(local_user(), 'twitter', 'post')); - $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default')); - $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts')); - $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import')); - $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user')); + $ckey = get_config('twitter', 'consumerkey' ); + $csecret = get_config('twitter', 'consumersecret' ); + $otoken = get_pconfig(local_user(), 'twitter', 'oauthtoken' ); + $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' ); + $enabled = get_pconfig(local_user(), 'twitter', 'post'); + $checked = (($enabled) ? ' checked="checked" ' : ''); + $defenabled = get_pconfig(local_user(),'twitter','post_by_default'); + $defchecked = (($defenabled) ? ' checked="checked" ' : ''); + $mirrorenabled = get_pconfig(local_user(),'twitter','mirror_posts'); + $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : ''); + $importenabled = get_pconfig(local_user(),'twitter','import'); + $importchecked = (($importenabled) ? ' checked="checked" ' : ''); + $create_userenabled = get_pconfig(local_user(),'twitter','create_user'); + $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); $s .= ''; - $s .= '

    ' . t('Twitter Import/Export/Mirror') . '

    '; + $s .= '

    '. t('Twitter Import/Export/Mirror').'

    '; $s .= '
    '; $s .= '
    '; + $s .= '
    '; } else { - /* * * + /*** * we have an OAuth key / secret pair for the user * so let's give a chance to disable the postings to Twitter */ - require_once 'library/twitteroauth.php'; - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + require_once('library/twitteroauth.php'); + $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); $details = $connection->get('account/verify_credentials'); + $s .= '

    '. t('Currently connected to: ') .''.$details->screen_name.'
    '.$details->description.'

    '; + $s .= '

    '. t('If enabled all your public postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') .'

    '; + if ($a->user['hidewall']) { + $s .= '

    '. t('Note: Due your privacy settings (Hide your profile details from unknown viewers?) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') .'

    '; + } + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; - $field_checkbox = get_markup_template('field_checkbox.tpl'); - - $s .= '
    -

    ' . t('Currently connected to: ') . '' . $details->screen_name . ' - -

    -

    - - ' . $details->description . ' -

    -
    '; + $s .= ''; + $s .= ''; $s .= '
    '; + $s .= '
    '; - $s .= replace_macros($field_checkbox, [ - '$field' => ['twitter-enable', t('Allow posting to Twitter'), $enabled, t('If enabled all your public postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')] - ]); - if ($a->user['hidewall']) { - $s .= '

    ' . t('Note: Due to your privacy settings (Hide your profile details from unknown viewers?) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '

    '; - } - $s .= replace_macros($field_checkbox, [ - '$field' => ['twitter-default', t('Send public postings to Twitter by default'), $defenabled, ''] - ]); - $s .= replace_macros($field_checkbox, [ - '$field' => ['twitter-mirror', t('Mirror all posts from twitter that are no replies'), $mirrorenabled, ''] - ]); - $s .= replace_macros($field_checkbox, [ - '$field' => ['twitter-import', t('Import the remote timeline'), $importenabled, ''] - ]); - $s .= replace_macros($field_checkbox, [ - '$field' => ['twitter-create_user', t('Automatically create contacts'), $create_userenabled, ''] - ]); + $s .= ''; + $s .= ''; + $s .= '
    '; + $s .= ''; + $s .= ''; $s .= '
    '; + + $s .= '
    '; + $s .= ''; + $s .= ''; + $s .= '
    '; $s .= '
    '; } } $s .= '
    '; } -function twitter_post_local(App $a, &$b) -{ + +function twitter_post_local(&$a, &$b) { + if ($b['edit']) { return; } @@ -367,11 +344,11 @@ function twitter_post_local(App $a, &$b) return; } - $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post')); + $twitter_post = intval(get_pconfig(local_user(), 'twitter', 'post')); $twitter_enable = (($twitter_post && x($_REQUEST, 'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0); // if API is used, default to the chosen settings - if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) { + if ($b['api_source'] && intval(get_pconfig(local_user(), 'twitter', 'post_by_default'))) { $twitter_enable = 1; } @@ -386,22 +363,22 @@ function twitter_post_local(App $a, &$b) $b['postopts'] .= 'twitter'; } -function twitter_action(App $a, $uid, $pid, $action) -{ - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); - $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); +function twitter_action($a, $uid, $pid, $action) { - require_once "addon/twitter/codebird.php"; + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($uid, 'twitter', 'oauthtoken'); + $osecret = get_pconfig($uid, 'twitter', 'oauthsecret'); + + require_once("addon/twitter/codebird.php"); $cb = \Codebird\Codebird::getInstance(); $cb->setConsumerKey($ckey, $csecret); $cb->setToken($otoken, $osecret); - $post = ['id' => $pid]; + $post = array('id' => $pid); - logger("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), LOGGER_DATA); + logger("twitter_action '".$action."' ID: ".$pid." data: " . print_r($post, true), LOGGER_DATA); switch ($action) { case "delete": @@ -414,25 +391,28 @@ function twitter_action(App $a, $uid, $pid, $action) $result = $cb->favorites_destroy($post); break; } - logger("twitter_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG); + logger("twitter_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG); } -function twitter_post_hook(App $a, &$b) -{ - // Post to Twitter - require_once "include/network.php"; +function twitter_post_hook(&$a,&$b) { - if (!PConfig::get($b["uid"], 'twitter', 'import') - && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) { - return; + /** + * Post to Twitter + */ + + require_once("include/network.php"); + + if (!get_pconfig($b["uid"],'twitter','import')) { + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) + return; } - if ($b['parent'] != $b['id']) { - logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA); + if($b['parent'] != $b['id']) { + logger("twitter_post_hook: parameter ".print_r($b, true), LOGGER_DATA); // Looking if its a reply to a twitter post if ((substr($b["parent-uri"], 0, 9) != "twitter::") && (substr($b["extid"], 0, 9) != "twitter::") && (substr($b["thr-parent"], 0, 9) != "twitter::")) { - logger("twitter_post_hook: no twitter post " . $b["parent"]); + logger("twitter_post_hook: no twitter post ".$b["parent"]); return; } @@ -440,8 +420,8 @@ function twitter_post_hook(App $a, &$b) dbesc($b["thr-parent"]), intval($b["uid"])); - if (!count($r)) { - logger("twitter_post_hook: no parent found " . $b["thr-parent"]); + if(!count($r)) { + logger("twitter_post_hook: no parent found ".$b["thr-parent"]); return; } else { $iscomment = true; @@ -450,36 +430,26 @@ function twitter_post_hook(App $a, &$b) $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]); - $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]"; - $nicknameplain = "@" . $nicknameplain; + $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]"; + $nicknameplain = "@".$nicknameplain; - logger("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG); - if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) { - $b["body"] = $nickname . " " . $b["body"]; - } + logger("twitter_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG); + if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) + $b["body"] = $nickname." ".$b["body"]; - logger("twitter_post_hook: parent found " . print_r($orig_post, true), LOGGER_DATA); + logger("twitter_post_hook: parent found ".print_r($orig_post, true), LOGGER_DATA); } else { $iscomment = false; - if ($b['private'] || !strstr($b['postopts'], 'twitter')) { - return; - } - - // Dont't post if the post doesn't belong to us. - // This is a check for forum postings - $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]); - if ($b['contact-id'] != $self['id']) { + if($b['private'] || !strstr($b['postopts'],'twitter')) return; - } } - if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) { + if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete"); - } - if ($b['verb'] == ACTIVITY_LIKE) { - logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG); + if($b['verb'] == ACTIVITY_LIKE) { + logger("twitter_post_hook: parameter 2 ".substr($b["thr-parent"], 9), LOGGER_DEBUG); if ($b['deleted']) twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike"); else @@ -487,61 +457,55 @@ function twitter_post_hook(App $a, &$b) return; } - if ($b['deleted'] || ($b['created'] !== $b['edited'])) { + if($b['deleted'] || ($b['created'] !== $b['edited'])) return; - } // if post comes from twitter don't send it back - if ($b['extid'] == NETWORK_TWITTER) { + if($b['extid'] == NETWORK_TWITTER) return; - } - if ($b['app'] == "Twitter") { + if($b['app'] == "Twitter") return; - } logger('twitter post invoked'); - PConfig::load($b['uid'], 'twitter'); - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken'); - $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret'); + load_pconfig($b['uid'], 'twitter'); + + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($b['uid'], 'twitter', 'oauthtoken'); + $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret'); - if ($ckey && $csecret && $otoken && $osecret) { + if($ckey && $csecret && $otoken && $osecret) { logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG); // If it's a repeated message from twitter then do a native retweet and exit - if (twitter_is_retweet($a, $b['uid'], $b['body'])) { + if (twitter_is_retweet($a, $b['uid'], $b['body'])) return; - } - require_once 'library/twitteroauth.php'; - require_once 'include/bbcode.php'; - $tweet = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + require_once('library/twitteroauth.php'); + require_once('include/bbcode.php'); + $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); - $max_char = 280; - require_once "include/plaintext.php"; - $msgarr = plaintext($b, $max_char, true, 8); + $max_char = 140; + require_once("include/plaintext.php"); + $msgarr = plaintext($a, $b, $max_char, true, 8); $msg = $msgarr["text"]; - if (($msg == "") && isset($msgarr["title"])) { + if (($msg == "") && isset($msgarr["title"])) $msg = shortenmsg($msgarr["title"], $max_char - 50); - } $image = ""; - if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) { - $msg .= "\n" . $msgarr["url"]; - } + if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) + $msg .= "\n".$msgarr["url"]; - if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) { + if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) $image = $msgarr["image"]; - } // and now tweet it :-) - if (strlen($msg) && ($image != "")) { + if(strlen($msg) && ($image != "")) { $img_str = fetch_url($image); $tempfile = tempnam(get_temppath(), "cache"); @@ -551,128 +515,112 @@ function twitter_post_hook(App $a, &$b) // so we are using a new library for twitter // To-Do: // Switching completely to this library with all functions - require_once "addon/twitter/codebird.php"; + require_once("addon/twitter/codebird.php"); $cb = \Codebird\Codebird::getInstance(); $cb->setConsumerKey($ckey, $csecret); $cb->setToken($otoken, $osecret); - $post = ['status' => $msg, 'media[]' => $tempfile]; + $post = array('status' => $msg, 'media[]' => $tempfile); - if ($iscomment) { + if ($iscomment) $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9); - } $result = $cb->statuses_updateWithMedia($post); unlink($tempfile); logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG); - if ($result->source) { - Config::set("twitter", "application_name", strip_tags($result->source)); - } + if ($result->source) + set_config("twitter", "application_name", strip_tags($result->source)); if ($result->errors || $result->error) { logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"'); // Workaround: Remove the picture link so that the post can be reposted without it - $msg .= " " . $image; + $msg .= " ".$image; $image = ""; } elseif ($iscomment) { - logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']); + logger('twitter_post: Update extid '.$result->id_str." for post id ".$b['id']); q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d", - dbesc("twitter::" . $result->id_str), + dbesc("twitter::".$result->id_str), dbesc($result->text), intval($b['id']) ); } } - if (strlen($msg) && ($image == "")) { -// ----------------- - $max_char = 280; - require_once "include/plaintext.php"; - $msgarr = plaintext($b, $max_char, true, 8); - $msg = $msgarr["text"]; - - if (($msg == "") && isset($msgarr["title"])) { - $msg = shortenmsg($msgarr["title"], $max_char - 50); - } - - if (isset($msgarr["url"])) { - $msg .= "\n" . $msgarr["url"]; - } -// ----------------- + if(strlen($msg) && ($image == "")) { $url = 'statuses/update'; - $post = ['status' => $msg, 'weighted_character_count' => 'true']; + $post = array('status' => $msg); - if ($iscomment) { + if ($iscomment) $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9); - } $result = $tweet->post($url, $post); logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG); - if ($result->source) { - Config::set("twitter", "application_name", strip_tags($result->source)); - } + if ($result->source) + set_config("twitter", "application_name", strip_tags($result->source)); if ($result->errors) { logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"'); $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid'])); - if (count($r)) { + if (count($r)) $a->contact = $r[0]["id"]; - } - $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]); - require_once 'include/queue_fn.php'; - add_to_queue($a->contact, NETWORK_TWITTER, $s); - notice(t('Twitter post failed. Queued for retry.') . EOL); + $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $post)); + require_once('include/queue_fn.php'); + add_to_queue($a->contact,NETWORK_TWITTER,$s); + notice(t('Twitter post failed. Queued for retry.').EOL); } elseif ($iscomment) { - logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']); + logger('twitter_post: Update extid '.$result->id_str." for post id ".$b['id']); q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d", - dbesc("twitter::" . $result->id_str), + dbesc("twitter::".$result->id_str), intval($b['id']) ); + //q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d", + // dbesc("twitter::".$result->id_str), + // dbesc($result->text), + // intval($b['id']) + //); } } } } -function twitter_plugin_admin_post(App $a) -{ - $consumerkey = x($_POST, 'consumerkey') ? notags(trim($_POST['consumerkey'])) : ''; - $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : ''; - Config::set('twitter', 'consumerkey', $consumerkey); - Config::set('twitter', 'consumersecret', $consumersecret); - info(t('Settings updated.') . EOL); +function twitter_plugin_admin_post(&$a){ + $consumerkey = ((x($_POST,'consumerkey')) ? notags(trim($_POST['consumerkey'])) : ''); + $consumersecret = ((x($_POST,'consumersecret')) ? notags(trim($_POST['consumersecret'])): ''); + $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'])):''); + set_config('twitter','consumerkey',$consumerkey); + set_config('twitter','consumersecret',$consumersecret); + //set_config('twitter','application_name',$applicationname); + info( t('Settings updated.'). EOL ); } +function twitter_plugin_admin(&$a, &$o){ + $t = get_markup_template( "admin.tpl", "addon/twitter/" ); -function twitter_plugin_admin(App $a, &$o) -{ - $t = get_markup_template("admin.tpl", "addon/twitter/"); - - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Save Settings'), - // name, label, value, help, [extra values] - '$consumerkey' => ['consumerkey', t('Consumer key'), Config::get('twitter', 'consumerkey'), ''], - '$consumersecret' => ['consumersecret', t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''], - ]); + // name, label, value, help, [extra values] + '$consumerkey' => array('consumerkey', t('Consumer key'), get_config('twitter', 'consumerkey' ), ''), + '$consumersecret' => array('consumersecret', t('Consumer secret'), get_config('twitter', 'consumersecret' ), ''), + //'$applicationname' => array('applicationname', t('Name of the Twitter Application'), get_config('twitter','application_name'),t('Set this to the exact name you gave the app on twitter.com/apps to avoid mirroring postings from ~friendica back to ~friendica')) + )); } -function twitter_cron(App $a, $b) -{ - $last = Config::get('twitter', 'last_poll'); +function twitter_cron($a,$b) { + $last = get_config('twitter','last_poll'); - $poll_interval = intval(Config::get('twitter', 'poll_interval')); - if (!$poll_interval) { + $poll_interval = intval(get_config('twitter','poll_interval')); + if(! $poll_interval) $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL; - } - if ($last) { + if($last) { $next = $last + ($poll_interval * 60); - if ($next > time()) { + if($next > time()) { logger('twitter: poll intervall not reached'); return; } @@ -680,80 +628,80 @@ function twitter_cron(App $a, $b) logger('twitter: cron_start'); $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'"); - if (count($r)) { - foreach ($r as $rr) { - logger('twitter: fetching for user ' . $rr['uid']); - Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']); + if(count($r)) { + foreach($r as $rr) { + logger('twitter: fetching for user '.$rr['uid']); + proc_run(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 1, (int)$rr['uid']); } } - $abandon_days = intval(Config::get('system', 'account_abandon_days')); + $abandon_days = intval(get_config('system','account_abandon_days')); if ($abandon_days < 1) $abandon_days = 0; $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400); $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'"); - if (count($r)) { - foreach ($r as $rr) { + if(count($r)) { + foreach($r as $rr) { if ($abandon_days != 0) { $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit); if (!count($user)) { - logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported'); + logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported'); continue; } } - logger('twitter: importing timeline from user ' . $rr['uid']); - Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']); - /* - // To-Do - // check for new contacts once a day - $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check'); - if($last_contact_check) - $next_contact_check = $last_contact_check + 86400; - else - $next_contact_check = 0; - - if($next_contact_check <= time()) { - pumpio_getallusers($a, $rr["uid"]); - PConfig::set($rr['uid'],'pumpio','contact_check',time()); - } - */ + logger('twitter: importing timeline from user '.$rr['uid']); + proc_run(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 2, (int)$rr['uid']); +/* + // To-Do + // check for new contacts once a day + $last_contact_check = get_pconfig($rr['uid'],'pumpio','contact_check'); + if($last_contact_check) + $next_contact_check = $last_contact_check + 86400; + else + $next_contact_check = 0; + + if($next_contact_check <= time()) { + pumpio_getallusers($a, $rr["uid"]); + set_pconfig($rr['uid'],'pumpio','contact_check',time()); + } +*/ + } } logger('twitter: cron_end'); - Config::set('twitter', 'last_poll', time()); + set_config('twitter','last_poll', time()); } -function twitter_expire(App $a, $b) -{ - $days = Config::get('twitter', 'expire'); +function twitter_expire($a,$b) { + + $days = get_config('twitter', 'expire'); - if ($days == 0) { + if ($days == 0) return; - } if (method_exists('dba', 'delete')) { - $r = dba::select('item', ['id'], ['deleted' => true, 'network' => NETWORK_TWITTER]); + $r = dba::select('item', array('id'), array('deleted' => true, 'network' => NETWORK_TWITTER)); while ($row = dba::fetch($r)) { - dba::delete('item', ['id' => $row['id']]); + dba::delete('item', array('id' => $row['id'])); } dba::close($r); } else { $r = q("DELETE FROM `item` WHERE `deleted` AND `network` = '%s'", dbesc(NETWORK_TWITTER)); } - require_once "include/items.php"; + require_once("include/items.php"); logger('twitter_expire: expire_start'); $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()"); - if (count($r)) { - foreach ($r as $rr) { - logger('twitter_expire: user ' . $rr['uid']); + if(count($r)) { + foreach($r as $rr) { + logger('twitter_expire: user '.$rr['uid']); item_expire($rr['uid'], $days, NETWORK_TWITTER, true); } } @@ -761,77 +709,73 @@ function twitter_expire(App $a, $b) logger('twitter_expire: expire_end'); } -function twitter_prepare_body(App $a, &$b) -{ - if ($b["item"]["network"] != NETWORK_TWITTER) { +function twitter_prepare_body(&$a,&$b) { + if ($b["item"]["network"] != NETWORK_TWITTER) return; - } if ($b["preview"]) { - $max_char = 280; - require_once "include/plaintext.php"; + $max_char = 140; + require_once("include/plaintext.php"); $item = $b["item"]; - $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"]; + $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"]; $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", dbesc($item["thr-parent"]), intval(local_user())); - if (count($r)) { + if(count($r)) { $orig_post = $r[0]; $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]); - $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]"; - $nicknameplain = "@" . $nicknameplain; + $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]"; + $nicknameplain = "@".$nicknameplain; - if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) { - $item["body"] = $nickname . " " . $item["body"]; - } + if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) + $item["body"] = $nickname." ".$item["body"]; } - $msgarr = plaintext($item, $max_char, true, 8); + + $msgarr = plaintext($a, $item, $max_char, true, 8); $msg = $msgarr["text"]; - if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) { - $msg .= " " . $msgarr["url"]; - } + if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) + $msg .= " ".$msgarr["url"]; - if (isset($msgarr["image"])) { - $msg .= " " . $msgarr["image"]; - } + if (isset($msgarr["image"])) + $msg .= " ".$msgarr["image"]; - $b['html'] = nl2br(htmlspecialchars($msg)); + $b['html'] = nl2br(htmlspecialchars($msg)); } } /** * @brief Build the item array for the mirrored post * - * @param App $a Application class + * @param object $a Application class * @param integer $uid User id * @param object $post Twitter object with the post * * @return array item data to be posted */ -function twitter_do_mirrorpost(App $a, $uid, $post) -{ +function twitter_do_mirrorpost($a, $uid, $post) { $datarray["type"] = "wall"; $datarray["api_source"] = true; $datarray["profile_uid"] = $uid; $datarray["extid"] = NETWORK_TWITTER; - $datarray['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_TWITTER . ":" . $post->id); + $datarray['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_TWITTER.":".$post->id); $datarray['object'] = json_encode($post); $datarray["title"] = ""; if (is_object($post->retweeted_status)) { // We don't support nested shares, so we mustn't show quotes as shares on retweets - $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true); + $item = twitter_createpost($a, $uid, $post->retweeted_status, array('id' => 0), false, false, true); - $datarray['body'] = "\n" . share_header($item['author-name'], $item['author-link'], $item['author-avatar'], "", $item['created'], $item['plink']); + $datarray['body'] = "\n".share_header($item['author-name'], $item['author-link'], $item['author-avatar'], "", + $item['created'], $item['plink']); - $datarray['body'] .= $item['body'] . '[/share]'; + $datarray['body'] .= $item['body'].'[/share]'; } else { - $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false); + $item = twitter_createpost($a, $uid, $post, array('id' => 0), false, false, false); $datarray['body'] = $item['body']; } @@ -850,86 +794,80 @@ function twitter_do_mirrorpost(App $a, $uid, $post) return $datarray; } -function twitter_fetchtimeline(App $a, $uid) -{ - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); - $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); - $lastid = PConfig::get($uid, 'twitter', 'lastid'); +function twitter_fetchtimeline($a, $uid) { + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($uid, 'twitter', 'oauthtoken'); + $osecret = get_pconfig($uid, 'twitter', 'oauthsecret'); + $lastid = get_pconfig($uid, 'twitter', 'lastid'); - $application_name = Config::get('twitter', 'application_name'); + $application_name = get_config('twitter', 'application_name'); - if ($application_name == "") { + if ($application_name == "") $application_name = $a->get_hostname(); - } $has_picture = false; - require_once 'mod/item.php'; - require_once 'include/items.php'; - require_once 'mod/share.php'; + require_once('mod/item.php'); + require_once('include/items.php'); + require_once('mod/share.php'); - require_once 'library/twitteroauth.php'; - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + require_once('library/twitteroauth.php'); + $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); - $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"]; + $parameters = array("exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"); $first_time = ($lastid == ""); - if ($lastid != "") { + if ($lastid <> "") $parameters["since_id"] = $lastid; - } $items = $connection->get('statuses/user_timeline', $parameters); - if (!is_array($items)) { + if (!is_array($items)) return; - } $posts = array_reverse($items); if (count($posts)) { - foreach ($posts as $post) { - if ($post->id_str > $lastid) { - $lastid = $post->id_str; - PConfig::set($uid, 'twitter', 'lastid', $lastid); - } + foreach ($posts as $post) { + if ($post->id_str > $lastid) { + $lastid = $post->id_str; + set_pconfig($uid, 'twitter', 'lastid', $lastid); + } - if ($first_time) { - continue; - } + if ($first_time) + continue; - if (!stristr($post->source, $application_name)) { - $_SESSION["authenticated"] = true; - $_SESSION["uid"] = $uid; + if (!stristr($post->source, $application_name)) { - $_REQUEST = twitter_do_mirrorpost($a, $uid, $post); + $_SESSION["authenticated"] = true; + $_SESSION["uid"] = $uid; - logger('twitter: posting for user ' . $uid); + $_REQUEST = twitter_do_mirrorpost($a, $uid, $post); - item_post($a); - } + logger('twitter: posting for user '.$uid); + + item_post($a); } + } } - PConfig::set($uid, 'twitter', 'lastid', $lastid); + set_pconfig($uid, 'twitter', 'lastid', $lastid); } -function twitter_queue_hook(App $a, &$b) -{ +function twitter_queue_hook(&$a,&$b) { + $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'", dbesc(NETWORK_TWITTER) - ); - if (!count($qi)) { + ); + if(! count($qi)) return; - } - require_once 'include/queue_fn.php'; + require_once('include/queue_fn.php'); - foreach ($qi as $x) { - if ($x['network'] !== NETWORK_TWITTER) { + foreach($qi as $x) { + if($x['network'] !== NETWORK_TWITTER) continue; - } logger('twitter_queue: run'); @@ -937,45 +875,43 @@ function twitter_queue_hook(App $a, &$b) WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1", intval($x['cid']) ); - if (!count($r)) { + if(! count($r)) continue; - } $user = $r[0]; - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($user['uid'], 'twitter', 'oauthtoken'); - $osecret = PConfig::get($user['uid'], 'twitter', 'oauthsecret'); + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($user['uid'], 'twitter', 'oauthtoken'); + $osecret = get_pconfig($user['uid'], 'twitter', 'oauthsecret'); $success = false; if ($ckey && $csecret && $otoken && $osecret) { + logger('twitter_queue: able to post'); $z = unserialize($x['content']); - require_once "addon/twitter/codebird.php"; + require_once("addon/twitter/codebird.php"); $cb = \Codebird\Codebird::getInstance(); $cb->setConsumerKey($ckey, $csecret); $cb->setToken($otoken, $osecret); - if ($z['url'] == "statuses/update") { + if ($z['url'] == "statuses/update") $result = $cb->statuses_update($z['post']); - } logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG); - if ($result->errors) { + if ($result->errors) logger('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"'); - } else { + else { $success = true; remove_queue_item($x['id']); } - } else { - logger("twitter_queue: Error getting tokens for user " . $user['uid']); - } + } else + logger("twitter_queue: Error getting tokens for user ".$user['uid']); if (!$success) { logger('twitter_queue: delayed'); @@ -984,45 +920,43 @@ function twitter_queue_hook(App $a, &$b) } } -function twitter_fix_avatar($avatar) -{ +function twitter_fix_avatar($avatar) { + require_once("include/Photo.php"); + $new_avatar = str_replace("_normal.", ".", $avatar); - $info = Image::getInfoFromURL($new_avatar); - if (!$info) { + $info = get_photo_info($new_avatar); + if (!$info) $new_avatar = $avatar; - } return $new_avatar; } -function twitter_fetch_contact($uid, $contact, $create_user) -{ - if ($contact->id_str == "") { - return -1; - } +function twitter_fetch_contact($uid, $contact, $create_user) { + + if ($contact->id_str == "") + return(-1); $avatar = twitter_fix_avatar($contact->profile_image_url_https); - GContact::update(["url" => "https://twitter.com/" . $contact->screen_name, - "network" => NETWORK_TWITTER, "photo" => $avatar, "hide" => true, - "name" => $contact->name, "nick" => $contact->screen_name, - "location" => $contact->location, "about" => $contact->description, - "addr" => $contact->screen_name . "@twitter.com", "generation" => 2]); + update_gcontact(array("url" => "https://twitter.com/".$contact->screen_name, + "network" => NETWORK_TWITTER, "photo" => $avatar, "hide" => true, + "name" => $contact->name, "nick" => $contact->screen_name, + "location" => $contact->location, "about" => $contact->description, + "addr" => $contact->screen_name."@twitter.com", "generation" => 2)); $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", - intval($uid), dbesc("twitter::" . $contact->id_str)); + intval($uid), dbesc("twitter::".$contact->id_str)); - if (!count($r) && !$create_user) { - return 0; - } + if(!count($r) && !$create_user) + return(0); if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) { - logger("twitter_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG); - return -1; + logger("twitter_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG); + return(-1); } - if (!count($r)) { + if(!count($r)) { // create contact record q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`, `name`, `nick`, `photo`, `network`, `rel`, `priority`, @@ -1030,12 +964,12 @@ function twitter_fetch_contact($uid, $contact, $create_user) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)", intval($uid), dbesc(datetime_convert()), - dbesc("https://twitter.com/" . $contact->screen_name), - dbesc(normalise_link("https://twitter.com/" . $contact->screen_name)), + dbesc("https://twitter.com/".$contact->screen_name), + dbesc(normalise_link("https://twitter.com/".$contact->screen_name)), dbesc($contact->screen_name."@twitter.com"), - dbesc("twitter::" . $contact->id_str), + dbesc("twitter::".$contact->id_str), dbesc(''), - dbesc("twitter::" . $contact->id_str), + dbesc("twitter::".$contact->id_str), dbesc($contact->name), dbesc($contact->screen_name), dbesc($avatar), @@ -1050,17 +984,25 @@ function twitter_fetch_contact($uid, $contact, $create_user) $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1", dbesc("twitter::".$contact->id_str), intval($uid) + ); + + if(! count($r)) + return(false); + + $contact_id = $r[0]['id']; + + $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1", + intval($uid) ); - if (!count($r)) { - return false; + if($g && intval($g[0]['def_gid'])) { + require_once('include/group.php'); + group_add_member($uid,'',$contact_id,$g[0]['def_gid']); } - $contact_id = $r[0]['id']; + require_once("Photo.php"); - Group::addMember(User::getDefaultGroup($uid), $contact_id); - - $photos = Photo::importProfilePhoto($avatar, $uid, $contact_id, true); + $photos = import_profile_photo($avatar, $uid, $contact_id, true); if ($photos) { q("UPDATE `contact` SET `photo` = '%s', @@ -1081,14 +1023,19 @@ function twitter_fetch_contact($uid, $contact, $create_user) } } else { // update profile photos once every two weeks as we have no notification of when they change. + //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false); - $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours')); + $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours')); // check that we have all the photos, this has been known to fail on occasion - if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) { - logger("twitter_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG); - $photos = Photo::importProfilePhoto($avatar, $uid, $r[0]['id'], true); + if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) { + + logger("twitter_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG); + + require_once("Photo.php"); + + $photos = import_profile_photo($avatar, $uid, $r[0]['id'], true); if ($photos) { q("UPDATE `contact` SET `photo` = '%s', @@ -1124,17 +1071,16 @@ function twitter_fetch_contact($uid, $contact, $create_user) } } - return $r[0]["id"]; + return($r[0]["id"]); } -function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") -{ - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); - $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); +function twitter_fetchuser($a, $uid, $screen_name = "", $user_id = "") { + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($uid, 'twitter', 'oauthtoken'); + $osecret = get_pconfig($uid, 'twitter', 'oauthsecret'); - require_once "addon/twitter/codebird.php"; + require_once("addon/twitter/codebird.php"); $cb = \Codebird\Codebird::getInstance(); $cb->setConsumerKey($ckey, $csecret); @@ -1143,37 +1089,33 @@ function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); - if (count($r)) { + if(count($r)) { $self = $r[0]; - } else { + } else return; - } - $parameters = []; + $parameters = array(); - if ($screen_name != "") { + if ($screen_name != "") $parameters["screen_name"] = $screen_name; - } - if ($user_id != "") { + if ($user_id != "") $parameters["user_id"] = $user_id; - } // Fetching user data $user = $cb->users_show($parameters); - if (!is_object($user)) { + if (!is_object($user)) return; - } $contact_id = twitter_fetch_contact($uid, $user, true); return $contact_id; } -function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $picture) -{ - require_once "include/network.php"; +function twitter_expand_entities($a, $body, $item, $no_tags = false, $picture) { + require_once("include/oembed.php"); + require_once("include/network.php"); $tags = ""; @@ -1186,21 +1128,21 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur $footer = ""; foreach ($item->entities->urls AS $url) { + $plain = str_replace($url->url, '', $plain); if ($url->url && $url->expanded_url && $url->display_url) { + $expanded_url = original_url($url->expanded_url); - $oembed_data = OEmbed::fetchURL($expanded_url); + $oembed_data = oembed_fetch_url($expanded_url); // Quickfix: Workaround for URL with "[" and "]" in it - if (strpos($expanded_url, "[") || strpos($expanded_url, "]")) { + if (strpos($expanded_url, "[") || strpos($expanded_url, "]")) $expanded_url = $url->url; - } - if ($type == "") { + if ($type == "") $type = $oembed_data->type; - } if ($oembed_data->type == "video") { //$body = str_replace($url->url, @@ -1208,16 +1150,20 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur //$dontincludemedia = true; $type = $oembed_data->type; $footerurl = $expanded_url; - $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]"; + $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]"; $body = str_replace($url->url, $footerlink, $body); - //} elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) { + //} elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) { } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) { - $body = str_replace($url->url, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body); + $body = str_replace($url->url, + "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", + $body); //$dontincludemedia = true; - } elseif ($oembed_data->type != "link") { - $body = str_replace($url->url, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body); - } else { + } elseif ($oembed_data->type != "link") + $body = str_replace($url->url, + "[url=".$expanded_url."]".$expanded_url."[/url]", + $body); + else { $img_str = fetch_url($expanded_url, true, $redirects, 4); $tempfile = tempnam(get_temppath(), "cache"); @@ -1227,12 +1173,12 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur if (substr($mime, 0, 6) == "image/") { $type = "photo"; - $body = str_replace($url->url, "[img]" . $expanded_url . "[/img]", $body); + $body = str_replace($url->url, "[img]".$expanded_url."[/img]", $body); //$dontincludemedia = true; } else { $type = $oembed_data->type; $footerurl = $expanded_url; - $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]"; + $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]"; $body = str_replace($url->url, $footerlink, $body); } @@ -1240,86 +1186,81 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur } } - if ($footerurl != "") { + if ($footerurl != "") $footer = add_page_info($footerurl, false, $picture); - } if (($footerlink != "") && (trim($footer) != "")) { $removedlink = trim(str_replace($footerlink, "", $body)); - if (($removedlink == "") || strstr($body, $removedlink)) { + if (($removedlink == "") || strstr($body, $removedlink)) $body = $removedlink; - } $body .= $footer; } - if (($footer == "") && ($picture != "")) { - $body .= "\n\n[img]" . $picture . "[/img]\n"; - } elseif (($footer == "") && ($picture == "")) { + if (($footer == "") && ($picture != "")) + $body .= "\n\n[img]".$picture."[/img]\n"; + elseif (($footer == "") && ($picture == "")) $body = add_page_info_to_body($body); - } - if ($no_tags) { - return ["body" => $body, "tags" => "", "plain" => $plain]; - } + if ($no_tags) + return array("body" => $body, "tags" => "", "plain" => $plain); - $tags_arr = []; + $tags_arr = array(); foreach ($item->entities->hashtags AS $hashtag) { - $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]"; - $tags_arr["#" . $hashtag->text] = $url; - $body = str_replace("#" . $hashtag->text, $url, $body); + $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag->text)."]".$hashtag->text."[/url]"; + $tags_arr["#".$hashtag->text] = $url; + $body = str_replace("#".$hashtag->text, $url, $body); } foreach ($item->entities->user_mentions AS $mention) { - $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]"; - $tags_arr["@" . $mention->screen_name] = $url; - $body = str_replace("@" . $mention->screen_name, $url, $body); + $url = "@[url=https://twitter.com/".rawurlencode($mention->screen_name)."]".$mention->screen_name."[/url]"; + $tags_arr["@".$mention->screen_name] = $url; + $body = str_replace("@".$mention->screen_name, $url, $body); } // it seems as if the entities aren't always covering all mentions. So the rest will be checked here $tags = get_tags($body); - if (count($tags)) { - foreach ($tags as $tag) { - if (strstr(trim($tag), " ")) { + if(count($tags)) { + foreach($tags as $tag) { + if (strstr(trim($tag), " ")) continue; - } - if (strpos($tag, '#') === 0) { - if (strpos($tag, '[url=')) { + if(strpos($tag,'#') === 0) { + if(strpos($tag,'[url=')) continue; - } // don't link tags that are already embedded in links - if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) { + + if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body)) continue; - } - if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) { + if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body)) continue; - } - $basetag = str_replace('_', ' ', substr($tag, 1)); - $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]'; - $body = str_replace($tag, $url, $body); - $tags_arr["#" . $basetag] = $url; - } elseif (strpos($tag, '@') === 0) { - if (strpos($tag, '[url=')) { + $basetag = str_replace('_',' ',substr($tag,1)); + $url = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($basetag).']'.$basetag.'[/url]'; + $body = str_replace($tag,$url,$body); + $tags_arr["#".$basetag] = $url; + continue; + } elseif(strpos($tag,'@') === 0) { + if(strpos($tag,'[url=')) continue; - } - $basetag = substr($tag, 1); - $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]'; - $body = str_replace($tag, $url, $body); - $tags_arr["@" . $basetag] = $url; + $basetag = substr($tag,1); + $url = '@[url=https://twitter.com/'.rawurlencode($basetag).']'.$basetag.'[/url]'; + $body = str_replace($tag,$url,$body); + $tags_arr["@".$basetag] = $url; } } } + $tags = implode($tags_arr, ","); + } - return ["body" => $body, "tags" => $tags, "plain" => $plain]; + return array("body" => $body, "tags" => $tags, "plain" => $plain); } /** @@ -1330,8 +1271,8 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur * * @return $picture string Returns a a single picture string if it isn't a media post */ -function twitter_media_entities($post, &$postarray) -{ +function twitter_media_entities($post, &$postarray) { + // There are no media entities? So we quit. if (!is_array($post->extended_entities->media)) { return ""; @@ -1341,7 +1282,7 @@ function twitter_media_entities($post, &$postarray) // We only do this when there is exactly one media. if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) { $picture = ""; - foreach ($post->extended_entities->media AS $medium) { + foreach($post->extended_entities->media AS $medium) { if (isset($medium->media_url_https)) { $picture = $medium->media_url_https; $postarray['body'] = str_replace($medium->url, "", $postarray['body']); @@ -1351,23 +1292,23 @@ function twitter_media_entities($post, &$postarray) } // This is a pure media post, first search for all media urls - $media = []; - foreach ($post->extended_entities->media AS $medium) { - switch ($medium->type) { + $media = array(); + foreach($post->extended_entities->media AS $medium) { + switch($medium->type) { case 'photo': - $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]"; + $media[$medium->url] .= "\n[img]".$medium->media_url_https."[/img]"; $postarray['object-type'] = ACTIVITY_OBJ_IMAGE; break; case 'video': case 'animated_gif': - $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]"; + $media[$medium->url] .= "\n[img]".$medium->media_url_https."[/img]"; $postarray['object-type'] = ACTIVITY_OBJ_VIDEO; if (is_array($medium->video_info->variants)) { $bitrate = 0; // We take the video with the highest bitrate foreach ($medium->video_info->variants AS $variant) { if (($variant->content_type == "video/mp4") && ($variant->bitrate >= $bitrate)) { - $media[$medium->url] = "\n[video]" . $variant->url . "[/video]"; + $media[$medium->url] = "\n[video]".$variant->url."[/video]"; $bitrate = $variant->bitrate; } } @@ -1381,41 +1322,42 @@ function twitter_media_entities($post, &$postarray) // Now we replace the media urls. foreach ($media AS $key => $value) { - $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']); + $postarray['body'] = str_replace($key, "\n".$value."\n", $postarray['body']); } return ""; } -function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote) -{ - $postarray = []; +function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote) { + + $postarray = array(); $postarray['network'] = NETWORK_TWITTER; $postarray['gravity'] = 0; $postarray['uid'] = $uid; $postarray['wall'] = 0; - $postarray['uri'] = "twitter::" . $post->id_str; + $postarray['uri'] = "twitter::".$post->id_str; $postarray['object'] = json_encode($post); // Don't import our own comments $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", dbesc($postarray['uri']), intval($uid) - ); + ); if (count($r)) { - logger("Item with extid " . $postarray['uri'] . " found.", LOGGER_DEBUG); - return []; + logger("Item with extid ".$postarray['uri']." found.", LOGGER_DEBUG); + return(array()); } $contactid = 0; if ($post->in_reply_to_status_id_str != "") { - $parent = "twitter::" . $post->in_reply_to_status_id_str; + + $parent = "twitter::".$post->in_reply_to_status_id_str; $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent), intval($uid) - ); + ); if (count($r)) { $postarray['thr-parent'] = $r[0]["uri"]; $postarray['parent-uri'] = $r[0]["parent-uri"]; @@ -1425,7 +1367,7 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", dbesc($parent), intval($uid) - ); + ); if (count($r)) { $postarray['thr-parent'] = $r[0]['uri']; $postarray['parent-uri'] = $r[0]['parent-uri']; @@ -1439,21 +1381,21 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis } // Is it me? - $own_id = PConfig::get($uid, 'twitter', 'own_id'); + $own_id = get_pconfig($uid, 'twitter', 'own_id'); if ($post->user->id_str == $own_id) { $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); - if (count($r)) { + if(count($r)) { $contactid = $r[0]["id"]; - $postarray['owner-name'] = $r[0]["name"]; - $postarray['owner-link'] = $r[0]["url"]; - $postarray['owner-avatar'] = $r[0]["photo"]; + $postarray['owner-name'] = $r[0]["name"]; + $postarray['owner-link'] = $r[0]["url"]; + $postarray['owner-avatar'] = $r[0]["photo"]; } else { - logger("No self contact for user " . $uid, LOGGER_DEBUG); - return []; + logger("No self contact for user ".$uid, LOGGER_DEBUG); + return(array()); } } // Don't create accounts of people who just comment something @@ -1467,15 +1409,15 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $contactid = twitter_fetch_contact($uid, $post->user, $create_user); $postarray['owner-name'] = $post->user->name; - $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name; + $postarray['owner-link'] = "https://twitter.com/".$post->user->screen_name; $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https); } - if (($contactid == 0) && !$only_existing_contact) { + if(($contactid == 0) && !$only_existing_contact) { $contactid = $self['id']; } elseif ($contactid <= 0) { logger("Contact ID is zero or less than zero.", LOGGER_DEBUG); - return []; + return(array()); } $postarray['contact-id'] = $contactid; @@ -1484,7 +1426,7 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $postarray['author-name'] = $postarray['owner-name']; $postarray['author-link'] = $postarray['owner-link']; $postarray['author-avatar'] = $postarray['owner-avatar']; - $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str; + $postarray['plink'] = "https://twitter.com/".$post->user->screen_name."/status/".$post->id_str; $postarray['app'] = strip_tags($post->source); if ($post->user->protected) { @@ -1509,8 +1451,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $converted = twitter_expand_entities($a, $postarray['body'], $post, false, $picture); $postarray['body'] = $converted["body"]; $postarray['tag'] = $converted["tags"]; - $postarray['created'] = datetime_convert('UTC', 'UTC', $post->created_at); - $postarray['edited'] = datetime_convert('UTC', 'UTC', $post->created_at); + $postarray['created'] = datetime_convert('UTC','UTC',$post->created_at); + $postarray['edited'] = datetime_convert('UTC','UTC',$post->created_at); $statustext = $converted["plain"]; @@ -1521,10 +1463,10 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $postarray["location"] = $post->place->full_name; } if (is_array($post->geo->coordinates)) { - $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1]; + $postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1]; } if (is_array($post->coordinates->coordinates)) { - $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0]; + $postarray["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0]; } if (is_object($post->retweeted_status)) { $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote); @@ -1545,76 +1487,75 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $postarray['body'] = $statustext; - $postarray['body'] .= "\n" . share_header($quoted['author-name'], $quoted['author-link'], $quoted['author-avatar'], "", $quoted['created'], $quoted['plink']); + $postarray['body'] .= "\n".share_header($quoted['author-name'], $quoted['author-link'], $quoted['author-avatar'], "", + $quoted['created'], $quoted['plink']); - $postarray['body'] .= $quoted['body'] . '[/share]'; + $postarray['body'] .= $quoted['body'].'[/share]'; } - return $postarray; + return($postarray); } -function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray) -{ - /// TODO: this whole function doesn't seem to work. Needs complete check +function twitter_checknotification($a, $uid, $own_id, $top_item, $postarray) { + + // this whole function doesn't seem to work. Needs complete check + $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($uid) - ); + ); - if (!count($user)) { + if(!count($user)) return; - } // Is it me? - if (link_compare($user[0]["url"], $postarray['author-link'])) { + if (link_compare($user[0]["url"], $postarray['author-link'])) return; - } $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", intval($uid), dbesc("twitter::".$own_id) - ); + ); - if (!count($own_user)) { + if(!count($own_user)) return; - } // Is it me from twitter? - if (link_compare($own_user[0]["url"], $postarray['author-link'])) { + if (link_compare($own_user[0]["url"], $postarray['author-link'])) return; - } $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", dbesc($postarray['parent-uri']), intval($uid) - ); + ); + + if(count($myconv)) { - if (count($myconv)) { - foreach ($myconv as $conv) { + foreach($myconv as $conv) { // now if we find a match, it means we're in this conversation - if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) { + + if(!link_compare($conv['author-link'],$user[0]["url"]) && !link_compare($conv['author-link'],$own_user[0]["url"])) continue; - } - require_once 'include/enotify.php'; + require_once('include/enotify.php'); $conv_parent = $conv['parent']; - notification([ - 'type' => NOTIFY_COMMENT, + notification(array( + 'type' => NOTIFY_COMMENT, 'notify_flags' => $user[0]['notify-flags'], - 'language' => $user[0]['language'], - 'to_name' => $user[0]['username'], - 'to_email' => $user[0]['email'], - 'uid' => $user[0]['uid'], - 'item' => $postarray, - 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)), - 'source_name' => $postarray['author-name'], - 'source_link' => $postarray['author-link'], + 'language' => $user[0]['language'], + 'to_name' => $user[0]['username'], + 'to_email' => $user[0]['email'], + 'uid' => $user[0]['uid'], + 'item' => $postarray, + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)), + 'source_name' => $postarray['author-name'], + 'source_link' => $postarray['author-link'], 'source_photo' => $postarray['author-avatar'], - 'verb' => ACTIVITY_POST, - 'otype' => 'item', - 'parent' => $conv_parent, - ]); + 'verb' => ACTIVITY_POST, + 'otype' => 'item', + 'parent' => $conv_parent, + )); // only send one notification break; @@ -1622,35 +1563,33 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray) } } -function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_id) -{ - logger("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, LOGGER_DEBUG); +function twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id) { + logger("twitter_fetchparentposts: Fetching for user ".$uid." and post ".$post->id_str, LOGGER_DEBUG); - $posts = []; + $posts = array(); while ($post->in_reply_to_status_id_str != "") { - $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str]; + $parameters = array("trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str); $post = $connection->get('statuses/show', $parameters); if (!count($post)) { - logger("twitter_fetchparentposts: Can't fetch post " . $parameters->id, LOGGER_DEBUG); + logger("twitter_fetchparentposts: Can't fetch post ".$parameters->id, LOGGER_DEBUG); break; } $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc("twitter::".$post->id_str), intval($uid) - ); + ); - if (count($r)) { + if (count($r)) break; - } $posts[] = $post; } - logger("twitter_fetchparentposts: Fetching " . count($posts) . " parents", LOGGER_DEBUG); + logger("twitter_fetchparentposts: Fetching ".count($posts)." parents", LOGGER_DEBUG); $posts = array_reverse($posts); @@ -1664,36 +1603,33 @@ function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_ $item = item_store($postarray); $postarray["id"] = $item; - logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item); + logger('twitter_fetchparentpost: User '.$self["nick"].' posted parent timeline item '.$item); - if ($item && !function_exists("check_item_notification")) { + if ($item && !function_exists("check_item_notification")) twitter_checknotification($a, $uid, $own_id, $item, $postarray); - } } } } -function twitter_fetchhometimeline(App $a, $uid) -{ - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); - $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); - $create_user = PConfig::get($uid, 'twitter', 'create_user'); - $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts'); +function twitter_fetchhometimeline($a, $uid) { + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($uid, 'twitter', 'oauthtoken'); + $osecret = get_pconfig($uid, 'twitter', 'oauthsecret'); + $create_user = get_pconfig($uid, 'twitter', 'create_user'); + $mirror_posts = get_pconfig($uid, 'twitter', 'mirror_posts'); - logger("twitter_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG); - $application_name = Config::get('twitter', 'application_name'); + $application_name = get_config('twitter', 'application_name'); - if ($application_name == "") { + if ($application_name == "") $application_name = $a->get_hostname(); - } - require_once 'library/twitteroauth.php'; - require_once 'include/items.php'; + require_once('library/twitteroauth.php'); + require_once('include/items.php'); - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); $own_contact = twitter_fetch_own_contact($a, $uid); @@ -1701,62 +1637,62 @@ function twitter_fetchhometimeline(App $a, $uid) intval($own_contact), intval($uid)); - if (count($r)) { + if(count($r)) { $own_id = $r[0]["nick"]; } else { - logger("twitter_fetchhometimeline: Own twitter contact not found for user " . $uid, LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Own twitter contact not found for user ".$uid, LOGGER_DEBUG); return; } $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); - if (count($r)) { + if(count($r)) { $self = $r[0]; } else { - logger("twitter_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG); return; } $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1", intval($uid)); - if (!count($u)) { - logger("twitter_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG); + if(!count($u)) { + logger("twitter_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG); return; } - $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"]; + $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"); //$parameters["count"] = 200; + + // Fetching timeline - $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid'); + $lastid = get_pconfig($uid, 'twitter', 'lasthometimelineid'); $first_time = ($lastid == ""); - if ($lastid != "") { + if ($lastid <> "") $parameters["since_id"] = $lastid; - } $items = $connection->get('statuses/home_timeline', $parameters); if (!is_array($items)) { - logger("twitter_fetchhometimeline: Error fetching home timeline: " . print_r($items, true), LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Error fetching home timeline: ".print_r($items, true), LOGGER_DEBUG); return; } $posts = array_reverse($items); - logger("twitter_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG); if (count($posts)) { foreach ($posts as $post) { if ($post->id_str > $lastid) { $lastid = $post->id_str; - PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid); + set_pconfig($uid, 'twitter', 'lasthometimelineid', $lastid); } - if ($first_time) { + if ($first_time) continue; - } if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) { logger("twitter_fetchhometimeline: Skip previously sended post", LOGGER_DEBUG); @@ -1768,80 +1704,71 @@ function twitter_fetchhometimeline(App $a, $uid) continue; } - if ($post->in_reply_to_status_id_str != "") { + if ($post->in_reply_to_status_id_str != "") twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id); - } $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false); - if (trim($postarray['body']) == "") { + if (trim($postarray['body']) == "") continue; - } $item = item_store($postarray); $postarray["id"] = $item; - logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item); + logger('twitter_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item); - if ($item && !function_exists("check_item_notification")) { + if ($item && !function_exists("check_item_notification")) twitter_checknotification($a, $uid, $own_id, $item, $postarray); - } + } } - PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid); + set_pconfig($uid, 'twitter', 'lasthometimelineid', $lastid); // Fetching mentions - $lastid = PConfig::get($uid, 'twitter', 'lastmentionid'); + $lastid = get_pconfig($uid, 'twitter', 'lastmentionid'); $first_time = ($lastid == ""); - if ($lastid != "") { + if ($lastid <> "") $parameters["since_id"] = $lastid; - } $items = $connection->get('statuses/mentions_timeline', $parameters); if (!is_array($items)) { - logger("twitter_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG); return; } $posts = array_reverse($items); - logger("twitter_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG); + logger("twitter_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG); if (count($posts)) { foreach ($posts as $post) { - if ($post->id_str > $lastid) { + if ($post->id_str > $lastid) $lastid = $post->id_str; - } - if ($first_time) { + if ($first_time) continue; - } - if ($post->in_reply_to_status_id_str != "") { + if ($post->in_reply_to_status_id_str != "") twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id); - } $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false); - if (trim($postarray['body']) == "") { + if (trim($postarray['body']) == "") continue; - } $item = item_store($postarray); $postarray["id"] = $item; - if ($item && function_exists("check_item_notification")) { + if ($item && function_exists("check_item_notification")) check_item_notification($item, $uid, NOTIFY_TAGSELF); - } - if (!isset($postarray["parent"]) || ($postarray["parent"] == 0)) { + if (!isset($postarray["parent"]) || ($postarray["parent"] == 0)) $postarray["parent"] = $item; - } - logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item); + logger('twitter_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item); if ($item == 0) { $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", @@ -1856,8 +1783,8 @@ function twitter_fetchhometimeline(App $a, $uid) $parent_id = $postarray['parent']; if (($item != 0) && !function_exists("check_item_notification")) { - require_once 'include/enotify.php'; - notification([ + require_once('include/enotify.php'); + notification(array( 'type' => NOTIFY_TAGSELF, 'notify_flags' => $u[0]['notify-flags'], 'language' => $u[0]['language'], @@ -1865,107 +1792,100 @@ function twitter_fetchhometimeline(App $a, $uid) 'to_email' => $u[0]['email'], 'uid' => $u[0]['uid'], 'item' => $postarray, - 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)), + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), 'source_name' => $postarray['author-name'], 'source_link' => $postarray['author-link'], 'source_photo' => $postarray['author-avatar'], 'verb' => ACTIVITY_TAG, 'otype' => 'item', 'parent' => $parent_id - ]); + )); } } } - PConfig::set($uid, 'twitter', 'lastmentionid', $lastid); + set_pconfig($uid, 'twitter', 'lastmentionid', $lastid); } -function twitter_fetch_own_contact(App $a, $uid) -{ - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); - $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); +function twitter_fetch_own_contact($a, $uid) { + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($uid, 'twitter', 'oauthtoken'); + $osecret = get_pconfig($uid, 'twitter', 'oauthsecret'); - $own_id = PConfig::get($uid, 'twitter', 'own_id'); + $own_id = get_pconfig($uid, 'twitter', 'own_id'); $contact_id = 0; if ($own_id == "") { - require_once 'library/twitteroauth.php'; + require_once('library/twitteroauth.php'); - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); // Fetching user data $user = $connection->get('account/verify_credentials'); - PConfig::set($uid, 'twitter', 'own_id', $user->id_str); + set_pconfig($uid, 'twitter', 'own_id', $user->id_str); $contact_id = twitter_fetch_contact($uid, $user, true); + } else { $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", - intval($uid), - dbesc("twitter::" . $own_id)); - if (count($r)) { + intval($uid), dbesc("twitter::".$own_id)); + if(count($r)) $contact_id = $r[0]["id"]; - } else { - PConfig::delete($uid, 'twitter', 'own_id'); - } + else + del_pconfig($uid, 'twitter', 'own_id'); + } - return $contact_id; + return($contact_id); } -function twitter_is_retweet(App $a, $uid, $body) -{ +function twitter_is_retweet($a, $uid, $body) { $body = trim($body); // Skip if it isn't a pure repeated messages // Does it start with a share? - if (strpos($body, "[share") > 0) { - return false; - } + if (strpos($body, "[share") > 0) + return(false); // Does it end with a share? - if (strlen($body) > (strrpos($body, "[/share]") + 8)) { - return false; - } + if (strlen($body) > (strrpos($body, "[/share]") + 8)) + return(false); - $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body); + $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body); // Skip if there is no shared message in there - if ($body == $attributes) { - return false; - } + if ($body == $attributes) + return(false); $link = ""; preg_match("/link='(.*?)'/ism", $attributes, $matches); - if ($matches[1] != "") { + if ($matches[1] != "") $link = $matches[1]; - } preg_match('/link="(.*?)"/ism', $attributes, $matches); - if ($matches[1] != "") { + if ($matches[1] != "") $link = $matches[1]; - } $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link); - if ($id == $link) { - return false; - } + if ($id == $link) + return(false); - logger('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG); + logger('twitter_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG); - $ckey = Config::get('twitter', 'consumerkey'); - $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); - $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); + $ckey = get_config('twitter', 'consumerkey'); + $csecret = get_config('twitter', 'consumersecret'); + $otoken = get_pconfig($uid, 'twitter', 'oauthtoken'); + $osecret = get_pconfig($uid, 'twitter', 'oauthsecret'); - require_once 'library/twitteroauth.php'; - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + require_once('library/twitteroauth.php'); + $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret); - $result = $connection->post('statuses/retweet/' . $id); + $result = $connection->post('statuses/retweet/'.$id); - logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG); + logger('twitter_is_retweet: result '.print_r($result, true), LOGGER_DEBUG); - return !isset($result->errors); + return(!isset($result->errors)); } +?> diff --git a/uhremotestorage/lang/C/messages.po b/uhremotestorage/lang/C/messages.po new file mode 100644 index 00000000..c4b824be --- /dev/null +++ b/uhremotestorage/lang/C/messages.po @@ -0,0 +1,42 @@ +# ADDON uhremotestorage +# Copyright (C) +# This file is distributed under the same license as the Friendica uhremotestorage addon package. +# +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: \n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2013-02-27 05:01-0500\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#: uhremotestorage.php:84 +#, php-format +msgid "" +"Allow to use your friendica id (%s) to connecto to external unhosted-enabled " +"storage (like ownCloud). See RemoteStorage WebFinger" +msgstr "" + +#: uhremotestorage.php:85 +msgid "Template URL (with {category})" +msgstr "" + +#: uhremotestorage.php:86 +msgid "OAuth end-point" +msgstr "" + +#: uhremotestorage.php:87 +msgid "Api" +msgstr "" + +#: uhremotestorage.php:89 +msgid "Submit" +msgstr "" diff --git a/uhremotestorage/lang/ca/strings.php b/uhremotestorage/lang/ca/strings.php new file mode 100644 index 00000000..2cfd6535 --- /dev/null +++ b/uhremotestorage/lang/ca/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permetre l'ús del seu ID de friendica (%s) per Connectar a l'emmagatzematge extern (com ownCloud). Veure WebFinger RemoteStorage "; +$a->strings["Template URL (with {category})"] = "Plantilles de URL (amb {categoria})"; +$a->strings["OAuth end-point"] = "OAuth end-point"; +$a->strings["Api"] = "Api"; +$a->strings["Submit"] = "Enviar"; diff --git a/uhremotestorage/lang/cs/messages.po b/uhremotestorage/lang/cs/messages.po new file mode 100644 index 00000000..599ff2bb --- /dev/null +++ b/uhremotestorage/lang/cs/messages.po @@ -0,0 +1,45 @@ +# ADDON uhremotestorage +# Copyright (C) +# This file is distributed under the same license as the Friendica uhremotestorage addon package. +# +# +# Translators: +# Michal Šupler , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2014-07-07 19:28+0000\n" +"Last-Translator: Michal Šupler \n" +"Language-Team: Czech (http://www.transifex.com/projects/p/friendica/language/cs/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: cs\n" +"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" + +#: uhremotestorage.php:84 +#, php-format +msgid "" +"Allow to use your friendica id (%s) to connecto to external unhosted-enabled" +" storage (like ownCloud). See RemoteStorage" +" WebFinger" +msgstr "Umožnit využití friendica id (%s) k napojení na externí úložiště (unhosted-enabled) (jako ownCloud). Více informací na RemoteStorage WebFinger" + +#: uhremotestorage.php:85 +msgid "Template URL (with {category})" +msgstr "Dočasná URL adresa (s {category})" + +#: uhremotestorage.php:86 +msgid "OAuth end-point" +msgstr "OAuth end-point" + +#: uhremotestorage.php:87 +msgid "Api" +msgstr "Api" + +#: uhremotestorage.php:89 +msgid "Save Settings" +msgstr "Uložit Nastavení" diff --git a/uhremotestorage/lang/cs/strings.php b/uhremotestorage/lang/cs/strings.php new file mode 100644 index 00000000..0c31cc4b --- /dev/null +++ b/uhremotestorage/lang/cs/strings.php @@ -0,0 +1,12 @@ +=2 && $n<=4) ? 1 : 2;; +}} +; +$a->strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Umožnit využití friendica id (%s) k napojení na externí úložiště (unhosted-enabled) (jako ownCloud). Více informací na RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "Dočasná URL adresa (s {category})"; +$a->strings["OAuth end-point"] = "OAuth end-point"; +$a->strings["Api"] = "Api"; +$a->strings["Save Settings"] = "Uložit Nastavení"; diff --git a/uhremotestorage/lang/de/messages.po b/uhremotestorage/lang/de/messages.po new file mode 100644 index 00000000..7c520ac5 --- /dev/null +++ b/uhremotestorage/lang/de/messages.po @@ -0,0 +1,45 @@ +# ADDON uhremotestorage +# Copyright (C) +# This file is distributed under the same license as the Friendica uhremotestorage addon package. +# +# +# Translators: +# bavatar , 2014 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2014-10-14 05:48+0000\n" +"Last-Translator: bavatar \n" +"Language-Team: German (http://www.transifex.com/projects/p/friendica/language/de/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: de\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: uhremotestorage.php:84 +#, php-format +msgid "" +"Allow to use your friendica id (%s) to connecto to external unhosted-enabled" +" storage (like ownCloud). See RemoteStorage" +" WebFinger" +msgstr "Ermöglicht es deine friendica id (%s) mit externen unhosted-fähigen Speichern (z.B. ownCloud) zu verbinden. Siehe RemoteStorage WebFinger" + +#: uhremotestorage.php:85 +msgid "Template URL (with {category})" +msgstr "Vorlagen URL (mit {Kategorie})" + +#: uhremotestorage.php:86 +msgid "OAuth end-point" +msgstr "OAuth end-point" + +#: uhremotestorage.php:87 +msgid "Api" +msgstr "Api" + +#: uhremotestorage.php:89 +msgid "Save Settings" +msgstr "Einstellungen speichern" diff --git a/uhremotestorage/lang/de/strings.php b/uhremotestorage/lang/de/strings.php new file mode 100644 index 00000000..a6b9bf0a --- /dev/null +++ b/uhremotestorage/lang/de/strings.php @@ -0,0 +1,12 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Ermöglicht es deine friendica id (%s) mit externen unhosted-fähigen Speichern (z.B. ownCloud) zu verbinden. Siehe RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "Vorlagen URL (mit {Kategorie})"; +$a->strings["OAuth end-point"] = "OAuth end-point"; +$a->strings["Api"] = "Api"; +$a->strings["Save Settings"] = "Einstellungen speichern"; diff --git a/uhremotestorage/lang/eo/strings.php b/uhremotestorage/lang/eo/strings.php new file mode 100644 index 00000000..94020c34 --- /dev/null +++ b/uhremotestorage/lang/eo/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permesi vian identecon ĉe Friendica (%s) por konekti al eksteraj konservejoj subtenata de unhosted (ekz. OwnCloud). Vidu RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "URL adreso de ŝablono (kun {category})"; +$a->strings["OAuth end-point"] = "OAuth finpunkto"; +$a->strings["Api"] = "Api"; +$a->strings["Submit"] = "Sendi"; diff --git a/uhremotestorage/lang/es/messages.po b/uhremotestorage/lang/es/messages.po new file mode 100644 index 00000000..9b3de008 --- /dev/null +++ b/uhremotestorage/lang/es/messages.po @@ -0,0 +1,45 @@ +# ADDON uhremotestorage +# Copyright (C) +# This file is distributed under the same license as the Friendica uhremotestorage addon package. +# +# +# Translators: +# Albert, 2016 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2016-11-19 11:35+0000\n" +"Last-Translator: Albert\n" +"Language-Team: Spanish (http://www.transifex.com/Friendica/friendica/language/es/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: es\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: uhremotestorage.php:84 +#, php-format +msgid "" +"Allow to use your friendica id (%s) to connecto to external unhosted-enabled" +" storage (like ownCloud). See RemoteStorage" +" WebFinger" +msgstr "Permite usar su ID de Friendica (%s) para conectar a un almacén habilitado externo sin hospedar (como ownCloud). Vea RemoteStorage WebFinger" + +#: uhremotestorage.php:85 +msgid "Template URL (with {category})" +msgstr "Plantilla de URL (con {categoría})" + +#: uhremotestorage.php:86 +msgid "OAuth end-point" +msgstr "Punto final de OAuth" + +#: uhremotestorage.php:87 +msgid "Api" +msgstr "API" + +#: uhremotestorage.php:89 +msgid "Save Settings" +msgstr "Guardar Ajustes" diff --git a/uhremotestorage/lang/es/strings.php b/uhremotestorage/lang/es/strings.php new file mode 100644 index 00000000..910a0562 --- /dev/null +++ b/uhremotestorage/lang/es/strings.php @@ -0,0 +1,12 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permite usar su ID de Friendica (%s) para conectar a un almacén habilitado externo sin hospedar (como ownCloud). Vea RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "Plantilla de URL (con {categoría})"; +$a->strings["OAuth end-point"] = "Punto final de OAuth"; +$a->strings["Api"] = "API"; +$a->strings["Save Settings"] = "Guardar Ajustes"; diff --git a/uhremotestorage/lang/fr/strings.php b/uhremotestorage/lang/fr/strings.php new file mode 100644 index 00000000..7bb4631b --- /dev/null +++ b/uhremotestorage/lang/fr/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permet l'utilisation de votre ID Friendica (%s) pour vous connecter à des sites compatibles \"unhosted\" (comme ownCloud). Voyez RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "Modèle d'URL (avec {catégorie})"; +$a->strings["OAuth end-point"] = "URL OAuth"; +$a->strings["Api"] = "Type d'API"; +$a->strings["Submit"] = "Envoyer"; diff --git a/uhremotestorage/lang/is/strings.php b/uhremotestorage/lang/is/strings.php new file mode 100644 index 00000000..83f80134 --- /dev/null +++ b/uhremotestorage/lang/is/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = ""; +$a->strings["Template URL (with {category})"] = ""; +$a->strings["OAuth end-point"] = ""; +$a->strings["Api"] = "Api"; +$a->strings["Submit"] = "Senda inn"; diff --git a/uhremotestorage/lang/it/messages.po b/uhremotestorage/lang/it/messages.po new file mode 100644 index 00000000..67fbc575 --- /dev/null +++ b/uhremotestorage/lang/it/messages.po @@ -0,0 +1,45 @@ +# ADDON uhremotestorage +# Copyright (C) +# This file is distributed under the same license as the Friendica uhremotestorage addon package. +# +# +# Translators: +# fabrixxm , 2015 +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2015-08-31 10:30+0000\n" +"Last-Translator: fabrixxm \n" +"Language-Team: Italian (http://www.transifex.com/Friendica/friendica/language/it/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: it\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: uhremotestorage.php:84 +#, php-format +msgid "" +"Allow to use your friendica id (%s) to connecto to external unhosted-enabled" +" storage (like ownCloud). See RemoteStorage" +" WebFinger" +msgstr "Permette di usare il tuo id friendica (%s) per collegarsi a storage esterni che supportano unhosted (come ownCloud). Vedi RemoteStorage WebFinger" + +#: uhremotestorage.php:85 +msgid "Template URL (with {category})" +msgstr "Template URL (con {category})" + +#: uhremotestorage.php:86 +msgid "OAuth end-point" +msgstr "OAuth end-point" + +#: uhremotestorage.php:87 +msgid "Api" +msgstr "Api" + +#: uhremotestorage.php:89 +msgid "Save Settings" +msgstr "Salva Impostazioni" diff --git a/uhremotestorage/lang/it/strings.php b/uhremotestorage/lang/it/strings.php new file mode 100644 index 00000000..9a344892 --- /dev/null +++ b/uhremotestorage/lang/it/strings.php @@ -0,0 +1,12 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permette di usare il tuo id friendica (%s) per collegarsi a storage esterni che supportano unhosted (come ownCloud). Vedi RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "Template URL (con {category})"; +$a->strings["OAuth end-point"] = "OAuth end-point"; +$a->strings["Api"] = "Api"; +$a->strings["Save Settings"] = "Salva Impostazioni"; diff --git a/uhremotestorage/lang/nb-no/strings.php b/uhremotestorage/lang/nb-no/strings.php new file mode 100644 index 00000000..7ffd9104 --- /dev/null +++ b/uhremotestorage/lang/nb-no/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Tillat å bruke din friendica id (%s) for å koble til ekstern unhosted-aktivert lagring (som ownCloud). Se RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = ""; +$a->strings["OAuth end-point"] = ""; +$a->strings["Api"] = ""; +$a->strings["Submit"] = "Lagre"; diff --git a/uhremotestorage/lang/pl/strings.php b/uhremotestorage/lang/pl/strings.php new file mode 100644 index 00000000..9f2ace13 --- /dev/null +++ b/uhremotestorage/lang/pl/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = ""; +$a->strings["Template URL (with {category})"] = ""; +$a->strings["OAuth end-point"] = ""; +$a->strings["Api"] = "Api"; +$a->strings["Submit"] = "Potwierdź"; diff --git a/uhremotestorage/lang/pt-br/strings.php b/uhremotestorage/lang/pt-br/strings.php new file mode 100644 index 00000000..082096d6 --- /dev/null +++ b/uhremotestorage/lang/pt-br/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permite o uso do id friendica (%s) para conectar ao armazenamento tipo unhosted externo (ex: ownCloud). Veja RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "URL do Template (com {category})"; +$a->strings["OAuth end-point"] = "OAuth terminal"; +$a->strings["Api"] = "Api"; +$a->strings["Submit"] = "Enviar"; diff --git a/uhremotestorage/lang/ro/messages.po b/uhremotestorage/lang/ro/messages.po new file mode 100644 index 00000000..7eeadf49 --- /dev/null +++ b/uhremotestorage/lang/ro/messages.po @@ -0,0 +1,44 @@ +# ADDON uhremotestorage +# Copyright (C) +# This file is distributed under the same license as the Friendica uhremotestorage addon package. +# +# +# Translators: +msgid "" +msgstr "" +"Project-Id-Version: friendica\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2014-06-23 14:45+0200\n" +"PO-Revision-Date: 2014-07-08 12:11+0000\n" +"Last-Translator: Arian - Cazare Muncitori \n" +"Language-Team: Romanian (Romania) (http://www.transifex.com/projects/p/friendica/language/ro_RO/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Language: ro_RO\n" +"Plural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1));\n" + +#: uhremotestorage.php:84 +#, php-format +msgid "" +"Allow to use your friendica id (%s) to connecto to external unhosted-enabled" +" storage (like ownCloud). See RemoteStorage" +" WebFinger" +msgstr "Permiteți utilizarea id-ului dvs. friendica (%s) să se conecteze cu medii de stocare externe de tip unhosted (precum ownCloud). Consultați RemoteStorage WebFinger" + +#: uhremotestorage.php:85 +msgid "Template URL (with {category})" +msgstr "URL șablon (cu {categorie})" + +#: uhremotestorage.php:86 +msgid "OAuth end-point" +msgstr "Punct-final OAuth " + +#: uhremotestorage.php:87 +msgid "Api" +msgstr "Api" + +#: uhremotestorage.php:89 +msgid "Save Settings" +msgstr "Salvare Configurări" diff --git a/uhremotestorage/lang/ro/strings.php b/uhremotestorage/lang/ro/strings.php new file mode 100644 index 00000000..7db8edad --- /dev/null +++ b/uhremotestorage/lang/ro/strings.php @@ -0,0 +1,12 @@ +19)||(($n%100==0)&&($n!=0)))?2:1));; +}} +; +$a->strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "Permiteți utilizarea id-ului dvs. friendica (%s) să se conecteze cu medii de stocare externe de tip unhosted (precum ownCloud). Consultați RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "URL șablon (cu {categorie})"; +$a->strings["OAuth end-point"] = "Punct-final OAuth "; +$a->strings["Api"] = "Api"; +$a->strings["Save Settings"] = "Salvare Configurări"; diff --git a/uhremotestorage/lang/ru/strings.php b/uhremotestorage/lang/ru/strings.php new file mode 100644 index 00000000..ebce59ab --- /dev/null +++ b/uhremotestorage/lang/ru/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = ""; +$a->strings["Template URL (with {category})"] = ""; +$a->strings["OAuth end-point"] = ""; +$a->strings["Api"] = "Api"; +$a->strings["Submit"] = "Подтвердить"; diff --git a/uhremotestorage/lang/sv/strings.php b/uhremotestorage/lang/sv/strings.php new file mode 100644 index 00000000..3ec569a7 --- /dev/null +++ b/uhremotestorage/lang/sv/strings.php @@ -0,0 +1,3 @@ +strings["Submit"] = "Spara"; diff --git a/uhremotestorage/lang/zh-cn/strings.php b/uhremotestorage/lang/zh-cn/strings.php new file mode 100644 index 00000000..7f7c2693 --- /dev/null +++ b/uhremotestorage/lang/zh-cn/strings.php @@ -0,0 +1,7 @@ +strings["Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger"] = "许用您的friendica用户名(%s)根对外没主办的贮藏(比如ownCloud)。看RemoteStorage WebFinger"; +$a->strings["Template URL (with {category})"] = "模板URL(根{category})"; +$a->strings["OAuth end-point"] = "OAuth 端点"; +$a->strings["Api"] = "API"; +$a->strings["Submit"] = "提交"; diff --git a/uhremotestorage/templates/settings.tpl b/uhremotestorage/templates/settings.tpl new file mode 100644 index 00000000..9a0a55f3 --- /dev/null +++ b/uhremotestorage/templates/settings.tpl @@ -0,0 +1,9 @@ +
    +

    {{$title}}

    +

    {{$desc}}

    + {{include file="field_input.tpl" field=$url}} + {{include file="field_input.tpl" field=$auth}} + {{include file="field_select.tpl" field=$api}} +
    + +
    diff --git a/uhremotestorage/uhremotestorage.php b/uhremotestorage/uhremotestorage.php new file mode 100644 index 00000000..76320f5c --- /dev/null +++ b/uhremotestorage/uhremotestorage.php @@ -0,0 +1,93 @@ + + * Status: Unsupported + */ + + function uhremotestorage_install() { + register_hook('personal_xrd', 'addon/uhremotestorage/uhremotestorage.php', 'uhremotestorage_personal_xrd'); + register_hook('plugin_settings', 'addon/uhremotestorage/uhremotestorage.php', 'uhremotestorage_settings'); + register_hook('plugin_settings_post', 'addon/uhremotestorage/uhremotestorage.php', 'uhremotestorage_settings_post'); + + logger("installed uhremotestorage"); +} + + +function uhremotestorage_uninstall() { + + unregister_hook('personal_xrd', 'addon/uhremotestorage/uhremotestorage.php', 'uhremotestorage_personal_xrd'); + unregister_hook('plugin_settings', 'addon/uhremotestorage/uhremotestorage.php', 'uhremotestorage_settings'); + unregister_hook('plugin_settings_post', 'addon/uhremotestorage/uhremotestorage.php', 'uhremotestorage_settings_post'); + + logger("removed uhremotestorage"); +} + +function uhremotestorage_personal_xrd($a, &$b){ + list($user, $host) = explode("@",$_GET['uri']); + $user = str_replace("acct:","",$user); + $r = q("SELECT uid FROM user WHERE nickname='%s'", dbesc($user)); + $uid = $r[0]['uid']; + + $url = get_pconfig($uid,'uhremotestorage','unhoestedurl'); + $auth = get_pconfig($uid,'uhremotestorage','unhoestedauth'); + $api = get_pconfig($uid,'uhremotestorage','unhoestedapi'); + + if ($url){ + $b['xml'] = str_replace( + '', + "\t".''."\n", + $b['xml'] + ); + } +} + +function uhremotestorage_settings_post($a, $post){ + if(! local_user()) + return; + set_pconfig(local_user(),'uhremotestorage','unhoestedurl',$_POST['unhoestedurl']); + set_pconfig(local_user(),'uhremotestorage','unhoestedauth',$_POST['unhoestedauth']); + set_pconfig(local_user(),'uhremotestorage','unhoestedapi',$_POST['unhoestedapi']); +} + +function uhremotestorage_settings($a, &$s){ + if(! local_user()) + return; + + $uid = $a->user['nickname'] ."@". $a->get_hostname(); + + $url = get_pconfig(local_user(),'uhremotestorage','unhoestedurl'); + $auth = get_pconfig(local_user(),'uhremotestorage','unhoestedauth'); + $api = get_pconfig(local_user(),'uhremotestorage','unhoestedapi'); + + + $arr_api = array( + 'WebDAV' => "WebDAV", + 'simple' => "simple WebDAV", + 'CouchDB' => "CouchDB", + ); + /* experimental apis */ + /* + $api = array_merge($api, array( + 'git' => "git", + 'tahoe-lafs' => 'tahoe-lafs', + 'camlistore' => 'camlistore', + 'AmazonS3' => 'AmazonS3', + 'GoogleDocs' => 'GoogleDocs', + 'Dropbox' => 'Dropbox', + ); + */ + $tpl = get_markup_template("settings.tpl", "addon/uhremotestorage/"); + $s .= replace_macros($tpl, array( + '$title' => 'Unhosted remote storage', + '$desc' => sprintf( t('Allow to use your friendica id (%s) to connecto to external unhosted-enabled storage (like ownCloud). See RemoteStorage WebFinger'), $uid ), + '$url' => array( 'unhoestedurl', t('Template URL (with {category})'), $url, 'If your are using ownCloud, your unhosted url will be like http://HOST/apps/remoteStorage/WebDAV.php/USER/remoteStorage/{category}'), + '$auth' => array( 'unhoestedauth', t('OAuth end-point'), $auth, 'If your are using ownCloud, your OAuth endpoint will be like http://HOST/apps/remoteStorage/auth.php/USER'), + '$api' => array( 'unhoestedapi', t('Api'), $api, 'If your are using ownCloud, your api will be WebDAV', $arr_api), + + '$submit' => t('Save Settings'), + )); + +} diff --git a/unicode_smilies/unicode_smilies.php b/unicode_smilies/unicode_smilies.php index 85077c45..583f6c97 100644 --- a/unicode_smilies/unicode_smilies.php +++ b/unicode_smilies/unicode_smilies.php @@ -6,7 +6,7 @@ * Author: Michael Vogel */ -use Friendica\Content\Smilies; +require_once 'include/Smilies.php'; function unicode_smilies_install() { register_hook('smilie', 'addon/unicode_smilies/unicode_smilies.php', 'unicode_smilies_smilies'); diff --git a/viewsrc/viewsrc.php b/viewsrc/viewsrc.php index 623ed89d..687d9253 100644 --- a/viewsrc/viewsrc.php +++ b/viewsrc/viewsrc.php @@ -6,7 +6,7 @@ * Description: Add "View Source" link to item context * Version: 1.0 * Author: Mike Macgirvin - * + * */ function viewsrc_install() { @@ -49,7 +49,7 @@ function viewsrc_item_photo_menu(&$a,&$b) { } else $item_id = $b['item']['id']; - $b['menu'] = array_merge( [ t('View Source') => $a->get_baseurl() . '/viewsrc/'. $item_id], $b['menu']); + $b['menu'] = array_merge( array( t('View Source') => $a->get_baseurl() . '/viewsrc/'. $item_id), $b['menu']); //if((! local_user()) || (local_user() != $b['item']['uid'])) // return; diff --git a/webrtc/webrtc.php b/webrtc/webrtc.php index 1588847d..8b3a243e 100644 --- a/webrtc/webrtc.php +++ b/webrtc/webrtc.php @@ -7,8 +7,6 @@ * Author: Tobias Diekershoff */ -use Friendica\Core\Config; - function webrtc_install() { register_hook('app_menu', 'addon/webrtc/webrtc.php', 'webrtc_app_menu'); } @@ -24,14 +22,14 @@ function webrtc_app_menu($a,&$b) { function webrtc_plugin_admin (&$a, &$o) { $t = get_markup_template( "admin.tpl", "addon/webrtc/" ); - $o = replace_macros( $t, [ + $o = replace_macros( $t, array( '$submit' => t('Save Settings'), - '$webrtcurl' => ['webrtcurl', t('WebRTC Base URL'), Config::get('webrtc','webrtcurl' ), t('Page your users will create a WebRTC chat room on. For example you could use https://live.mayfirst.org .')], - ]); + '$webrtcurl' => array('webrtcurl', t('WebRTC Base URL'), get_config('webrtc','webrtcurl' ), t('Page your users will create a WebRTC chat room on. For example you could use https://live.mayfirst.org .')), + )); } function webrtc_plugin_admin_post (&$a) { $url = ((x($_POST, 'webrtcurl')) ? notags(trim($_POST['webrtcurl'])) : ''); - Config::set('webrtc', 'webrtcurl', $url); + set_config('webrtc', 'webrtcurl', $url); info( t('Settings updated.'). EOL); } @@ -43,7 +41,7 @@ function webrtc_content(&$a) { $o = ''; /* landingpage to create chatrooms */ - $webrtcurl = Config::get('webrtc','webrtcurl'); + $webrtcurl = get_config('webrtc','webrtcurl'); /* embedd the landing page in an iframe */ $o .= '

    '.t('Video Chat').'

    '; diff --git a/widgets/widget_friendheader.php b/widgets/widget_friendheader.php index f9a8acec..20a84e25 100644 --- a/widgets/widget_friendheader.php +++ b/widgets/widget_friendheader.php @@ -8,17 +8,17 @@ function friendheader_widget_help() { } function friendheader_widget_args(){ - return []; + return Array(); } function friendheader_widget_size(){ - return ['780px','140px']; + return Array('780px','140px'); } function friendheader_widget_content(&$a, $conf){ - $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` + $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid` WHERE `user`.`uid` = %s AND `profile`.`is-default` = 1 LIMIT 1", intval($conf['uid']) @@ -34,10 +34,10 @@ function friendheader_widget_content(&$a, $conf){ .allcontact-link { float: right; margin: 0px; } .contact-block-content { clear:both; } .contact-block-div { display: block !important; float: left!important; width: 50px!important; height: 50px!important; margin: 2px!important;} - + "; $o .= _abs_url(contact_block()); $o .= "profile['nickname']."' target=new>". t('Get added to this list!') .""; - + return $o; } diff --git a/widgets/widget_friends.php b/widgets/widget_friends.php index 25e20180..195667e8 100644 --- a/widgets/widget_friends.php +++ b/widgets/widget_friends.php @@ -8,17 +8,17 @@ function friends_widget_help() { } function friends_widget_args(){ - return []; + return Array(); } function friends_widget_size(){ - return ['100%','200px']; + return Array('100%','200px'); } function friends_widget_content(&$a, $conf){ - $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` + $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.* FROM `profile` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid` WHERE `user`.`uid` = %s AND `profile`.`is-default` = 1 LIMIT 1", intval($conf['uid']) @@ -34,7 +34,7 @@ function friends_widget_content(&$a, $conf){ .allcontact-link { float: right; margin: 0px; } .contact-block-content { clear:both; } .contact-block-div { display: block !important; float: left!important; width: 50px!important; height: 50px!important; margin: 2px!important;} - + "; $o .= _abs_url(contact_block()); $o .= "profile['nickname']."'>". t('Connect on Friendica!') .""; diff --git a/widgets/widget_like.php b/widgets/widget_like.php index a67f0bd8..8f356da9 100644 --- a/widgets/widget_like.php +++ b/widgets/widget_like.php @@ -8,30 +8,30 @@ function like_widget_help() { } function like_widget_args(){ - return ["KEY"]; + return Array("KEY"); } function like_widget_size(){ - return ['60px','20px']; + return Array('60px','20px'); } function like_widget_content(&$a, $conf){ $args = explode(",",$_GET['a']); - - + + $baseq="SELECT COUNT(`item`.`id`) as `c`, `p`.`id` - FROM `item`, - (SELECT `i`.`id` FROM `item` as `i` WHERE + FROM `item`, + (SELECT `i`.`id` FROM `item` as `i` WHERE `i`.`visible` = 1 AND `i`.`deleted` = 0 - AND (( `i`.`wall` = 1 AND `i`.`allow_cid` = '' - AND `i`.`allow_gid` = '' - AND `i`.`deny_cid` = '' - AND `i`.`deny_gid` = '' ) + AND (( `i`.`wall` = 1 AND `i`.`allow_cid` = '' + AND `i`.`allow_gid` = '' + AND `i`.`deny_cid` = '' + AND `i`.`deny_gid` = '' ) OR `i`.`uid` = %d ) AND `i`.`body` LIKE '%%%s%%' LIMIT 1) as `p` WHERE `item`.`parent` = `p`.`id` "; - + // count likes $r = q( $baseq . "AND `item`.`verb` = 'http://activitystrea.ms/schema/1.0/like'", intval($conf['uid']), @@ -39,30 +39,30 @@ function like_widget_content(&$a, $conf){ ); $likes = $r[0]['c']; $iid = $r[0]['id']; - + // count dislikes $r = q( $baseq . "AND `item`.`verb` = 'http://purl.org/macgirvin/dfrn/1.0/dislike'", intval($conf['uid']), dbesc($args[0]) ); $dislikes = $r[0]['c']; - - + + require_once("include/conversation.php"); - + $o = ""; - + # $t = file_get_contents( dirname(__file__). "/widget_like.tpl" ); $t = get_markup_template("widget_like.tpl", "addon/widgets/"); - $o .= replace_macros($t, [ + $o .= replace_macros($t, array( '$like' => $likes, '$strlike' => sprintf( tt("%d person likes this", "%d people like this", $likes), $likes), - + '$dislike' => $dislikes, '$strdislike'=> sprintf( tt("%d person doesn't like this", "%d people don't like this", $dislikes), $dislikes), - + '$baseurl' => $a->get_baseurl(), - ]); - + )); + return $o; } diff --git a/widgets/widgets.php b/widgets/widgets.php index 502278a2..72534ce3 100644 --- a/widgets/widgets.php +++ b/widgets/widgets.php @@ -5,16 +5,15 @@ * Version: 1.0 * Author: Fabio Comuni */ - -use Friendica\Core\PConfig; - + + function widgets_install() { - register_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings'); + register_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings'); register_hook('plugin_settings_post', 'addon/widgets/widgets.php', 'widgets_settings_post'); logger("installed widgets"); } function widgets_uninstall() { - unregister_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings'); + unregister_hook('plugin_settings', 'addon/widgets/widgets.php', 'widgets_settings'); unregister_hook('plugin_settings_post', 'addon/widgets/widgets.php', 'widgets_settings_post'); } @@ -23,20 +22,20 @@ function widgets_settings_post(){ if(! local_user()) return; if (isset($_POST['widgets-submit'])){ - PConfig::delete(local_user(), 'widgets', 'key'); - + del_pconfig(local_user(), 'widgets', 'key'); + } } function widgets_settings(&$a,&$o) { if(! local_user()) - return; + return; + + + $key = get_pconfig(local_user(), 'widgets', 'key' ); + if ($key=='') { $key = mt_rand(); set_pconfig(local_user(), 'widgets', 'key', $key); } - - $key = PConfig::get(local_user(), 'widgets', 'key' ); - if ($key=='') { $key = mt_rand(); PConfig::set(local_user(), 'widgets', 'key', $key); } - - $widgets = []; + $widgets = array(); $d = dir(dirname(__file__)); while(false !== ($f = $d->read())) { if(substr($f,0,7)=="widget_") { @@ -44,17 +43,17 @@ function widgets_settings(&$a,&$o) { $w=$m[1]; if ($w!=""){ require_once($f); - $widgets[] = [$w, call_user_func($w."_widget_name")]; + $widgets[] = array($w, call_user_func($w."_widget_name")); } } } - - + + # $t = file_get_contents( dirname(__file__). "/settings.tpl" ); $t = get_markup_template("settings.tpl", "addon/widgets/"); - $o .= replace_macros($t, [ + $o .= replace_macros($t, array( '$submit' => t('Generate new key'), '$baseurl' => $a->get_baseurl(), '$title' => "Widgets", @@ -62,8 +61,8 @@ function widgets_settings(&$a,&$o) { '$key' => $key, '$widgets_h' => t('Widgets available'), '$widgets' => $widgets, - ]); - + )); + } function widgets_module() { @@ -77,7 +76,7 @@ function _abs_url($s){ function _randomAlphaNum($length){ return substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',$length)),0,$length); -} +} function widgets_content(&$a) { @@ -93,12 +92,12 @@ function widgets_content(&$a) { if (!count($r)){ if($a->argv[2]=="cb"){header('HTTP/1.0 400 Bad Request'); killme();} return; - } - $conf = []; + } + $conf = array(); $conf['uid'] = $r[0]['uid']; foreach($r as $e) { $conf[$e['k']]=$e['v']; } - - $o = ""; + + $o = ""; $widgetfile =dirname(__file__)."/widget_".$a->argv[1].".php"; if (file_exists($widgetfile)){ @@ -106,8 +105,8 @@ function widgets_content(&$a) { } else { if($a->argv[2]=="cb"){header('HTTP/1.0 400 Bad Request'); killme();} return; - } - + } + @@ -115,10 +114,10 @@ function widgets_content(&$a) { if ($a->argv[2]=="cb"){ /*header('Access-Control-Allow-Origin: *');*/ $o .= call_user_func($a->argv[1].'_widget_content',$a, $conf); - + } else { - + if (isset($_GET['p']) && local_user()==$conf['uid'] ) { $o .= ""; $o .= "

    Preview Widget

    "; @@ -131,13 +130,13 @@ function widgets_content(&$a) { } else { header("content-type: application/x-javascript"); } - - - + + + $widget_size = call_user_func($a->argv[1].'_widget_size'); - + $script = file_get_contents(dirname(__file__)."/widgets.js"); - $o .= replace_macros($script, [ + $o .= replace_macros($script, array( '$entrypoint' => $a->get_baseurl()."/widgets/".$a->argv[1]."/cb/", '$key' => $conf['key'], '$widget_id' => 'f9a_'.$a->argv[1]."_"._randomAlphaNum(6), @@ -146,35 +145,35 @@ function widgets_content(&$a) { '$width' => $widget_size[0], '$height' => $widget_size[1], '$type' => $a->argv[1], - ]); - + )); + if (isset($_GET['p'])) { $wargs = call_user_func($a->argv[1].'_widget_args'); $jsargs = implode(",", $wargs); if ($jsargs!='') $jsargs = "&a=".$jsargs.""; - + $o .= "

    Copy and paste this code

    " - + .htmlspecialchars('') .""; - + return $o; - } - - } - + } + + } + echo $o; killme(); } - + ?> diff --git a/windowsphonepush/windowsphonepush.php b/windowsphonepush/windowsphonepush.php index 66b23a7c..21f986e0 100644 --- a/windowsphonepush/windowsphonepush.php +++ b/windowsphonepush/windowsphonepush.php @@ -1,58 +1,68 @@ - * - * + * + * * Pre-requisite: Windows Phone mobile device (at least WP 7.0) * Friendica mobile app on Windows Phone * * When plugin is installed, the system calls the plugin * name_install() function, located in 'addon/name/name.php', * where 'name' is the name of the addon. - * If the addon is removed from the configuration list, the + * If the addon is removed from the configuration list, the * system will call the name_uninstall() function. * * Version history: - * 1.1 : addon crashed on php versions >= 5.4 as of removed deprecated call-time + * 1.1 : addon crashed on php versions >= 5.4 as of removed deprecated call-time * pass-by-reference used in function calls within function windowsphonepush_content * 2.0 : adaption for supporting emphasizing new entries in app (count on tile cannot be read out, - * so we need to retrieve counter through show_settings secondly). Provide new function for + * so we need to retrieve counter through show_settings secondly). Provide new function for * calling from app to set the counter back after start (if user starts again before cronjob * sets the counter back * count only unseen elements which are not type=activity (likes and dislikes not seen as new elements) */ -use Friendica\App; -use Friendica\Core\PConfig; -use Friendica\Model\User; - -function windowsphonepush_install() -{ - /* Our plugin will attach in three places. - * The first is within cron - so the push notifications will be + + +function windowsphonepush_install() { + + /** + * + * Our plugin will attach in three places. + * The first is within cron - so the push notifications will be * sent every 10 minutes (or whatever is set in crontab). + * */ + register_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron'); - /* Then we'll attach into the plugin settings page, and also the + /** + * + * Then we'll attach into the plugin settings page, and also the * settings post hook so that we can create and update - * user preferences. User shall be able to activate the plugin and + * user preferences. User shall be able to activate the plugin and * define whether he allows pushing first characters of item text + * */ + register_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings'); register_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post'); logger("installed windowsphonepush"); } -function windowsphonepush_uninstall() -{ - /* uninstall unregisters any hooks created with register_hook + +function windowsphonepush_uninstall() { + + /** + * + * uninstall unregisters any hooks created with register_hook * during install. Don't delete data in table `pconfig`. + * */ + unregister_hook('cron', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_cron'); unregister_hook('plugin_settings', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings'); unregister_hook('plugin_settings_post', 'addon/windowsphonepush/windowsphonepush.php', 'windowsphonepush_settings_post'); @@ -60,54 +70,57 @@ function windowsphonepush_uninstall() logger("removed windowsphonepush"); } + /* declare the windowsphonepush function so that /windowsphonepush url requests will land here */ -function windowsphonepush_module() -{ +function windowsphonepush_module() {} -} -/* Callback from the settings post function. +/** + * + * Callback from the settings post function. * $post contains the $_POST array. * We will make sure we've got a valid user account * and if so set our configuration setting for this person. + * */ -function windowsphonepush_settings_post($a, $post) -{ - if (!local_user() || (!x($_POST, 'windowsphonepush-submit'))) { +function windowsphonepush_settings_post($a,$post) { + if(! local_user() || (! x($_POST,'windowsphonepush-submit'))) return; - } $enable = intval($_POST['windowsphonepush']); - PConfig::set(local_user(), 'windowsphonepush', 'enable', $enable); + set_pconfig(local_user(),'windowsphonepush','enable',$enable); - if ($enable) { - PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0); + if($enable) { + set_pconfig(local_user(),'windowsphonepush','counterunseen', 0); } - PConfig::set(local_user(), 'windowsphonepush', 'senditemtext', intval($_POST['windowsphonepush-senditemtext'])); + set_pconfig(local_user(),'windowsphonepush','senditemtext',intval($_POST['windowsphonepush-senditemtext'])); - info(t('WindowsPhonePush settings updated.') . EOL); + info( t('WindowsPhonePush settings updated.') . EOL); } -/* Called from the Plugin Setting form. + +/** + * + * Called from the Plugin Setting form. * Add our own settings info to the page. + * */ -function windowsphonepush_settings(&$a, &$s) -{ - if (!local_user()) { +function windowsphonepush_settings(&$a,&$s) { + + if(! local_user()) return; - } /* Add our stylesheet to the page so we can make our settings look nice */ $a->page['htmlhead'] .= '' . "\r\n"; /* Get the current state of our config variables */ - $enabled = PConfig::get(local_user(), 'windowsphonepush', 'enable'); + $enabled = get_pconfig(local_user(),'windowsphonepush','enable'); $checked_enabled = (($enabled) ? ' checked="checked" ' : ''); - $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext'); + $senditemtext = get_pconfig(local_user(), 'windowsphonepush', 'senditemtext'); $checked_senditemtext = (($senditemtext) ? ' checked="checked" ' : ''); - $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url'); + $device_url = get_pconfig(local_user(), 'windowsphonepush', 'device_url'); /* Add some HTML to the existing form */ $s .= '
    '; @@ -123,7 +136,7 @@ function windowsphonepush_settings(&$a, &$s) $s .= ''; $s .= '
    '; - /* provide a submit button - enable und senditemtext can be changed by the user */ + /* provide a submit button - enable und senditemtext can be changed by the user*/ $s .= '
    '; /* provide further read-only information concerning the addon (useful for */ @@ -131,41 +144,48 @@ function windowsphonepush_settings(&$a, &$s) $s .= ''; $s .= ''; $s .= '
    '; - + return; + } -/* Cron function used to regularly check all users on the server with active windowsphonepushplugin and send + +/** + * + * Cron function used to regularly check all users on the server with active windowsphonepushplugin and send * notifications to the Microsoft servers and consequently to the Windows Phone device + * */ -function windowsphonepush_cron() -{ + +function windowsphonepush_cron() { // retrieve all UID's for which the plugin windowsphonepush is enabled and loop through every user $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'windowsphonepush' AND `k` = 'enable' AND `v` = 1"); - if (count($r)) { - foreach ($r as $rr) { + if(count($r)) { + foreach($r as $rr) { // load stored information for the user-id of the current loop - $device_url = PConfig::get($rr['uid'], 'windowsphonepush', 'device_url'); - $lastpushid = PConfig::get($rr['uid'], 'windowsphonepush', 'lastpushid'); + $device_url = get_pconfig($rr['uid'], 'windowsphonepush', 'device_url'); + $lastpushid = get_pconfig($rr['uid'], 'windowsphonepush', 'lastpushid'); - // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent + // pushing only possible if device_url (the URI on Microsoft server) is available or not "NA" (which will be sent // by app if user has switched the server setting in app - sending blank not possible as this would return an update error) - if (( $device_url == "" ) || ( $device_url == "NA" )) { + if ( ( $device_url == "" ) || ( $device_url == "NA" ) ) { // no Device-URL for the user availabe, but plugin is enabled --> write info to Logger logger("WARN: windowsphonepush is enable for user " . $rr['uid'] . ", but no Device-URL is specified for the user."); } else { - // retrieve the number of unseen items and the id of the latest one (if there are more than + // retrieve the number of unseen items and the id of the latest one (if there are more than // one new entries since last poller run, only the latest one will be pushed) - $count = q("SELECT count(`id`) as count, max(`id`) as max FROM `item` WHERE `unseen` = 1 AND `type` <> 'activity' AND `uid` = %d", intval($rr['uid'])); + $count = q("SELECT count(`id`) as count, max(`id`) as max FROM `item` WHERE `unseen` = 1 AND `type` <> 'activity' AND `uid` = %d", + intval($rr['uid']) + ); - // send number of unseen items to the device (the number will be displayed on Start screen until - // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if + // send number of unseen items to the device (the number will be displayed on Start screen until + // App will be started by user) - this update will be sent every 10 minutes to update the number to 0 if // user has loaded the timeline through app or website $res_tile = send_tile_update($device_url, "", $count[0]['count'], ""); switch (trim($res_tile)) { case "Received": - // ok, count has been pushed, let's save it in personal settings - PConfig::set($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']); + // ok, count has been pushed, let's save it in personal settings + set_pconfig($rr['uid'], 'windowsphonepush', 'counterunseen', $count[0]['count']); break; case "QueueFull": // maximum of 30 messages reached, server rejects any further push notification until device reconnects @@ -188,25 +208,27 @@ function windowsphonepush_cron() if (intval($count[0]['max']) > intval($lastpushid)) { // user can define if he wants to see the text of the item in the push notification // this has been implemented as the device_url is not a https uri (not so secure) - $senditemtext = PConfig::get($rr['uid'], 'windowsphonepush', 'senditemtext'); + $senditemtext = get_pconfig($rr['uid'], 'windowsphonepush', 'senditemtext'); if ($senditemtext == 1) { // load item with the max id - $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d", intval($count[0]['max'])); + $item = q("SELECT `author-name` as author, `body` as body FROM `item` where `id` = %d", + intval($count[0]['max']) + ); // as user allows to send the item, we want to show the sender of the item in the toast - // toasts are limited to one line, therefore place is limited - author shall be in + // toasts are limited to one line, therefore place is limited - author shall be in // max. 15 chars (incl. dots); author is displayed in bold font $author = $item[0]['author']; $author = ((strlen($author) > 12) ? substr($author, 0, 12) . "..." : $author); // normally we show the body of the item, however if it is an url or an image we cannot - // show this in the toast (only test), therefore changing to an alternate text + // show this in the toast (only test), therefore changing to an alternate text // Otherwise BBcode-Tags will be eliminated and plain text cutted to 140 chars (incl. dots) // BTW: information only possible in English $body = $item[0]['body']; - if (substr($body, 0, 4) == "[url") { + if (substr($body, 0, 4) == "[url") $body = "URL/Image ..."; - } else { + else { require_once('include/bbcode.php'); require_once("include/html2plain.php"); $body = bbcode($body, false, false, 2, true); @@ -214,82 +236,91 @@ function windowsphonepush_cron() $body = ((strlen($body) > 137) ? substr($body, 0, 137) . "..." : $body); } } else { - // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived" + // if user wishes higher privacy, we only display "Friendica - New timeline entry arrived" $author = "Friendica"; $body = "New timeline entry arrived ..."; } - // only if toast push notification returns the Notification status "Received" we will update th settings with the + // only if toast push notification returns the Notification status "Received" we will update th settings with the // new indicator max-id is checked against (QueueFull, Suppressed, N/A, Dropped shall qualify to resend - // the push notification some minutes later (BTW: if resulting in Expired for subscription status the + // the push notification some minutes later (BTW: if resulting in Expired for subscription status the // device_url will be deleted (no further try on this url, see send_push) // further log information done on count pushing with send_tile (see above) $res_toast = send_toast($device_url, $author, $body); if (trim($res_toast) === 'Received') { - PConfig::set($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']); - } + set_pconfig($rr['uid'], 'windowsphonepush', 'lastpushid', $count[0]['max']); + } } } } } } -/* Tile push notification change the number in the icon of the App in Start Screen of + +/* + * + * Tile push notification change the number in the icon of the App in Start Screen of * a Windows Phone Device, Image could be changed, not used for App "Friendica Mobile" + * */ -function send_tile_update($device_url, $image_url, $count, $title, $priority = 1) -{ +function send_tile_update($device_url, $image_url, $count, $title, $priority = 1) { $msg = "" . "" . - "" . - "" . $image_url . "" . - "" . $count . "" . - "" . $title . "" . - " " . + "". + "" . $image_url . "" . + "" . $count . "" . + "" . $title . "" . + " " . ""; - $result = send_push($device_url, [ + $result = send_push($device_url, array( 'X-WindowsPhone-Target: token', 'X-NotificationClass: ' . $priority, - ], $msg); + ), $msg); return $result; } -/* Toast push notification send information to the top of the display +/* + * + * Toast push notification send information to the top of the display * if the user is not currently using the Friendica Mobile App, however * there is only one line for displaying the information + * */ -function send_toast($device_url, $title, $message, $priority = 2) -{ - $msg = "" . +function send_toast($device_url, $title, $message, $priority = 2) { + $msg = "" . "" . - "" . - "" . $title . "" . - "" . $message . "" . - "" . - "" . + "" . + "" . $title . "" . + "" . $message . "" . + "" . + "" . ""; - $result = send_push($device_url, [ + $result = send_push($device_url, array( 'X-WindowsPhone-Target: toast', - 'X-NotificationClass: ' . $priority, - ], $msg); + 'X-NotificationClass: ' . $priority, + ), $msg); return $result; } -// General function to send the push notification via cURL -function send_push($device_url, $headers, $msg) -{ +/* + * + * General function to send the push notification via cURL + * + */ +function send_push($device_url, $headers, $msg) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $device_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_HEADER, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers + [ - 'Content-Type: text/xml', - 'charset=utf-8', - 'Accept: application/*', - ] - ); + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_HTTPHEADER, + $headers + array( + 'Content-Type: text/xml', + 'charset=utf-8', + 'Accept: application/*', + ) + ); curl_setopt($ch, CURLOPT_POSTFIELDS, $msg); $output = curl_exec($ch); @@ -299,31 +330,35 @@ function send_push($device_url, $headers, $msg) // and log this fact $subscriptionStatus = get_header_value($output, 'X-SubscriptionStatus'); if ($subscriptionStatus == "Expired") { - PConfig::set(local_user(), 'windowsphonepush', 'device_url', ""); + set_pconfig(local_user(),'windowsphonepush','device_url', ""); logger("ERROR: the stored Device-URL " . $device_url . "returned an 'Expired' error, it has been deleted now."); } - // the notification status shall be returned to windowsphonepush_cron (will + // the notification status shall be returned to windowsphonepush_cron (will // update settings if 'Received' otherwise keep old value in settings (on QueuedFull. Suppressed, N/A, Dropped) $notificationStatus = get_header_value($output, 'X-NotificationStatus'); return $notificationStatus; -} + } -// helper function to receive statuses from webresponse of Microsoft server -function get_header_value($content, $header) -{ +/* + * helper function to receive statuses from webresponse of Microsoft server + */ +function get_header_value($content, $header) { return preg_match_all("/$header: (.*)/i", $content, $match) ? $match[1][0] : ""; } -/* reading information from url and deciding which function to start + +/* + * + * reading information from url and deciding which function to start * show_settings = delivering settings to check * update_settings = set the device_url * update_counterunseen = set counter for unseen elements to zero + * */ -function windowsphonepush_content(App $a) -{ +function windowsphonepush_content(&$a) { // Login with the specified Network credentials (like in api.php) - windowsphonepush_login($a); + windowsphonepush_login(); $path = $a->argv[0]; $path2 = $a->argv[1]; @@ -335,14 +370,14 @@ function windowsphonepush_content(App $a) break; case "update_settings": $ret = windowsphonepush_updatesettings($a); - header("Content-Type: application/json; charset=utf-8"); - echo json_encode(['status' => $ret]); - killme(); + header("Content-Type: application/json; charset=utf-8"); + echo json_encode(array('status' => $ret)); + killme(); break; case "update_counterunseen": $ret = windowsphonepush_updatecounterunseen(); header("Content-Type: application/json; charset=utf-8"); - echo json_encode(['status' => $ret]); + echo json_encode(array('status' => $ret)); killme(); break; default: @@ -351,50 +386,48 @@ function windowsphonepush_content(App $a) } } -// return settings for windowsphonepush addon to be able to check them in WP app -function windowsphonepush_showsettings() -{ - if (!local_user()) { +/* + * return settings for windowsphonepush addon to be able to check them in WP app + */ +function windowsphonepush_showsettings(&$a) { + if(! local_user()) return; - } - $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable'); - $device_url = PConfig::get(local_user(), 'windowsphonepush', 'device_url'); - $senditemtext = PConfig::get(local_user(), 'windowsphonepush', 'senditemtext'); - $lastpushid = PConfig::get(local_user(), 'windowsphonepush', 'lastpushid'); - $counterunseen = PConfig::get(local_user(), 'windowsphonepush', 'counterunseen'); + $enable = get_pconfig(local_user(), 'windowsphonepush', 'enable'); + $device_url = get_pconfig(local_user(), 'windowsphonepush', 'device_url'); + $senditemtext = get_pconfig(local_user(), 'windowsphonepush', 'senditemtext'); + $lastpushid = get_pconfig(local_user(), 'windowsphonepush', 'lastpushid'); + $counterunseen = get_pconfig(local_user(), 'windowsphonepush', 'counterunseen'); $addonversion = "2.0"; - if (!$device_url) { + if (!$device_url) $device_url = ""; - } - if (!$lastpushid) { + if (!$lastpushid) $lastpushid = 0; - } - header("Content-Type: application/json"); - echo json_encode(['uid' => local_user(), - 'enable' => $enable, - 'device_url' => $device_url, - 'senditemtext' => $senditemtext, - 'lastpushid' => $lastpushid, - 'counterunseen' => $counterunseen, - 'addonversion' => $addonversion]); + header ("Content-Type: application/json"); + echo json_encode(array('uid' => local_user(), + 'enable' => $enable, + 'device_url' => $device_url, + 'senditemtext' => $senditemtext, + 'lastpushid' => $lastpushid, + 'counterunseen' => $counterunseen, + 'addonversion' => $addonversion)); } -/* update_settings is used to transfer the device_url from WP device to the Friendica server +/* + * update_settings is used to transfer the device_url from WP device to the Friendica server * return the status of the operation to the server */ -function windowsphonepush_updatesettings() -{ - if (!local_user()) { +function windowsphonepush_updatesettings(&$a) { + if(! local_user()) { return "Not Authenticated"; } // no updating if user hasn't enabled the plugin - $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable'); - if (!$enable) { + $enable = get_pconfig(local_user(), 'windowsphonepush', 'enable'); + if(! $enable) { return "Plug-in not enabled"; } @@ -405,69 +438,79 @@ function windowsphonepush_updatesettings() return "No valid Device-URL specified"; } - // check if sent url is already stored in database for another user, we assume that there was a change of + // check if sent url is already stored in database for another user, we assume that there was a change of // the user on the Windows Phone device and that device url is no longer true for the other user, so we - // et the device_url for the OTHER user blank (should normally not occur as App should include User/server + // et the device_url for the OTHER user blank (should normally not occur as App should include User/server // in url request to Microsoft Push Notification server) - $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND - `cat` = 'windowsphonepush' AND - `k` = 'device_url' AND + $r = q("SELECT * FROM `pconfig` WHERE `uid` <> " . local_user() . " AND + `cat` = 'windowsphonepush' AND + `k` = 'device_url' AND `v` = '" . $device_url . "'"); - if (count($r)) { - foreach ($r as $rr) { - PConfig::set($rr['uid'], 'windowsphonepush', 'device_url', ''); - logger("WARN: the sent URL was already registered with user '" . $rr['uid'] . "'. Deleted for this user as we expect to be correct now for user '" . local_user() . "'."); + if(count($r)) { + foreach($r as $rr) { + set_pconfig($rr['uid'], 'windowsphonepush', 'device_url', ''); + logger("WARN: the sent URL was already registered with user '" . $rr['uid'] . "'. Deleted for this user as we expect to be correct now for user '" . local_user() . "'."); } } - PConfig::set(local_user(), 'windowsphonepush', 'device_url', $device_url); + set_pconfig(local_user(),'windowsphonepush','device_url', $device_url); // output the successfull update of the device URL to the logger for error analysis if necessary logger("INFO: Device-URL for user '" . local_user() . "' has been updated with '" . $device_url . "'"); return "Device-URL updated successfully!"; } -// update_counterunseen is used to reset the counter to zero from Windows Phone app -function windowsphonepush_updatecounterunseen() -{ - if (!local_user()) { +/* + * update_counterunseen is used to reset the counter to zero from Windows Phone app + */ +function windowsphonepush_updatecounterunseen() { + if(! local_user()) { return "Not Authenticated"; } // no updating if user hasn't enabled the plugin - $enable = PConfig::get(local_user(), 'windowsphonepush', 'enable'); - if (!$enable) { + $enable = get_pconfig(local_user(), 'windowsphonepush', 'enable'); + if(! $enable) { return "Plug-in not enabled"; } - PConfig::set(local_user(), 'windowsphonepush', 'counterunseen', 0); + set_pconfig(local_user(),'windowsphonepush','counterunseen', 0); return "Counter set to zero"; } -/* helper function to login to the server with the specified Network credentials +/* + * helper function to login to the server with the specified Network credentials * (mainly copied from api.php) */ -function windowsphonepush_login(App $a) -{ +function windowsphonepush_login() { if (!isset($_SERVER['PHP_AUTH_USER'])) { - logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG); - header('WWW-Authenticate: Basic realm="Friendica"'); - header('HTTP/1.0 401 Unauthorized'); - die('This api requires login'); + logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG); + header('WWW-Authenticate: Basic realm="Friendica"'); + header('HTTP/1.0 401 Unauthorized'); + die('This api requires login'); } - $user_id = User::authenticate($_SERVER['PHP_AUTH_USER'], trim($_SERVER['PHP_AUTH_PW'])); + $user = $_SERVER['PHP_AUTH_USER']; + $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW'])); - if ($user_id) { - $record = dba::selectFirst('user', [], ['uid' => $user_id]); + // check if user specified by app is available in the user table + $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) + AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1", + dbesc(trim($user)), + dbesc(trim($user)), + dbesc($encrypted) + ); + + if(count($r)){ + $record = $r[0]; } else { - logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG); - header('WWW-Authenticate: Basic realm="Friendica"'); - header('HTTP/1.0 401 Unauthorized'); - die('This api requires login'); + logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG); + header('WWW-Authenticate: Basic realm="Friendica"'); + header('HTTP/1.0 401 Unauthorized'); + die('This api requires login'); } - require_once 'include/security.php'; - authenticate_success($record); - $_SESSION["allow_api"] = true; + require_once('include/security.php'); + authenticate_success($record); $_SESSION["allow_api"] = true; call_hooks('logged_in', $a->user); } + diff --git a/wppost/wppost.php b/wppost/wppost.php index 22032c90..fc9244af 100644 --- a/wppost/wppost.php +++ b/wppost/wppost.php @@ -7,8 +7,6 @@ * Author: Mike Macgirvin */ -use Friendica\Core\PConfig; - function wppost_install() { register_hook('post_local', 'addon/wppost/wppost.php', 'wppost_post_local'); register_hook('notifier_normal', 'addon/wppost/wppost.php', 'wppost_send'); @@ -36,9 +34,9 @@ function wppost_jot_nets(&$a,&$b) { if(! local_user()) return; - $wp_post = PConfig::get(local_user(),'wppost','post'); + $wp_post = get_pconfig(local_user(),'wppost','post'); if(intval($wp_post) == 1) { - $wp_defpost = PConfig::get(local_user(),'wppost','post_by_default'); + $wp_defpost = get_pconfig(local_user(),'wppost','post_by_default'); $selected = ((intval($wp_defpost) == 1) ? ' checked="checked" ' : ''); $b .= '
    ' . t('Post to Wordpress') . '
    '; @@ -57,23 +55,23 @@ function wppost_settings(&$a,&$s) { /* Get the current state of our config variables */ - $enabled = PConfig::get(local_user(),'wppost','post'); + $enabled = get_pconfig(local_user(),'wppost','post'); $checked = (($enabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); - $def_enabled = PConfig::get(local_user(),'wppost','post_by_default'); - $back_enabled = PConfig::get(local_user(),'wppost','backlink'); - $shortcheck_enabled = PConfig::get(local_user(),'wppost','shortcheck'); + $def_enabled = get_pconfig(local_user(),'wppost','post_by_default'); + $back_enabled = get_pconfig(local_user(),'wppost','backlink'); + $shortcheck_enabled = get_pconfig(local_user(),'wppost','shortcheck'); $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); $back_checked = (($back_enabled) ? ' checked="checked" ' : ''); $shortcheck_checked = (($shortcheck_enabled) ? ' checked="checked" ' : ''); - $wp_username = PConfig::get(local_user(), 'wppost', 'wp_username'); - $wp_password = PConfig::get(local_user(), 'wppost', 'wp_password'); - $wp_blog = PConfig::get(local_user(), 'wppost', 'wp_blog'); - $wp_backlink_text = PConfig::get(local_user(), 'wppost', 'wp_backlink_text'); + $wp_username = get_pconfig(local_user(), 'wppost', 'wp_username'); + $wp_password = get_pconfig(local_user(), 'wppost', 'wp_password'); + $wp_blog = get_pconfig(local_user(), 'wppost', 'wp_blog'); + $wp_backlink_text = get_pconfig(local_user(), 'wppost', 'wp_backlink_text'); /* Add some HTML to the existing form */ @@ -135,17 +133,17 @@ function wppost_settings_post(&$a,&$b) { if(x($_POST,'wppost-submit')) { - PConfig::set(local_user(),'wppost','post',intval($_POST['wppost'])); - PConfig::set(local_user(),'wppost','post_by_default',intval($_POST['wp_bydefault'])); - PConfig::set(local_user(),'wppost','wp_username',trim($_POST['wp_username'])); - PConfig::set(local_user(),'wppost','wp_password',trim($_POST['wp_password'])); - PConfig::set(local_user(),'wppost','wp_blog',trim($_POST['wp_blog'])); - PConfig::set(local_user(),'wppost','backlink',trim($_POST['wp_backlink'])); - PConfig::set(local_user(),'wppost','shortcheck',trim($_POST['wp_shortcheck'])); + set_pconfig(local_user(),'wppost','post',intval($_POST['wppost'])); + set_pconfig(local_user(),'wppost','post_by_default',intval($_POST['wp_bydefault'])); + set_pconfig(local_user(),'wppost','wp_username',trim($_POST['wp_username'])); + set_pconfig(local_user(),'wppost','wp_password',trim($_POST['wp_password'])); + set_pconfig(local_user(),'wppost','wp_blog',trim($_POST['wp_blog'])); + set_pconfig(local_user(),'wppost','backlink',trim($_POST['wp_backlink'])); + set_pconfig(local_user(),'wppost','shortcheck',trim($_POST['wp_shortcheck'])); $wp_backlink_text = notags(trim($_POST['wp_backlink_text'])); $wp_backlink_text = bbcode($wp_backlink_text, false, false, 8); $wp_backlink_text = html2plain($wp_backlink_text, 0, true); - PConfig::set(local_user(),'wppost','wp_backlink_text', $wp_backlink_text); + set_pconfig(local_user(),'wppost','wp_backlink_text', $wp_backlink_text); } @@ -167,11 +165,11 @@ function wppost_post_local(&$a, &$b) { return; } - $wp_post = intval(PConfig::get(local_user(),'wppost','post')); + $wp_post = intval(get_pconfig(local_user(),'wppost','post')); $wp_enable = (($wp_post && x($_REQUEST,'wppost_enable')) ? intval($_REQUEST['wppost_enable']) : 0); - if ($b['api_source'] && intval(PConfig::get(local_user(),'wppost','post_by_default'))) { + if ($b['api_source'] && intval(get_pconfig(local_user(),'wppost','post_by_default'))) { $wp_enable = 1; } @@ -191,29 +189,20 @@ function wppost_post_local(&$a, &$b) { function wppost_send(&$a,&$b) { - if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { + if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) return; - } - if(! strstr($b['postopts'],'wppost')) { + if(! strstr($b['postopts'],'wppost')) return; - } - if($b['parent'] != $b['id']) { + if($b['parent'] != $b['id']) return; - } - // Dont't post if the post doesn't belong to us. - // This is a check for forum postings - $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]); - if ($b['contact-id'] != $self['id']) { - return; - } - $wp_username = xmlify(PConfig::get($b['uid'],'wppost','wp_username')); - $wp_password = xmlify(PConfig::get($b['uid'],'wppost','wp_password')); - $wp_blog = PConfig::get($b['uid'],'wppost','wp_blog'); - $wp_backlink_text = PConfig::get($b['uid'],'wppost','wp_backlink_text'); + $wp_username = xmlify(get_pconfig($b['uid'],'wppost','wp_username')); + $wp_password = xmlify(get_pconfig($b['uid'],'wppost','wp_password')); + $wp_blog = get_pconfig($b['uid'],'wppost','wp_blog'); + $wp_backlink_text = get_pconfig($b['uid'],'wppost','wp_backlink_text'); if ($wp_backlink_text == '') { $wp_backlink_text = t('Read the orig­i­nal post and com­ment stream on Friendica'); } @@ -226,14 +215,14 @@ function wppost_send(&$a,&$b) { $wptitle = trim($b['title']); - if (intval(PConfig::get($b['uid'],'wppost','shortcheck'))) { + if (intval(get_pconfig($b['uid'],'wppost','shortcheck'))) { // Checking, if its a post that is worth a blog post $postentry = false; $siteinfo = get_attached_data($b["body"]); // Is it a link to an aricle, a video or a photo? if (isset($siteinfo["type"])) { - if (in_array($siteinfo["type"], ["link", "audio", "video", "photo"])) { + if (in_array($siteinfo["type"], array("link", "audio", "video", "photo"))) { $postentry = true; } } @@ -287,7 +276,7 @@ function wppost_send(&$a,&$b) { $post = $title.$post; - $wp_backlink = intval(PConfig::get($b['uid'],'wppost','backlink')); + $wp_backlink = intval(get_pconfig($b['uid'],'wppost','backlink')); if($wp_backlink && $b['plink']) { $post .= EOL . EOL . '' . $wp_backlink_text . '' . EOL . EOL; diff --git a/xmpp/lang/C/messages.po b/xmpp/lang/C/messages.po deleted file mode 100644 index a37749d0..00000000 --- a/xmpp/lang/C/messages.po +++ /dev/null @@ -1,57 +0,0 @@ -# ADDON xmpp -# Copyright (C) -# This file is distributed under the same license as the Friendica xmpp addon package. -# -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: \n" -"Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2017-11-27 09:30+0100\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"Language: \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" - -#: xmpp.php:38 -msgid "XMPP settings updated." -msgstr "" - -#: xmpp.php:63 xmpp.php:67 -msgid "XMPP-Chat (Jabber)" -msgstr "" - -#: xmpp.php:71 -msgid "Enable Webchat" -msgstr "" - -#: xmpp.php:76 -msgid "Individual Credentials" -msgstr "" - -#: xmpp.php:82 xmpp.php:108 -msgid "Jabber BOSH host" -msgstr "" - -#: xmpp.php:91 xmpp.php:107 -msgid "Save Settings" -msgstr "" - -#: xmpp.php:109 -msgid "Use central userbase" -msgstr "" - -#: xmpp.php:109 -msgid "" -"If enabled, users will automatically login to an ejabberd server that has to " -"be installed on this machine with synchronized credentials via the " -"\"auth_ejabberd.php\" script." -msgstr "" - -#: xmpp.php:119 -msgid "Settings updated." -msgstr "" diff --git a/xmpp/lang/de/messages.po b/xmpp/lang/de/messages.po deleted file mode 100644 index 252beb9b..00000000 --- a/xmpp/lang/de/messages.po +++ /dev/null @@ -1,61 +0,0 @@ -# ADDON xmpp -# Copyright (C) -# This file is distributed under the same license as the Friendica xmpp addon package. -# -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: \n" -"Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2017-11-27 09:30+0100\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: Andreas H. , 2017\n" -"Language-Team: German (https://www.transifex.com/Friendica/teams/12172/de/)\n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=UTF-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Language: de\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\n" - -#: xmpp.php:38 -msgid "XMPP settings updated." -msgstr "XMPP Einstellungen aktualisiert." - -#: xmpp.php:63 xmpp.php:67 -msgid "XMPP-Chat (Jabber)" -msgstr "XMPP-Chat (Jabber)" - -#: xmpp.php:71 -msgid "Enable Webchat" -msgstr "Aktiviere Webchat" - -#: xmpp.php:76 -msgid "Individual Credentials" -msgstr "Individuelle Anmeldedaten" - -#: xmpp.php:82 xmpp.php:108 -msgid "Jabber BOSH host" -msgstr "Jabber BOSH Host" - -#: xmpp.php:91 xmpp.php:107 -msgid "Save Settings" -msgstr "Speichere Einstellungen" - -#: xmpp.php:109 -msgid "Use central userbase" -msgstr "Nutze zentrale Nutzerbasis" - -#: xmpp.php:109 -msgid "" -"If enabled, users will automatically login to an ejabberd server that has to" -" be installed on this machine with synchronized credentials via the " -"\"auth_ejabberd.php\" script." -msgstr "" -"Wenn aktiviert, werden die Nutzer automatisch auf dem EJabber Server, der " -"auf dieser Maschine installiert ist, angemeldet und die Zugangsdaten werden " -"über das \"auth_ejabberd.php\"-Script synchronisiert." - -#: xmpp.php:119 -msgid "Settings updated." -msgstr "Einstellungen aktualisiert." diff --git a/xmpp/lang/de/strings.php b/xmpp/lang/de/strings.php deleted file mode 100644 index a8785024..00000000 --- a/xmpp/lang/de/strings.php +++ /dev/null @@ -1,16 +0,0 @@ -strings["XMPP settings updated."] = "XMPP Einstellungen aktualisiert."; -$a->strings["XMPP-Chat (Jabber)"] = "XMPP-Chat (Jabber)"; -$a->strings["Enable Webchat"] = "Aktiviere Webchat"; -$a->strings["Individual Credentials"] = "Individuelle Anmeldedaten"; -$a->strings["Jabber BOSH host"] = "Jabber BOSH Host"; -$a->strings["Save Settings"] = "Speichere Einstellungen"; -$a->strings["Use central userbase"] = "Nutze zentrale Nutzerbasis"; -$a->strings["If enabled, users will automatically login to an ejabberd server that has to be installed on this machine with synchronized credentials via the \"auth_ejabberd.php\" script."] = "Wenn aktiviert, werden die Nutzer automatisch auf dem EJabber Server, der auf dieser Maschine installiert ist, angemeldet und die Zugangsdaten werden über das \"auth_ejabberd.php\"-Script synchronisiert."; -$a->strings["Settings updated."] = "Einstellungen aktualisiert."; diff --git a/xmpp/xmpp.php b/xmpp/xmpp.php index ba8c27c7..076b7b13 100644 --- a/xmpp/xmpp.php +++ b/xmpp/xmpp.php @@ -1,48 +1,39 @@ */ -use Friendica\App; -use Friendica\Core\Config; -use Friendica\Core\PConfig; -function xmpp_install() -{ +function xmpp_install() { register_hook('plugin_settings', 'addon/xmpp/xmpp.php', 'xmpp_plugin_settings'); register_hook('plugin_settings_post', 'addon/xmpp/xmpp.php', 'xmpp_plugin_settings_post'); register_hook('page_end', 'addon/xmpp/xmpp.php', 'xmpp_script'); register_hook('logged_in', 'addon/xmpp/xmpp.php', 'xmpp_login'); } -function xmpp_uninstall() -{ +function xmpp_uninstall() { unregister_hook('plugin_settings', 'addon/xmpp/xmpp.php', 'xmpp_plugin_settings'); unregister_hook('plugin_settings_post', 'addon/xmpp/xmpp.php', 'xmpp_plugin_settings_post'); unregister_hook('page_end', 'addon/xmpp/xmpp.php', 'xmpp_script'); unregister_hook('logged_in', 'addon/xmpp/xmpp.php', 'xmpp_login'); } -function xmpp_plugin_settings_post() -{ - if (!local_user() || (!x($_POST, 'xmpp-settings-submit'))) { +function xmpp_plugin_settings_post($a,$post) { + if(! local_user() || (! x($_POST,'xmpp-settings-submit'))) return; - } - PConfig::set(local_user(), 'xmpp', 'enabled', intval($_POST['xmpp_enabled'])); - PConfig::set(local_user(), 'xmpp', 'individual', intval($_POST['xmpp_individual'])); - PConfig::set(local_user(), 'xmpp', 'bosh_proxy', $_POST['xmpp_bosh_proxy']); + set_pconfig(local_user(),'xmpp','enabled',intval($_POST['xmpp_enabled'])); + set_pconfig(local_user(),'xmpp','individual',intval($_POST['xmpp_individual'])); + set_pconfig(local_user(),'xmpp','bosh_proxy',$_POST['xmpp_bosh_proxy']); - info(t('XMPP settings updated.') . EOL); + info( t('XMPP settings updated.') . EOL); } -function xmpp_plugin_settings(App $a, &$s) -{ - if (!local_user()) { +function xmpp_plugin_settings(&$a,&$s) { + + if(! local_user()) return; - } /* Add our stylesheet to the xmpp so we can make our settings look nice */ @@ -50,13 +41,13 @@ function xmpp_plugin_settings(App $a, &$s) /* Get the current state of our config variable */ - $enabled = intval(PConfig::get(local_user(), 'xmpp', 'enabled')); + $enabled = intval(get_pconfig(local_user(),'xmpp','enabled')); $enabled_checked = (($enabled) ? ' checked="checked" ' : ''); - $individual = intval(PConfig::get(local_user(), 'xmpp', 'individual')); + $individual = intval(get_pconfig(local_user(),'xmpp','individual')); $individual_checked = (($individual) ? ' checked="checked" ' : ''); - $bosh_proxy = PConfig::get(local_user(), "xmpp", "bosh_proxy"); + $bosh_proxy = get_pconfig(local_user(),"xmpp","bosh_proxy"); /* Add some HTML to the existing form */ $s .= ''; @@ -72,15 +63,15 @@ function xmpp_plugin_settings(App $a, &$s) $s .= ''; $s .= '
    '; - if (Config::get("xmpp", "central_userbase")) { + if (get_config("xmpp", "central_userbase")) { $s .= ''; $s .= ''; $s .= '
    '; } - if (!Config::get("xmpp", "central_userbase") || PConfig::get(local_user(), "xmpp", "individual")) { - $s .= ''; - $s .= ' '; + if (!get_config("xmpp", "central_userbase") || get_pconfig(local_user(),"xmpp","individual")) { + $s .= ''; + $s .= ' '; $s .= '
    '; } @@ -89,77 +80,68 @@ function xmpp_plugin_settings(App $a, &$s) /* provide a submit button */ $s .= '
    '; + } -function xmpp_login() -{ +function xmpp_login($a,$b) { if (!$_SESSION["allow_api"]) { - $password = random_string(16); - PConfig::set(local_user(), "xmpp", "password", $password); + $password = substr(random_string(),0,16); + set_pconfig(local_user(), "xmpp", "password", $password); } } -function xmpp_plugin_admin(App $a, &$o) -{ +function xmpp_plugin_admin(&$a, &$o){ $t = get_markup_template("admin.tpl", "addon/xmpp/"); - $o = replace_macros($t, [ + $o = replace_macros($t, array( '$submit' => t('Save Settings'), - '$bosh_proxy' => ['bosh_proxy', t('Jabber BOSH host'), Config::get('xmpp', 'bosh_proxy'), ''], - '$central_userbase' => ['central_userbase', t('Use central userbase'), Config::get('xmpp', 'central_userbase'), t('If enabled, users will automatically login to an ejabberd server that has to be installed on this machine with synchronized credentials via the "auth_ejabberd.php" script.')], - ]); + '$bosh_proxy' => array('bosh_proxy', t('Jabber BOSH host'), get_config('xmpp', 'bosh_proxy'), ''), + '$central_userbase' => array('central_userbase', t('Use central userbase'), get_config('xmpp', 'central_userbase'), t('If enabled, users will automatically login to an ejabberd server that has to be installed on this machine with synchronized credentials via the "auth_ejabberd.php" script.')), + )); } -function xmpp_plugin_admin_post() -{ - $bosh_proxy = ((x($_POST, 'bosh_proxy')) ? trim($_POST['bosh_proxy']) : ''); - $central_userbase = ((x($_POST, 'central_userbase')) ? intval($_POST['central_userbase']) : false); - Config::set('xmpp', 'bosh_proxy', $bosh_proxy); - Config::set('xmpp', 'central_userbase', $central_userbase); - info(t('Settings updated.') . EOL); +function xmpp_plugin_admin_post(&$a){ + $bosh_proxy = ((x($_POST,'bosh_proxy')) ? trim($_POST['bosh_proxy']) : ''); + $central_userbase = ((x($_POST,'central_userbase')) ? intval($_POST['central_userbase']) : false); + set_config('xmpp','bosh_proxy',$bosh_proxy); + set_config('xmpp','central_userbase',$central_userbase); + info( t('Settings updated.'). EOL ); } -function xmpp_script(App $a) -{ - xmpp_converse($a); +function xmpp_script(&$a,&$s) { + xmpp_converse($a,$s); } -function xmpp_converse(App $a) -{ - if (!local_user()) { +function xmpp_converse(&$a,&$s) { + if (!local_user()) return; - } - if ($_GET["mode"] == "minimal") { + if ($_GET["mode"] == "minimal") return; - } - if ($a->is_mobile || $a->is_tablet) { + if ($a->is_mobile || $a->is_tablet) return; - } - if (!PConfig::get(local_user(), "xmpp", "enabled")) { + if (!get_pconfig(local_user(),"xmpp","enabled")) return; - } - if (in_array($a->query_string, ["admin/federation/"])) { + if (in_array($a->query_string, array("admin/federation/"))) return; - } - $a->page['htmlhead'] .= '' . "\n"; - $a->page['htmlhead'] .= '' . "\n"; + $a->page['htmlhead'] .= ''."\n"; + $a->page['htmlhead'] .= ''."\n"; - if (Config::get("xmpp", "central_userbase") && !PConfig::get(local_user(), "xmpp", "individual")) { - $bosh_proxy = Config::get("xmpp", "bosh_proxy"); + if (get_config("xmpp", "central_userbase") && !get_pconfig(local_user(),"xmpp","individual")) { + $bosh_proxy = get_config("xmpp", "bosh_proxy"); - $password = PConfig::get(local_user(), "xmpp", "password", '', true); + $password = get_pconfig(local_user(), "xmpp", "password"); if ($password == "") { - $password = random_string(16); - PConfig::set(local_user(), "xmpp", "password", $password); + $password = substr(random_string(),0,16); + set_pconfig(local_user(), "xmpp", "password", $password); } - $jid = $a->user["nickname"] . "@" . $a->get_hostname() . "/converse-" . random_string(5); + $jid = $a->user["nickname"]."@".$a->get_hostname()."/converse-".substr(random_string(),0,5);; $auto_login = "auto_login: true, authentication: 'login', @@ -167,20 +149,18 @@ function xmpp_converse(App $a) password: '$password', allow_logout: false,"; } else { - $bosh_proxy = PConfig::get(local_user(), "xmpp", "bosh_proxy"); + $bosh_proxy = get_pconfig(local_user(), "xmpp", "bosh_proxy"); $auto_login = ""; } - if ($bosh_proxy == "") { + if ($bosh_proxy == "") return; - } - if (in_array($a->argv[0], ["manage", "logout"])) { + if (in_array($a->argv[0], array("manage", "logout"))) $additional_commands = "converse.user.logout();\n"; - } else { + else $additional_commands = ""; - } $on_ready = ""; @@ -217,3 +197,4 @@ function xmpp_converse(App $a) }); "; } +?> diff --git a/yourls/yourls.css b/yourls/yourls.css index 53743650..cfd09c97 100644 --- a/yourls/yourls.css +++ b/yourls/yourls.css @@ -15,7 +15,7 @@ yourls-url { .yourls { text-align: left; - width: 100%; + width 100%; margin-top: 25px; font-size: 20px; } diff --git a/yourls/yourls.php b/yourls/yourls.php index d5d6d234..beea2619 100644 --- a/yourls/yourls.php +++ b/yourls/yourls.php @@ -9,8 +9,6 @@ * */ -use Friendica\Core\Config; - function yourls_install() { register_hook('plugin_settings', 'addon/yourls/yourls.php', 'yourls_addon_settings'); register_hook('plugin_settings_post', 'addon/yourls/yourls.php', 'yourls_addon_settings_post'); @@ -21,10 +19,10 @@ function yourls_install() { function yourls_uninstall() { unregister_hook('plugin_settings', 'addon/yourls/yourls.php', 'yourls_addon_settings'); unregister_hook('plugin_settings_post', 'addon/yourls/yourls.php', 'yourls_addon_settings_post'); - Config::set('yourls','url1',trim($_POST[''])); - Config::set('yourls','username1',trim($_POST[''])); - Config::set('yourls','password1',trim($_POST[''])); - Config::set('yourls','ssl1',trim($_POST[''])); + set_config('yourls','url1',trim($_POST[''])); + set_config('yourls','username1',trim($_POST[''])); + set_config('yourls','password1',trim($_POST[''])); + set_config('yourls','ssl1',trim($_POST[''])); } @@ -43,15 +41,15 @@ function yourls_addon_settings(&$a,&$s) { $a->page['htmlhead'] .= '' . "\r\n"; - $yourls_url = Config::get('yourls','url1'); - $yourls_username = Config::get('yourls','username1'); - $yourls_password = Config::get('yourls', 'password1'); - $ssl_enabled = Config::get('yourls','ssl1'); + $yourls_url = get_config('yourls','url1'); + $yourls_username = get_config('yourls','username1'); + $yourls_password = get_config('yourls', 'password1'); + $ssl_enabled = get_config('yourls','ssl1'); $ssl_checked = (($ssl_enabled) ? ' checked="checked" ' : ''); - $yourls_ssl = Config::get('yourls', 'ssl1'); + $yourls_ssl = get_config('yourls', 'ssl1'); $s .= ''; $s .= '

    ' . t('YourLS') . '

    '; @@ -93,10 +91,10 @@ function yourls_addon_settings_post(&$a,&$b) { return; if($_POST['yourls-submit']) { - Config::set('yourls','url1',trim($_POST['yourls_url'])); - Config::set('yourls','username1',trim($_POST['yourls_username'])); - Config::set('yourls','password1',trim($_POST['yourls_password'])); - Config::set('yourls','ssl1',intval($_POST['yourls_ssl'])); + set_config('yourls','url1',trim($_POST['yourls_url'])); + set_config('yourls','username1',trim($_POST['yourls_username'])); + set_config('yourls','password1',trim($_POST['yourls_password'])); + set_config('yourls','ssl1',intval($_POST['yourls_ssl'])); info( t('yourls Settings saved.') . EOL); } } -- 2.39.5