PageRenderTime 55ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/inc/cron.php

https://bitbucket.org/ryanhowdy/family-connections
PHP | 426 lines | 293 code | 64 blank | 69 comment | 35 complexity | b70ab5203e4949571cb22d00ed19627d MD5 | raw file
Possible License(s): Apache-2.0, GPL-2.0
  1. <?php
  2. /**
  3. * Cron
  4. *
  5. * Helper functions for the FCMS Scheduler.
  6. *
  7. * PHP versions 4 and 5
  8. *
  9. * @category FCMS
  10. * @package FamilyConnections
  11. * @author Ryan Haudenschilt <r.haudenschilt@gmail.com>
  12. * @copyright 2011 Haudenschilt LLC
  13. * @license http://www.gnu.org/licenses/gpl-2.0.html GPLv2
  14. * @link http://www.familycms.com/wiki/
  15. * @since 2.6
  16. */
  17. /**
  18. * runAwardsJob
  19. *
  20. * @return void
  21. */
  22. function runAwardsJob ()
  23. {
  24. include_once 'awards_class.php';
  25. $awards = new Awards(1);
  26. if (!$awards->calculateMonthlyAwards())
  27. {
  28. logError(__FILE__.' ['.__LINE__.'] - Could not calculate monthly awards.');
  29. die();
  30. }
  31. if (!$awards->calculateAchievementAwards())
  32. {
  33. logError(__FILE__.' ['.__LINE__.'] - Could not calculate achievement awards.');
  34. die();
  35. }
  36. // Update date we last ran this job
  37. updateLastRun(date('Y-m-d H:i:s'), 'awards');
  38. }
  39. /**
  40. * runFamilyNewsJob
  41. *
  42. * Checks if any user has an external blog setup.
  43. * Imports posts from those blogs if they haven't been imported already.
  44. *
  45. * @return void
  46. */
  47. function runFamilyNewsJob ()
  48. {
  49. include_once 'familynews_class.php';
  50. $newsObj = new FamilyNews(1);
  51. // Get date we last checked for external news
  52. $sql = "SELECT `value` AS 'external_news_date'
  53. FROM `fcms_config`
  54. WHERE `name` = 'external_news_date'
  55. LIMIT 1";
  56. $result = mysql_query($sql);
  57. if (!$result)
  58. {
  59. logError(__FILE__.' ['.__LINE__.'] - Could not get external_news_date.');
  60. die();
  61. }
  62. $r = mysql_fetch_assoc($result);
  63. $last_checked = strtotime($r['external_news_date']);
  64. // RFC 3339 format
  65. $atomDate = 0;
  66. if (!empty($r['external_news_date']))
  67. {
  68. $atomDate = date('Y-m-d\TH:i:s\Z', strtotime($r['external_news_date']));
  69. }
  70. // Get import blog settings
  71. $sql = "SELECT `user`, `blogger`, `tumblr`, `wordpress`, `posterous`
  72. FROM `fcms_user_settings`";
  73. $result = mysql_query($sql);
  74. if (!$result)
  75. {
  76. logError(__FILE__.' ['.__LINE__.'] - Could not get blog settings.');
  77. die();
  78. }
  79. if (mysql_num_rows($result) <= 0)
  80. {
  81. if (debugOn())
  82. {
  83. logError(__FILE__.' ['.__LINE__.'] - No blog settings found.');
  84. }
  85. updateLastRun(date('Y-m-d H:i:s'), 'familynews');
  86. die();
  87. }
  88. $external_ids = $newsObj->getExternalPostIds();
  89. while ($r = mysql_fetch_assoc($result))
  90. {
  91. // Blogger
  92. if (!empty($r['blogger']))
  93. {
  94. $ret = $newsObj->importBloggerPosts($r['blogger'], $r['user'], $atomDate, $external_ids);
  95. if ($ret === false)
  96. {
  97. if (debugOn())
  98. {
  99. logError(__FILE__.' ['.__LINE__.'] - No posts to import from blogger for user ['.$r['user'].'].');
  100. }
  101. continue;
  102. }
  103. }
  104. // Tumblr
  105. if (!empty($r['tumblr']))
  106. {
  107. $ret = $newsObj->importTumblrPosts($r['tumblr'], $r['user'], $atomDate, $external_ids);
  108. if ($ret === false)
  109. {
  110. if (debugOn())
  111. {
  112. logError(__FILE__.' ['.__LINE__.'] - No posts to import from tumblr for user ['.$r['user'].'].');
  113. }
  114. continue;
  115. }
  116. }
  117. // Wordpress
  118. if (!empty($r['wordpress']))
  119. {
  120. $ret = $newsObj->importWordpressPosts($r['wordpress'], $r['user'], $atomDate, $external_ids);
  121. if ($ret === false)
  122. {
  123. if (debugOn())
  124. {
  125. logError(__FILE__.' ['.__LINE__.'] - No posts to import from wordpress for user ['.$r['user'].'].');
  126. }
  127. continue;
  128. }
  129. }
  130. // Posterous
  131. if (!empty($r['posterous']))
  132. {
  133. $ret = $newsObj->importPosterousPosts($r['posterous'], $r['user'], $atomDate, $external_ids);
  134. if ($ret === false)
  135. {
  136. if (debugOn())
  137. {
  138. logError(__FILE__.' ['.__LINE__.'] - No posts to import from posterous for user ['.$r['user'].'].');
  139. }
  140. continue;
  141. }
  142. }
  143. }
  144. // Update date we last imported news
  145. $now = date('Y-m-d H:i:s');
  146. $sql = "UPDATE `fcms_config`
  147. SET `value` = '$now'
  148. WHERE `name` = 'external_news_date'";
  149. if (!mysql_query($sql))
  150. {
  151. logError(__FILE__.' ['.__LINE__.'] - Could not update last imported news date.');
  152. die();
  153. }
  154. // Update date we last ran this job
  155. updateLastRun($now, 'familynews');
  156. }
  157. /**
  158. * runYouTubeJob
  159. *
  160. * Imports YouTube videos.
  161. *
  162. * @return void
  163. */
  164. function runYouTubeJob ()
  165. {
  166. global $file;
  167. require_once "constants.php";
  168. require_once "socialmedia.php";
  169. require_once "datetime.php";
  170. require_once THIRDPARTY."gettext.inc";
  171. set_include_path(THIRDPARTY);
  172. require_once 'Zend/Loader.php';
  173. Zend_Loader::loadClass('Zend_Gdata_YouTube');
  174. Zend_Loader::loadClass('Zend_Gdata_AuthSub');
  175. Zend_Loader::loadClass('Zend_Gdata_App_Exception');
  176. $existingIds = getExistingYouTubeIds();
  177. // Get user's session tokens
  178. $sql = "SELECT u.`id`, s.`youtube_session_token`
  179. FROM `fcms_user_settings` AS s, `fcms_users` AS u
  180. WHERE s.`user` = u.`id`
  181. AND s.`youtube_session_token` IS NOT NULL";
  182. $result = mysql_query($sql);
  183. if (!$result)
  184. {
  185. logError(__FILE__.' ['.__LINE__.'] - Could not get youtube tokens.');
  186. die();
  187. }
  188. $sessionTokens = array();
  189. while ($row = mysql_fetch_assoc($result))
  190. {
  191. $sessionTokens[$row['id']] = $row['youtube_session_token'];
  192. }
  193. $youtubeConfig = getYouTubeConfigData();
  194. // Get videos for each user
  195. foreach ($sessionTokens as $userId => $token)
  196. {
  197. // Setup youtube api
  198. $httpClient = getAuthSubHttpClient($youtubeConfig['youtube_key'], $token);
  199. $youTubeService = new Zend_Gdata_YouTube($httpClient);
  200. $feed = $youTubeService->getUserUploads('default');
  201. $values = '';
  202. $videoCount = 0;
  203. foreach ($feed as $entry)
  204. {
  205. $id = $entry->getVideoId();
  206. if (isset($existingIds[$id]))
  207. {
  208. if (debugOn())
  209. {
  210. logError(__FILE__.' ['.__LINE__.'] - Video ['.$id.'] for user ['.$userId.'] already imported.');
  211. }
  212. continue;
  213. }
  214. $title = htmlspecialchars($entry->getVideoTitle());
  215. $description = htmlspecialchars($entry->getVideoDescription());
  216. $created = formatDate('Y-m-d H:i:s', $entry->published);
  217. $duration = $entry->getVideoDuration();
  218. $height = '420';
  219. $width = '780';
  220. $thumbs = $entry->getVideoThumbnails();
  221. if (count($thumbs) > 0)
  222. {
  223. $height = $thumbs[0]['height'];
  224. $width = $thumbs[0]['width'];
  225. }
  226. $title = escape_string($title);
  227. $description = escape_string($description);
  228. $values .= "('$id', '$title', '$description', 'youtube', '$height', '$width', '$created', '$userId', NOW(), '$userId'),";
  229. $videoCount++;
  230. }
  231. if ($videoCount > 0)
  232. {
  233. $values = substr($values, 0, -1); // remove comma
  234. $sql = "INSERT INTO `fcms_video` (`source_id`, `title`, `description`, `source`, `height`, `width`, `created`, `created_id`, `updated`, `updated_id`)
  235. VALUES $values";
  236. if (!mysql_query($sql))
  237. {
  238. logError(__FILE__.' ['.__LINE__.'] - Could not insert new video to db.');
  239. die();
  240. }
  241. }
  242. }
  243. // Update date we last ran this job
  244. updateLastRun(date('Y-m-d H:i:s'), 'youtube');
  245. }
  246. /**
  247. * runInstagramJob
  248. *
  249. * @return void
  250. */
  251. function runInstagramJob ()
  252. {
  253. require_once 'inc/config_inc.php';
  254. require_once 'inc/constants.php';
  255. require_once 'inc/socialmedia.php';
  256. require_once 'inc/utils.php';
  257. require_once THIRDPARTY.'gettext.inc';
  258. require_once THIRDPARTY.'Instagram.php';
  259. global $cfg_mysql_host, $cfg_mysql_user, $cfg_mysql_pass, $cfg_mysql_db;
  260. $connection = mysql_connect($cfg_mysql_host, $cfg_mysql_user, $cfg_mysql_pass);
  261. mysql_select_db($cfg_mysql_db);
  262. if (!mysql_query("SET NAMES 'utf8'"))
  263. {
  264. logError(__FILE__.' ['.__LINE__.'] - Could not set names utf8.');
  265. die();
  266. }
  267. // Get user's access tokens
  268. $sql = "SELECT u.`id`, s.`instagram_access_token`
  269. FROM `fcms_user_settings` AS s, `fcms_users` AS u
  270. WHERE s.`user` = u.`id`
  271. AND s.`instagram_auto_upload` = 1
  272. AND s.`instagram_access_token` IS NOT NULL";
  273. $result = mysql_query($sql);
  274. if (!$result)
  275. {
  276. logError(__FILE__.' ['.__LINE__.'] - Could not get instagram access tokens.');
  277. die();
  278. }
  279. $accessTokens = array();
  280. while ($row = mysql_fetch_assoc($result))
  281. {
  282. $accessTokens[$row['id']] = $row['instagram_access_token'];
  283. }
  284. $config = getInstagramConfigData();
  285. $existingIds = getExistingInstagramIds();
  286. // Get pics for each user
  287. foreach ($accessTokens as $userId => $token)
  288. {
  289. $categoryId = getUserInstagramCategory($userId);
  290. $instagram = new Instagram($config['instagram_client_id'], $config['instagram_client_secret'], $token);
  291. try
  292. {
  293. $feed = $instagram->get('users/self/media/recent');
  294. }
  295. catch (InstagramApiError $e)
  296. {
  297. logError(__FILE__.' ['.__LINE__.'] - Could not get user instagram data. - '.$e->getMessage());
  298. die();
  299. }
  300. $sql = "INSERT INTO `fcms_gallery_photos`
  301. (`date`, `path`, `caption`, `category`, `user`)
  302. VALUES ";
  303. foreach ($feed->data as $photo)
  304. {
  305. $sourceId = $photo->id;
  306. $thumbnail = $photo->images->thumbnail->url;
  307. $medium = $photo->images->low_resolution->url;
  308. $full = $photo->images->standard_resolution->url;
  309. $caption = sprintf(T_('Imported from Instagram. Filter: %s.'), $photo->filter);
  310. // Skip existing photos
  311. if (isset($existingIds[$sourceId]))
  312. {
  313. continue;
  314. }
  315. // Save external paths
  316. $sql = "INSERT INTO `fcms_gallery_external_photo`
  317. (`source_id`, `thumbnail`, `medium`, `full`)
  318. VALUES
  319. ('$sourceId', '$thumbnail', '$medium', '$full')";
  320. $result = mysql_query($sql);
  321. if (!$result)
  322. {
  323. logError(__FILE__.' ['.__LINE__.'] - Could not save external photos.');
  324. die();
  325. }
  326. $id = mysql_insert_id();
  327. // Insert new photo
  328. $sql = "INSERT INTO `fcms_gallery_photos`
  329. (`date`, `external_id`, `caption`, `category`, `user`)
  330. VALUES
  331. (NOW(), '$id', '$caption', '$categoryId', '$userId')";
  332. $result = mysql_query($sql);
  333. if (!$result)
  334. {
  335. logError(__FILE__.' ['.__LINE__.'] - Could not insert new photo.');
  336. die();
  337. }
  338. }
  339. }
  340. // Update date we last ran this job
  341. updateLastRun(date('Y-m-d H:i:s'), 'instagram');
  342. }
  343. /**
  344. * updateLastRun
  345. *
  346. * @param date $now
  347. * @param string $type
  348. *
  349. * @return void
  350. */
  351. function updateLastRun ($now, $type)
  352. {
  353. // Update date we last ran this job
  354. $sql = "UPDATE `fcms_schedule`
  355. SET `lastrun` = '$now'
  356. WHERE `type` = '$type'";
  357. if (!mysql_query($sql))
  358. {
  359. logError(__FILE__.' ['.__LINE__.'] - Could not update last run date for '.$type.' job.');
  360. die();
  361. }
  362. }