/lib/wc_actions.php
PHP | 1735 lines | 683 code | 324 blank | 728 comment | 110 complexity | 22260f2246f1bc941ae5a22e7cd9454e MD5 | raw file
- <?php
- /**
- * This class is responsible for setting up all
- * all the configurations and functions surrounding
- * the \syndicate and allowing them to function
- * inside of a local installation of WordPress
- *
- * @author WriteCrowd <support@writecrowd.com>
- * @version 0.9
- * @link https://www.writecrowd.com/
- * @copyright WriteCrowd https://www.writecrowd.com/
- * @license GPL 3.0
- *
- * WriteCrowd is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * WriteCrowd is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with WriteCrowd. If not, see <http://www.gnu.org/licenses/>.
- *
- */
- class Wc_Actions {
- ////////////////////////////////////////////////////////////////////////
- ////////// Properties ///////////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- protected static $oInstance = null; // Singleton instance container
- protected $oAccount = null; // The current 180Create account in use
- protected $oArticle = null; // The current article in use
- protected $aArticles = null; // The current article set in use
- protected $aCategories = null; // Our categories
- protected $aComments = null; // Our comments
- protected $oDatabase = null; // Our database object
- protected $sError = null; // Container for the current error
- protected $aGroups = null; // Container for the current user's groups
- protected $sNamespace = null; // Our application namespace
- protected $sPluginPath = null; // Path to our Plugin
- protected $sPluginWebPath = null; // URL to plugin
- protected $oPost = null; // The current WordPress Post in use
- protected $aPosts = null; // WordPress posts
- protected $oPostData = null; // POST data container
- protected $mResponse = null; // RPC response container
- protected $oScope = null; // A variable scope to pass to the template
- protected $aSearchResults = null; // Results container for when a search is run
- protected $aSubcategories = null; // Our subcategories
- ////////////////////////////////////////////////////////////////////////
- ////////// Singleton ////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- /**
- * This sets the singleton pattern instance
- *
- * @return object self::$oInstance
- */
- public static function setInstance() {
- try {
- // Set instance to new self
- self::$oInstance = new Wc_Actions();
- //self::$oInstance = new Wc_Actions();
- //self::$oInstance = new StdClass();
- } catch (Exception $oException) {
- // Set error string
- // $this->setError("Error: {$oException->getMessage()}");
- }
- // Return instance of class
- return self::$oInstance;
- }
- /**
- * This gets the singleton instance
- *
- * @return object self::$oInstance
- */
- public static function getInstance() {
- // Check to see if an instance has already
- // been created
- if (is_null(self::$oInstance)) {
- return self::setInstance();
- } else {
- // If so, return the previously created
- // instance
- return self::$oInstance;
- }
- }
- /**
- * This method resets the sinleton instance
- *
- * @return void
- */
- public static function resetInstance() {
- self::$oInstance = null;
- }
- ////////////////////////////////////////////////////////////////////////
- ////////// Private Construct //////////////////////////////
- /////////////////////////////////////////////////////////////////////
- /**
- * This method sets up all of the WordPress features we wish to use
- *
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- private function __construct() {
- /*
- // Check to see if an admin
- // has logged into the system
- if (is_admin()) {
- // If so, setup all of the
- // admin functions and controls
- // WordPress Init
- add_action('init', array($this, 'loadAssets'));
- // Create the sidebar menu for 180 Create
- add_action('admin_menu', array($this, 'loadAdminMenu'));
- // Meta Box
- // WordPress >= 3.0
- // add_action('add_meta_boxes', array($this, 'loadMetaBox'));
- // WordPress < 3.0
- add_action('admin_init', array($this, 'loadMetaBox'), 1);
- } else {
- // Load scripts and styles
- // for the client
- add_action('wp_head', array($this, 'loadAssets'), 1);
- }
- // Display Post Author
- add_filter('the_author', array($this, 'renderPostAuthor'));
- // Display Post Content
- add_filter('the_content', array($this, 'renderPostContent'));
- // Set all of the functions and controls
- // Display Post Title
- add_filter('the_title', array($this, 'renderPostTitle'));
- // Determine if we want to display our comments
- if (Wc_Config::Get('variables', 'enableCommentEngine')) {
- // Run when displaying Comments for a single post
- add_filter('comments_array', array($this, 'handleComments'));
- // Use Our Comments Template
- add_filter('comments_template', array($this, 'renderComments'));
- }
- */
- // Return instance
- return $this;
- }
- ////////////////////////////////////////////////////////////////////////
- ////////// Public Methods ///////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- /**
- * This method is responsible for logging data
- *
- * @param string $sData is a json encoded string of properties
- * @return boolean based on the success or failure of the log
- */
- public function doLog($sData = null) {
- // Make sure we have data
- if (is_null($sData)) {
- // If there is no data,
- // return false
- return false;
- // We have data
- } else {
- // Setup the SQL query
- $sQuery = "INSERT INTO `{$this->getDatabase()->prefix}{$this->getNamespace()}_log` VALUES (NOW(), ".mysql_real_escape_string($sData).");";
- // Try to log the data
- try {
- // Log the data
- $this->getDatabase()->query($sQuery);
- // Return true because there
- // were no errors
- return true;
- // Catch any exceptions
- } catch (Exception $oException) {
- // Set system error to exception message
- $this->setError($oException->getMessage());
- // Return false because there
- // was an exception
- return false;
- }
- }
- }
- /**
- * This method handles the login process
- * for the 180Create Account
- *
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function doLogin() {
- // Check for POST data
- if ($this->checkForData('getPostData')) {
- // POST data was found, make the
- // JSON-RPC service call
- $aPostNameSpace = $this->getPostData()->{$this->getNameSpace()};
- $this->feedJson(array(
- '_method' => 'logon',
- 'username' => $this->doSanitize($aPostNameSpace['txtDisplayName']),
- 'passwd' => $this->doSanitize($aPostNameSpace['txtPasswd'])
- ));
- // Check for a JSON-RPC error
- if (is_object($this->getRpcResponse()) && property_exists($this->getRpcResponse(), 'error')) {
- // Set the system error to the
- // JSON-RPC service error
- $this->setError($this->getRpcResponse()->error);
- } else {
- // No error was found, now
- // set the system account
- $this->setAccount($this->getRpcResponse());
- // Store the current user
- $oUser = wp_get_current_user();
- // Make sure a user is logged in
- if (empty($oUser->ID)) {
- // No user is logged in, so
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noWordPressUserLoggedIn'));
- } else {
- // Store the account
- $this->getDatabase()->query(str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}',
- '{wpId}',
- '{returnedAccountId}',
- '{returnedAccountObject}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNamespace(),
- $oUser->ID,
- $this->getRpcResponse()->id,
- mysql_real_escape_string(json_encode($this->getRpcResponse()))
- ), Wc_Config::Get('sqlMiscQueries', 'storeOneightyAccount')));
- }
- }
- } else {
- // No POST data was found,
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noPostData'));
- }
- // Return instance
- return $this;
- }
- /**
- * This method logs a user out of the syndicate
- *
- * @return bool
- */
- public function doLogout() {
- // Grab the current user
- $oUser = wp_get_current_user();
- // Setup the sql
- $sSql = str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}',
- '{wpId}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNamespace(),
- $oUser->ID
- ), Wc_Config::Get('sqlMiscQueries', 'removeOneightyAccount'));
- // Try to run the query
- if ($this->getDatabase()->query($sSql)) {
- // The user has been
- // logged out, return
- return true;
- } else {
- // The user was not
- // logged out, return
- return false;
- }
- }
- /**
- * This method handles the removal process
- *
- * @param integer $aid article ID
- * @return boolean based on the success or failure of the removal
- */
- public function doRemoveArticle($aid) {
- $aid = intval($aid);
- // Check for a 180Create Account
- if (!$user = wp_oneighty_user_details()) {
- // if (!$this->checkForOneightyAccount()) {
- // No 180Create account was found
- return false;
- }
- $this->setAccount($user);
- // Make sure this is actually a
- // 180Create article
- if ($wcid = $this->checkIfOneightyArticle($aid)) {
- // Check to see if the author of
- // the article is logged into this
- // local WordPress instance
- //
- // MK this is severly unsafe if this is the only check protecting the server's data.
- //if ($this->checkIfArticleBelongsToOneightyAccount() === true) {
- $article = $this->getDatabase()->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE ID = '".addslashes($aid)."'");
- $article = $article[0];
- $this->getDatabase()->query("DELETE FROM {$this->getDatabase()->prefix}mediaplace_posts WHERE post_id = '".addslashes($aid)."'");
- // Update Post
- wp_update_post(array(
- 'ID' => $aid,
- 'post_content' => $this->getArticle()->aSyndicationData[str_replace('{nameSpace}', $this->getNameSpace(), Wc_Config::Get('wordPress', 'postMetaKeyData'))]->content
- ));
- // Remove post meta
- delete_post_meta($aid, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyData')));
- delete_post_meta($aid, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyId')));
- delete_post_meta($aid, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyPullComments')));
- delete_post_meta($aid, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicated')));
- delete_post_meta($aid, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicationDate')));
- // Send the deactivation signal
- // to the RPC server
- $this->feedJson(array(
- '_method' => 'deactivate_article',
- '_key' => $user->data->account_key,
- 'article_id' => $wcid
- ));
- // We're done, return
- return true;
- //} else {
- //}
- } else {
- // Try to remove the article
- // from the WordPress DB
- try {
- // Delete the post from,
- // the WordPress DB
- wp_delete_post($aid, true);
- // Catch all errors and exceptions
- } catch (Exception $oException) {
- // Set the system error to the
- // exception error message
- $this->setError($oException->getMessage());
- // Return false because
- // there was an error
- return false;
- }
- // Return true because the artice
- // was successfully removed
- return true;
- }
- /*
- } else {
- // Set system error
- $this->setError(Wc_Config::Get('errorMessages', 'noPostData'));
- // Return false because there
- // was an error
- return false;
- }
- */
- }
- /**
- * This method sanitizes and strips unwanted
- * characters from the provided string
- *
- * @param string $sData is the string to sanitize
- * @param string $sCustom is a custom expression to run
- * @return string $sSanitized is the sanitized string
- */
- public function doSanitize($sData, $sCustom = null) {
- // Sanitized string placeholder
- $sSanitized = null;
- // Check for a custom expression
- if (is_null($sCustom)) {
- // There is no custom expression,
- // run the default sanitization
- $sSanitized = mysql_real_escape_string(strip_tags($sData));
- } else {
- // Run the custom expression
- $sSanitized = mysql_real_escape_string(preg_replace($sCustom, '', $sData));
- }
- // Return the sanitized string
- return $sSanitized;
- }
- /**
- * This method handles the searching of
- * the 180Create database
- *
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function doSearch() {
- // Check for POST data
- if ($this->checkForData('getPostData')) {
- // POST data was found, check for
- // a user account
- if ($this->checkForOneightyAccount()) {
- // POST data was found, make the
- // JSON-RPC service call
- $aPostNameSpace = $this->getPostData()->{$this->getNameSpace()};
- $this->feedJson(array(
- '_method' => 'search',
- '_key' => $this->getAccount()->account_key,
- 'criteria' => $this->doSanitize($aPostNameSpace['txtCriteria'])
- ));
- // Check for a JSON-RPC error
- if (is_object($this->getRpcResponse()) && property_exists($this->getRpcResponse(), 'error')) {
- // Set the system error to the
- // JSON-RPC service error
- $this->setError($this->getRpcResponse()->error);
- // Return instance
- return $this;
- } else {
- // No error was found, now
- // Check for actual results
- if (count($this->getRpcResponse())) {
- // Grab the current articles
- // in the local WordPress DB
- $sArticlesQuery = str_replace(array(
- '{wpdbPrefix}', '{nameSpace}'
- ), array(
- $this->getDatabase()->prefix, $this->getNamespace()
- ), Wc_Config::Get('sqlMiscQueries', 'retrieveOneightyArticles'));
- // Try to execute the SQL
- try {
- // Execute the SQL
- $aArticles = $this->getDatabase()->get_results($sArticlesQuery);
- // Check for results
- if (count($aArticles)) {
- // We have results, create
- // the exclusion array
- $aExclude = array();
- // Loop through the local IDs
- // and append them
- foreach ($aArticles as $oArticle) {
- // Append the ID to the exclusion
- // array
- $aExclude[] = $oArticle->iOneightyId;
- }
- // Now loop through the search
- // results and check id the ID
- // is in the exclusion array
- $aSearchResults = $this->getRpcResponse();
- foreach ($aSearchResults as $iIndex => $oArticle) {
- // Check for ID
- if (in_array($oArticle->id, $aExclude)) {
- // If it is in the exclude array
- // unset the array index
- unset($aSearchResults[$iIndex]);
- }
- }
- // Set the system search results
- $this->setSearchResults($aSearchResults);
- // Return instance
- return $this;
- // Nothing has been syndicated yet
- } else {
- // Set the system search results
- $this->setSearchResults($this->getRpcResponse());
- // Return instance
- return $this;
- }
- // Catch all exceptions
- } catch (Exception $oException) {
- // Set the system error to the
- // exception message
- $this->setError($oException->getMessage());
- // Return instance
- return $this;
- }
- } else {
- // No articles were found,
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noSearchResults'));
- // Return instance
- return $this;
- }
- }
- // No account was found
- } else {
- // Set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noOneightyAccount'));
- // Return instance
- return $this;
- }
- } else {
- // No POST data was found,
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noPostData'));
- // Return instance
- return $this;
- }
- }
- /**
- * This method increments the syndication count of the articles
- *
- * @param string $sApiKey is the account holder's API key
- * @param integer $iArticleId is the article id to increment statistics
- * @param integer $iUserId is the account holder's account ID
- * @return bool based on success or failure
- */
- public function doSyndicatePlusOne($sApiKey, $iArticleId, $iUserId) {
- // Run the feed
- $this->feedJson(array(
- '_method' => 'syndicate_plus_one',
- '_key' => $sApiKey,
- 'article_id' => $iArticleId,
- 'user_id' => $iUserId
- ));
- // Check for an error
- if (empty($this->getRpcResponse()->error)) {
- // All is well, return
- return true;
- } else {
- // We have an error, set it
- // into the system
- $this->setError($this->getRpcResponse()->error);
- // Return
- return false;
- }
- }
- /**
- * This method is responsible syndicating
- * content between WordPress and 180Create
- *
- * @param boolean $bToWordPress determines whether we are syndicating to WordPress or 180Create
- * @return boolean based on the success or failure of the syndication
- */
- public function doSyndicateToRpc() {
- // Check for an account
- if ($this->checkForOneightyAccount()) {
- // We now have data, process
- // and syndicate it
- $aJsonRpcParams = array(
- '_method' => 'post',
- '_key' => $this->getAccount()->account_key,
- 'author_id' => $this->getAccount()->id,
- 'content' => $this->getArticle()->sContent,
- 'title' => $this->getArticle()->sTitle,
- 'description' => $this->getArticle()->sExcerpt,
- 'category_id' => $this->getArticle()->iCategoryId,
- 'secondcategory_id' => $this->getArticle()->iSecondCategoryId,
- 'subcategory_id' => $this->getArticle()->iSubcategoryId,
- 'secondsubcategory_id' => $this->getArticle()->iSecondSubcategoryId,
- 'group_id' => $this->getArticle()->iGroupId,
- 'private' => $this->getArticle()->iPrivate,
- 'tag_words' => $this->getArticle()->sTagWords,
- 'cost' => $this->getArticle()->iCost,
- 'allow_free' => $this->getArticle()->iFree,
- 'name' => $this->getArticle()->sName,
- 'from_blog' => get_bloginfo('name'),
- 'from_url' => get_bloginfo('url')
- );
- // Try to run the RPC request
- if ($this->feedJson($aJsonRpcParams)) {
- // Check fro RPC errors
- if (!empty($this->getRpcResponse()->error)) {
- // Set the system error
- $this->setError($this->getRpcResponse()->error);
- // Return
- return false;
- }
- // No errors were found, all signs
- // point to the article being syndicated
- // now check for a WordPress Post ID
- if (empty($this->getArticle()->iWordPressId)) {
- // Set system error
- $this->setError(Wc_Config::Get('errorMessages', 'noArticleToSyndicate'));
- // Return
- return false;
- } else {
- // We have a WordPress Post
- // no update the post
- $this->getDatabase()->query(str_replace(array(
- '{wpdbPrefix}',
- '{iWordPressId}',
- '{sPostStatus}',
- '{sPostTitle}',
- '{sPostType}',
- '{sPostName}',
- '{sPostContent}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getArticle()->iWordPressId,
- 'publish',
- $this->getRpcResponse()->title,
- 'post',
- $this->getRpcResponse()->name,
- mysql_real_escape_string(json_encode(array(
- 'iArticleId' => $this->getRpcResponse()->id
- )))
- ), Wc_Config::Get('sqlMiscQueries', 'updateWordPressPost')));
- // Add our post meta data
- add_post_meta($this->getArticle()->iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyData')), mysql_real_escape_string(json_encode($this->getRpcResponse())), true);
- add_post_meta($this->getArticle()->iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyId')), $this->doSanitize($this->getRpcResponse()->id), true);
- add_post_meta($this->getArticle()->iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyPullComments')), true, true);
- add_post_meta($this->getArticle()->iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicationDate')), date('Y-m-d H:i:s'), true);
- add_post_meta($this->getArticle()->iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicated')), true, true);
- // One up the syndication count
- if ($this->doSyndicatePlusOne($this->getAccount()->account_key, $this->getRpcResponse()->id, $this->getAccount()->id)) {
- // All is well, return
- return true;
- } else {
- // Something got fubar'd, return
- return false;
- }
- }
- } else {
- // Return
- return false;
- }
- } else {
- // Set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noOneightyAccount'));
- // Return
- return false;
- }
- }
- public function doSyndicateToWordPress() {
- // Check for POST
- if (!empty($_POST) && !empty($_POST[$this->getNameSpace()])) {
- // Set our POST data
- $aPostData = (array) $_POST[$this->getNameSpace()];
- // Check for user account
- if ($this->checkForOneightyAccount()) {
- // Make the JSON-RPC call
- $this->feedJson(array(
- '_method' => 'fetch',
- '_key' => $this->getAccount()->account_key,
- 'article_id' => $this->doSanitize($aPostData['iArticleId'])
- ));
- // Check for JSON-RPC errors
- if (property_exists($this->getRpcResponse(), 'error')) {
- // Set the system error
- // to the JSON-RPC error
- $this->setError($this->getRpcResponse()->error);
- // Return false because
- // there was an error
- return false;
- }
- // Create a new WordPress
- // post and store the ID
- $iWordPressId = wp_insert_post(array(
- 'post_status' => 'publish',
- 'post_title' => $this->doSanitize($this->getRpcResponse()->title),
- 'post_type' => 'post',
- 'post_name' => $this->doSanitize($this->getRpcResponse()->name),
- 'post_content' => json_encode(array(
- 'iOneightyId' => $this->doSanitize($this->getRpcResponse()->id)
- ))
- ));
- // Add the 180Create post meta data
- // into the local WordPress system
- add_post_meta($iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyData')), mysql_real_escape_string(json_encode($this->getRpcResponse())), true);
- add_post_meta($iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyId')), $this->doSanitize($this->getRpcResponse()->id), true);
- add_post_meta($iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyPullComments')), true, true);
- add_post_meta($iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicationDate')), date('Y-m-d H:i:s'), true);
- add_post_meta($iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicated')), true, true);
- // All is well, now update
- // the syndication count
- $this->feedJson(array(
- '_method' => 'syndicate_plus_one',
- '_key' => $this->doSanitize($this->getAccount()->account_key),
- 'article_id' => $this->doSanitize($aPostData['iArticleId']),
- 'user_id' => $this->doSanitize($this->getAccount()->id)
- ));
- // Check for JSON-RPC errors
- if (property_exists($this->getRpcResponse(), 'error')) {
- // Set the system error to the
- // JSON-RPC error message
- $this->setError($this->getRpcResponse()->error);
- // Return false because
- // there was an error
- return false;
- }
- // Check for JSON-RPC success
- if (property_exists($this->getRpcResponse(), 'success') && $this->getRpcResponse()->success == true) {
- // There are no errors
- // and all is well,
- // return true
- return true;
- } else {
- // Set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noSyndicatePlusOne'));
- // Return false because
- // there was an error
- return false;
- }
- }else {
- // Set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noOneightyAccount'));
- // Return
- return false;
- }
- } else {
- // Set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noPostData'));
- // Return
- return false;
- }
- }
- /**
- * This method runs all of the actions necessary to install
- * our plugin and use it with WordPress
- *
- * @return void
- */
- public function runInstall() {
- // Create our accounts table
- dbDelta(str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNamespace()
- ), Wc_Config::Get('sqlInstallQueries', 'createAccountsTable')));
- }
- /**
- * This method runs all of the actions necessary to uninstall
- * our plugin from WordPress
- *
- * @return void
- */
- public function runUninstall() {
- // Delete our accounts table
- dbDelta(str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNamespace()
- ), Wc_Config::Get('sqlUninstallQueries', 'dropAccountsTable')));
- }
- ////////////////////////////////////////////////////////////////////////
- ////////// Checks ///////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- /**
- * This method run a specified getter method
- * and check to see if any data was returned
- *
- * @package Checks
- * @param string $sMethod the name of the method
- * @return boolean
- */
- public function checkForData($sMethod) {
- // Store the response
- $mResponse = call_user_func(array($this, $sMethod));
- // Call the method and
- // check for returned
- // dataset
- if (empty($mResponse)) {
- // If the dataset is
- // null or unset,
- // return false
- return false;
- } else {
- // If there is data,
- // return true
- return true;
- }
- }
- /**
- * This method checks for any set errors
- * and throws an exception if an error is
- * set with the current error message as
- * the exception message
- *
- * @package Checks
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function checkForErrors() {
- // Check for an error
- if ($this->checkForData('getError')) {
- // If there is an error,
- // throw an exception
- throw new Exception($this->getError());
- }
- // Return instance
- return $this;
- }
- /**
- * This method determines if there is a
- * 180Create account stored in the local
- * WordPress database
- *
- * @package Checks
- * @return boolean
- */
- public function checkForOneightyAccount() {
- // Grab the current user
- $oUser = wp_get_current_user();
- // Query for the account
- $aAccount = $this->getDatabase()->get_results(str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}',
- '{wpId}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNamespace(),
- $oUser->ID
- ), Wc_Config::Get('sqlMiscQueries', 'retrieveOneightyAccount')));
- // Check to see if the user has
- // a 180Create account
- if (count($aAccount)) {
- // This user has an account, set
- // the system account and
- // return true
- $this->setAccount(json_decode($aAccount[0]->oAccount));
- // Return
- return true;
- } else {
- // There is no user account
- // set the system error and
- // return false
- $this->setError(Wc_Config::Get('errorMessages', 'noOneightyAccount'));
- // Return
- return false;
- }
- }
- /**
- * This method checks to see if an article
- * belongs to a currently stored account
- *
- * @return bool true for yes, false for no
- */
- public function checkIfArticleBelongsToOneightyAccount() {
- // Query for the account
- $aAccount = $this->getDatabase()->get_results(str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}',
- '{iOneightyId}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNamespace(),
- $this->getArticle()->aSyndicationData[str_replace('{nameSpace}', $this->getNameSpace(), Wc_Config::Get('wordPress', 'postMetaKeyData'))]->author_id
- ), Wc_Config::Get('sqlMiscQueries', 'retrieveOneightyAccountByOneightyId')));
- // Check to see if the
- // account array is empty
- if (empty($aAccount)) {
- // This article does not belong to
- // a currently stored account,
- // return
- return false;
- } else {
- // This article does belong to
- // a currently stored account
- // return
- return true;
- }
- }
- /**
- * This method determines if the
- * provided WordPress post ID is
- * a valid 180Create article
- *
- * @package Checks
- * @return boolean
- */
- public function checkIfOneightyArticle($iWordPressId) {
- global $wpdb;
- $iWordPressId = (int)$iWordPressId;
- //$something = get_post_meta($iWordPressId, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicated')), true);
- //if (!empty($iWordPressId) && intval($something)) {
- // Check for an article count
- $syndicated = $wpdb->get_results("SELECT mediaplace_id FROM {$wpdb->prefix}mediaplace_posts WHERE post_id = '{$iWordPressId}'");
- if (!empty($iWordPressId) && count($syndicated)) {
- // Grab the article from
- // the local database
- $oArticle = get_post($iWordPressId);
- if ($oArticle === NULL) {
- return false;
- }
- return $syndicated[0]->mediaplace_id;
- // Create the 180Create data property
- $oArticle->aSyndicationData = array();
- // Loop through each of the
- // custom meta keys and check
- // to see if they are one of
- // our meta keys
- /*
- foreach (get_post_custom_keys($iWordPressId) as $sMetaKey) {
- // Make sure it is one of ours
- if (strpos($sMetaKey, $this->getNameSpace()) !== false) {
- // It's one of ours, now
- // grab and set the value
- $oArticle->aSyndicationData[$sMetaKey] = get_post_meta($iWordPressId, $sMetaKey, true);
- }
- }
- */
- // Decode the syndication data
- //$oArticle->aSyndicationData[str_replace('{nameSpace}', $this->getNameSpace(), Wc_Config::Get('wordPress', 'postMetaKeyData'))] = json_decode($oArticle->aSyndicationData[str_replace('{nameSpace}', $this->getNameSpace(), Wc_Config::Get('wordPress', 'postMetaKeyData'))]);
- // Set the article into the system
- $this->setArticle($oArticle);
- // This is a 180Create
- // article, return true
- return true;
- } else {
- // This is not a 180Create
- // article, return false
- return false;
- }
- }
- ////////////////////////////////////////////////////////////////////////
- ////////// Load /////////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- /**
- * This method is responsible for loading the
- * menu into the WordPress admin interface
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadAdminMenu() {
- // Setup the parent menu
- add_menu_page(
- Wc_Config::Get('variables', 'appName'), // Page title
- Wc_Config::Get('variables', 'appName'), // Menu title
- 'administrator', // Permissions
- $this->getNameSpace(), // Page slug
- array($this, 'renderOneighty'), // Function to render HTML
- "{$this->getPluginWebPath()}/".Wc_Config::Get('folders', 'images')."/{$this->getNamespace()}.png" // Logo
- );
- // Setup Sub pages
- //Login/Accont
- add_submenu_page(
- $this->getNameSpace(), // Parent slug
- Wc_Config::Get('variables', 'appName'), // Page title
- ($this->checkForOneightyAccount() ? 'Account' : 'Login'), // Menu title
- 'administrator', // Permissions
- $this->getNameSpace(), // Slug
- array($this, 'renderOneighty') // Function to render HTML
- );
- // Existing Content
- add_submenu_page(
- $this->getNameSpace(), // Parent slug
- Wc_Config::Get('variables', 'appName').' Existing Content', // Page title
- 'Existing Content', // Menu title
- 'administrator', // Permissions
- $this->getNameSpace().'_existing', // Slug
- array($this, 'renderExistingContent') // Function to render HTML
- );
- // Search
- add_submenu_page(
- $this->getNameSpace(), // Parent slug
- Wc_Config::Get('variables', 'appName').' Article Search', // Page title
- 'Article Search', // Menu title
- 'administrator', // Permissions
- $this->getNameSpace().'_search', // Slug
- array($this, 'renderArticleSearch') // Function to render HTML
- );
- // Syndicated Content
- add_submenu_page(
- $this->getNameSpace(), // Parent slug
- Wc_Config::Get('variables', 'appName').' Syndicated Content', // Page title
- 'Syndicated Content', // Menu title
- 'administrator', // Permissions
- $this->getNameSpace().'_syndicated', // Slug
- array($this, 'renderSyndicatedContent') // Function to render HTML
- );
- // Logout
- add_submenu_page(
- $this->getNameSpace(), // Parent slug
- Wc_Config::Get('variables', 'appName').' Logout', // Page title
- 'Logout', // Menu title
- 'administrator', // Permissions
- $this->getNameSpace().'_logout', // Slug
- array($this, 'renderLogout') // Function to render HTML
- );
- // Return instance
- return $this;
- }
- /**
- * This method retrieves an article from the 180Create
- * table based on its associated WordPress ID
- *
- * @param integer $iWordPressId is the WordPress ID for the article
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadArticle($iWordPressId) {
- // Load the article
- $aArticles = $this->getDatabase()->get_results(str_replace(array(
- '{wpdbPrefix}',
- '{nameSpace}',
- '{wpId}'
- ), array(
- $this->getDatabase()->prefix,
- $this->getNameSpace(),
- $this->doSanitize($iWordPressId)
- ), Wc_Config::Get('sqlMiscQueries', 'retrieveOneightyArticle')));
- // Check to make sure we have
- // an article or article set
- if (count($aArticles)) {
- // Set the article into the system
- $this->setArticle(json_decode($aArticles[0]->oArticle));
- // Return true
- return true;
- } else {
- // There was no article,
- // so return false
- return false;
- }
- }
- /**
- * This method loads all of the syndicated
- * articles into the system
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadArticles() {
- // Check for a 180Create Account
- if (!$this->checkForOneightyAccount()) {
- return $this;
- }
- // Try to execute the query
- try {
- // Execute the SQL and store the results
- $aArticles = get_posts(array(
- 'post_type' => 'post',
- 'post_status' => 'publish',
- 'meta_query' => array(
- array(
- 'key' => str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicated')),
- 'value' => 1,
- 'compare' => '='
- )
- )
- ));
- // Set the articles to display
- // array placeholder
- $aDisplayArticles = array();
- // Catch all errors and exceptions
- } catch (Exception $oException) {
- // Set the system error
- $this->setError($oException->getMessage());
- // Return instance
- return $this;
- }
- // Make sure we have articles
- if (count($aArticles)) {
- // Loop through each of the articles
- // and grab the meta data from them
- foreach ($aArticles as $oArticle) {
- // Make sure this is one
- // of our articles
- if ($this->checkIfOneightyArticle($oArticle->ID) === true) {
- // Add the article to the
- // array of articles
- $aArticles[] = $this->getArticle();
- }
- }
- // Set the system articles
- $this->setArticles($aArticles);
- } else {
- // There are no articles, so
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noSyndicatedContent'));
- }
- // Return instance
- return $this;
- }
- /**
- * This method is responsible for loadin the
- * JavaScripts and Stylesheets into the system
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadAssets() {
- // Create our custom post type
- // register_post_type($this->getNamespace(), array(
- // 'publicly_queryable' => true,
- // 'exclude_from_search' => false,
- // 'show_ui' => false,
- // 'show_in_menu' => $this->getNameSpace(),
- // 'capability_type' => 'post',
- // 'show_in_nav_menus' => true,
- // 'rewrite' => true,
- // 'query_var' => true,
- // ));
- // Register the latest jQueryUI Stylesheet from Google
- wp_register_style("{$this->getNamespace()}-jquery-ui-all-css", "{$this->getPluginWebPath()}/".Wc_Config::Get('styleSheets', 'jQueryUi'));
- // Load jQueryUI Stylesheet
- wp_enqueue_style("{$this->getNamespace()}-jquery-ui-all-css");
- if (is_admin() == false) {
- // Load jQuery libraries
- wp_enqueue_script('jquery');
- // Register the latest jQueryUI Library
- wp_register_script("{$this->getNamespace()}-jquery-ui-all", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'jQueryUi'));
- // Register the latest jQueryUI Select Menu Plugin
- wp_register_script("{$this->getNamespace()}-jquery-ui-selectmenu", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'jQueryUiSelectMenu'));
- // Register the latest jQuery Validation
- // plugin from the jQuery repository
- wp_register_script("{$this->getNamespace()}-jquery-validate", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'jQueryValidate'));
- // Load our base functions
- wp_enqueue_script("{$this->getNamespace()}-base");
- // Load jQueryUI
- wp_enqueue_script("{$this->getNamespace()}-jquery-ui-all");
- // Load jQueryUi Select Menu
- wp_enqueue_script("{$this->getNamespace()}-jquery-ui-selectmenu");
- // Load jQuery Validate
- wp_enqueue_script("{$this->getNamespace()}-jquery-validate");
- // See if we are on post page
- if (!is_null(get_the_ID())) {
- if ($this->checkIfOneightyArticle(get_the_ID()) === true) {
- // Meta property
- $sMetaProperty = str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeyData'));
- // Add in our meta tags
- echo("<meta name=\"syndication-source\" content=\"{$this->getArticle()->aSyndicationData[$sMetaProperty]->from_url}\">\n");
- }
- }
- } else {
- // Register our plugin's extra styles
- wp_register_style("{$this->getNamespace()}-extra-css", "{$this->getPluginWebPath()}/".Wc_Config::Get('styleSheets', 'base'));
- // Load our plugin's extra styles
- wp_enqueue_style("{$this->getNameSpace()}-extra-css");
- // Register our base functions
- wp_register_script("{$this->getNamespace()}-base", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'base'));
- // Register the latest jQueryUI Library
- wp_register_script("{$this->getNamespace()}-jquery-ui-all", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'jQueryUi'));
- // Register the latest jQueryUI Select Menu Plugin
- wp_register_script("{$this->getNamespace()}-jquery-ui-selectmenu", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'jQueryUiSelectMenu'));
- // Register the latest jQuery Validation
- // plugin from the jQuery repository
- wp_register_script("{$this->getNamespace()}-jquery-validate", "{$this->getPluginWebPath()}/".Wc_Config::Get('javaScripts', 'jQueryValidate'));
- // Load our base functions
- wp_enqueue_script("{$this->getNamespace()}-base");
- // Load jQueryUI
- wp_enqueue_script("{$this->getNamespace()}-jquery-ui-all");
- // Load jQueryUi Select Menu
- wp_enqueue_script("{$this->getNamespace()}-jquery-ui-selectmenu");
- // Load jQuery Validate
- wp_enqueue_script("{$this->getNamespace()}-jquery-validate");
- }
- // Return instance
- return $this;
- }
- /**
- * This method load the categories from the
- * 180Create RPC server
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadCategories() {
- // Check to see if there is a user logged in
- if ($this->checkForOneightyAccount()) {
- // If there is an account, make
- // the call to the RPC server
- $this->feedJson(array(
- '_method' => 'categories',
- '_key' => $this->getAccount()->account_key
- ));
- // Check for RPC errors
- if (is_object($this->getRpcResponse()) && property_exists($this->getRpcResponse(), 'error')) {
- // If there is an error,
- // set the system error
- $this->setError($this->getRpcResponse()->error);
- // Return instance
- return $this;
- } else {
- // If there are no errors,
- // set the system categories
- $this->setCategories($this->getRpcResponse());
- // Return instance
- return $this;
- }
- } else {
- // Return instance
- return $this;
- }
- }
- /**
- * This method loads the comments from 180Create
- * into the system for the current post being viewed
- *
- * @package Load
- * @param integer $iOneightyId is the article ID
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadComments() {
- // Check to see if the user is logged in
- if ($this->checkForOneightyAccount()) {
- // If there was a 180Create account
- // load the comments from rpc
- $this->feedJson(array(
- '_method' => 'grab_comments',
- '_key' => $this->getAccount()->account_key,
- 'article_id' => $this->getArticle()->id
- ));
- // Check for RPC errors
- if (is_object($this->getRpcResponse()) && property_exists($this->getRpcResponse(), 'error')) {
- // If there is an error,
- // set the system error
- $this->setError($this->getRpcResponse()->error);
- // Return instance
- return $this;
- } else {
- // If there are no errors,
- // check to see if we have
- // any comments
- if (count($this->getRpcResponse())) {
- // If so, set them into the system
- $this->setComments($this->getRpcResponse());
- } else {
- // If not, return an error
- $this->setError(Wc_Config::Get('errorMessages', 'noCommentsFound'));
- }
- // Return instance
- return $this;
- }
- } else {
- // Return instance
- return $this;
- }
- }
- /**
- * This method loads the current stored account's
- * groups from 180Create into the system
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadGroups() {
- // Check for user account
- if ($this->checkForData('getAccount')) {
- // We have a user account,
- // now make the call to the
- // RPC server for the groups
- $this->feedJson(array(
- '_method' => 'groups',
- '_key' => $this->doSanitize($this->getAccount()->account_key),
- 'user_id' => $this->doSanitize($this->getAccount()->id)
- ));
- // Check for JSON-RPC server errors
- if (is_object($this->getRpcResponse()) && property_exists($this->getRpcResponse(), 'error')) {
- // Check to see that we have
- // actual results
- if (is_array($this->getRpcResponse()) && count($this->getRpcResponse())) {
- // We have results, now
- // set the groups into
- // the system
- $this->setGroups($this->getRpcResponse());
- // Return instance
- return $this;
- } else {
- // No groups were found,
- // set the system notification
- $this->setError(Wc_Config::Get('notificationMessages', 'noGroupsFound'));
- // Return instance
- return $this;
- }
- // An error is present
- } else {
- // Set the system error
- $this->setError($this->getRpcResponse()->error);
- // Return false because there
- // was an error from the JSON
- // RPC server
- return $this;
- }
- } else {
- // Return false because
- // we have not categories
- return $this;
- }
- }
- /**
- * This method loads our custom meta box
- * into the WordPress interface
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadMetaBox() {
- if (function_exists('add_meta_box')) {
- // Add the meta_box to the system
- add_meta_box("{$this->getNamespace()}-post-meta-box", __(Wc_Config::Get('variables', 'appName').' Article Details', "{$this->getNameSpace()}-post-meta-box"), array($this, 'renderMetaBox'), 'post', 'side', 'high');
- }
- }
- /**
- * This method loads all of the posts
- * from the local WordPress DB
- * into the system
- *
- * @package Load
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadPosts() {
- // Load the WordPress posts
- // into the system
- $aPosts = get_posts(array(
- 'post_type' => 'post',
- 'post_status' => 'publish'
- ));
- // Indices to remove array
- $aIndices = array();
- // Loop through the posts,
- // weeding out the ones
- // that are ours
- for ($iPost = 0; $iPost < count($aPosts); $iPost ++) {
- // Check to see if the post is ours
- if (get_post_meta($aPosts[$iPost]->ID, str_replace('{nameSpace}', $this->getNamespace(), Wc_Config::Get('wordPress', 'postMetaKeySyndicated')))) {
- // Add the index to the posts to remove
- $aIndices[] = $iPost;
- }
- }
- // Loop through the indices
- // and unset them
- foreach ($aIndices as $iIndex) {
- // Unset the index
- unset($aPosts[$iIndex]);
- }
- // Set the posts into the system
- $this->setPosts($aPosts);
- // Return instance
- return $this;
- }
- /**
- * This method loads the subcategories
- * from the 180Create RPC server
- *
- * @package Load
- * @param integer $iCategoryId is the ID of the parent Category
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadSubcategories($iCategoryId) {
- // Check to see if there is a user logged in
- if ($this->checkForOneightyAccount()) {
- // If there is an account, make
- // the call to the RPC server
- $this->feedJson(array(
- '_method' => 'subcategories',
- '_key' => $this->getAccount()->account_key,
- 'category_id' => $this->doSanitize($iCategoryId)
- ));
- // Check for RPC errors
- if (is_object($this->getRpcResponse()) && property_exists($this->getRpcResponse(), 'error')) {
- // If there is an error,
- // set the system error
- $this->setError($this->getRpcResponse()->error);
- // Return instance
- return $this;
- } else {
- // If there are no errors,
- // set the system categories
- $this->setSubcategories($this->getRpcResponse());
- // Return instance
- return $this;
- }
- } else {
- // If there is no account,
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'noOneightyAccount'));
- // Return instance
- return $this;
- }
- }
- /**
- * This method loads and renders a template file.
- * The scope of the template file is that of @var $this
- *
- * @package Load
- * @param string $sTemplateFile is the name of the template file
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function loadTemplate($sTemplateName) {
- // Make sure a template file was
- // actually specified
- if (is_null($sTemplateName)) {
- // If not set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'nullTemplateFile'));
- } else {
- // Set full filename
- $sTemplateFile = (string) $this->getPluginPath().'/'.Wc_Config::Get('folders', 'templates').'/'.$sTemplateName.'.tpl';
- // Check to see if the file exists
- if (!include_once($sTemplateFile)) {
- // If the file doesn't exist,
- // set the system error
- $this->setError(Wc_Config::Get('errorMessages', 'templateFileNoExist'));
- if ($sTemplateName != 'error')
- // Load error template
- $this->loadTemplate("error");
- }
- }
- return $this;
- }
- ////////////////////////////////////////////////////////////////////////
- ////////// Render ///////////////////////////////////////////
- //////////////////////////////////////////////////////////////////////
- /**
- * This method is responsible for rendering
- * the article search form and results
- *
- * @package Render
- * @return Wc_Actions $this for a fluid and chain-loadable interface
- */
- public function renderArticleSearch() {
- // Check for POST data
- if ($this->checkForData('getPostData') && property_exists($this->getPostData(), $this->getNamespace())) {
- // If a form has been submitted
- // run the search actions
- $this->doSearch();
- }
- // Check to see if there is a 180Create
- // account stored in the local DB
- if ($this->checkForOneightyAccount()) {
- // If so, load our template
- // for logged in users
- $this->loadTemplate("search");
- } else {
- // No account is there, load our
- // template for non-log