* @license PHP License * @package WB * @subpackage base */ WBClass::load('WBEvent_Handler' , 'WBString' , 'WBBlog' , 'WBBlog_Tool' ); /** * Event_Handler_Blog2Facebook * * Post blog article on facebook * * @version 0.1.0 * @package WB * @subpackage base */ class WBEvent_Handler_Blog2Facebook extends WBEvent_Handler { /** * configuration parameter * @var array */ protected $config = array( 'msgindex' => 'title', 'titleindex' => 'title' // 'actions' => array('Like') ); /** * blog tool * @vart WBBlog_Tool */ private $blog; /** * facebook connection * @var WBFacebook */ private $fb; /** * dict * @var WBDatasource_URLReference */ private $ref; /** * file * @var WBVFS_File */ private $file; /** * process event * * just say OK * * @see isRecoverable() * @param WBEvent $e * @return bool true to continue, false to stop processing * @throws Exception in case of error */ public function process(WBEvent $e) { $change = $e->get('change'); if ('public' != $change[1]) { return true; } $new = $e->get('new'); if (!$new && 'public' == $change[0]) { return true; } $msg = $e->get($this->config['msgindex'], ''); if (empty($msg)) { $msg = $e->get('title'); } // check for timed records $ts = strtotime($e->get('created', '1970-01-01 00:00:00')); if (time() < $ts) { $this->retry(); return true; } $url = $this->getBlogUrl($e); $data = array( 'message' => $msg ); $this->addPicture($data, $url); $this->postOnWall($data, $url); return true; } /** * add picture URL * * Find vfsfile references and add first file as picture. * * @param array $data * @param string $url */ private function addPicture(&$data, $url) { $this->file = WBClass::create('WBVFS_File'); $this->ref = WBClass::create('WBDatasource_URLReference'); $files = $this->ref->get($url, array('vfsfile')); if (empty($files)) { return; } foreach ($files as $f) { $file = $this->file->loadById($f['xid']); if (!$file->isOK()) { continue; } $data['picture'] = WBString::replaceSuperPlaceholders($file->getUrl('image')); return; } } /** * post record on wall * * @todo do something with the post id? * @param array $data * @param string $link */ private function postOnWall($data, $link) { if (!$this->fb) { $this->fb = WBClass::create('WBFacebook'); } $data['link'] = $link; $actions = array( array( 'name' => 'Like', 'link' => $link ) ); $id = $this->fb->postOnWall($data, $actions); } /** * get blog's article URL * * @param WBEvent $e * @return string $url */ private function getBlogUrl(WBEvent $e) { if (!$this->blog) { $this->blog = WBClass::create('WBBlog_Tool'); } $this->blog->loadArticleByData($e->get()); $url = $this->blog->getArticleUrl(); $url = WBString::replaceSuperPlaceholders($url); return $url; } /** * throw recoverable execption * * @throws WBException_Trylater */ private function retry() { $this->recoverable = true; WBClass::load('WBException_Trylater'); throw new WBException_Trylater('It is too early to publish the article at facebook, try again later.', 1, __CLASS__); } } ?>