PageRenderTime 62ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/wordpress-flash-uploader/inc/wfu-sync.php

https://bitbucket.org/sidi09/aryans
PHP | 511 lines | 415 code | 43 blank | 53 comment | 93 complexity | a11c05c5cfa7a4ba12fe843ff94a6ae5 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-3.0, GPL-2.0
  1. <?php
  2. /**
  3. * Wordpress Flash uploader 2.14.x
  4. *
  5. * This file contains the methods used by the synch part from the WFU class
  6. *
  7. * Copyright (c) 2004-2011 TinyWebGallery
  8. * Author: Michael Dempfle
  9. * Author URI: http://www.tinywebgallery.com
  10. */
  11. if (!class_exists("WFUSync")) {
  12. class WFUSync {
  13. function printSync($devOptions, $istab) {
  14. // now we check all possible actions if the correct nonce is set.
  15. if (isset($_POST['synchronize_media_library']) || isset($_POST['clean_media_library']) || isset($_GET['clean_media_library']) ) {
  16. $nonce=$_POST['wfunonce'];
  17. if (! wp_verify_nonce($nonce, 'wfu-nonce') ) die('Security check failed!');
  18. }
  19. // nounce is set porperly - we continue...
  20. echo '<div class="wrap wfupadding">';
  21. $nonce= wp_create_nonce ('wfu-nonce');
  22. echo '<form method="post" action="'. $_SERVER["REQUEST_URI"] . '">';
  23. echo '<input type="hidden" name="wfunonce" value="'.$nonce.'">';
  24. // this is printed first to get a header while generating thumbnails.
  25. echo '<div id="icon-upload" class="icon_jfu"><br></div>
  26. <h2>Synchronize Media Library</h2>';
  27. flush();
  28. $mlf = WFUSync::getMediaLibraryFiles();
  29. $uff = WFUSync::getUploadFolderFiles('../' . WFUSync::getUploadPath());
  30. $enable_sych = ($uff !== false);
  31. if (!$enable_sych) {
  32. $uff = array();
  33. }
  34. $mfo = WFUSync::getMediaLibraryOnly($mlf);
  35. $fuo = WFUSync::findUploadOnly($mlf, $uff);
  36. if (isset($_POST['synchronize_media_library']) || isset($_POST['clean_media_library']) || isset($_GET['clean_media_library']) ||
  37. isset($_POST['synchronize_media_library']) || isset($_POST['import_media_library']) || isset($_GET['import_media_library'])) {
  38. echo '<script type="text/javascript">
  39. if (window.parent.frames[window.name] && (parent.document.getElementsByTagName(\'frameset\').length <= 0)) {
  40. window.parent.document.getElementById("status_text").innerHTML = "Starting synchronisation.";
  41. }</script>';
  42. }
  43. if (isset($_POST['synchronize_media_library']) || isset($_POST['clean_media_library']) || isset($_GET['clean_media_library'])) {
  44. // we remove the ones tat are not in the upload folder anymore.
  45. echo '<div class="updated"><p><strong>';
  46. if (count($mfo) > 0) {
  47. foreach($mfo as $item) {
  48. if ($item->type == 'main') {
  49. wp_delete_post($item->post_id);
  50. } else { // metadata stuff! we update the database table!
  51. $data = $item->data;
  52. wp_update_attachment_metadata($item->post_id, $data);
  53. }
  54. }
  55. echo _e("Invalid media library entries where removed.", "WFU");
  56. } else {
  57. echo _e("No invalid media library entries found.", "WFU");
  58. }
  59. echo '</strong></p></div>';
  60. }
  61. if (isset($_POST['synchronize_media_library'])
  62. || isset($_POST['import_media_library']) || isset($_GET['import_media_library'])) {
  63. $sum = count ($fuo);
  64. $current = 0;
  65. foreach($fuo as $item) {
  66. $current++;
  67. if( !ini_get('safe_mode') ){
  68. @set_time_limit(30);
  69. }
  70. WFUSync::handle_import_file($item, $current, $sum);
  71. }
  72. echo '<div class="updated"><p><strong>';
  73. if ($current > 0) {
  74. echo _e("Files imported to media library.", "WFU");
  75. } else {
  76. echo _e("No files found which are not already in the media library.", "WFU");
  77. }
  78. echo '</strong></p></div>';
  79. }
  80. echo '<script type="text/javascript">
  81. if (window.parent.frames[window.name] && (parent.document.getElementsByTagName(\'frameset\').length <= 0)) {
  82. window.parent.document.getElementById("status_text").innerHTML = "Synchronisation finished.";
  83. if (window.parent.refreshFileList) {
  84. window.parent.refreshFileList();
  85. }
  86. }</script>';
  87. if (isset($_POST['synchronize_media_library'])
  88. || isset($_POST['clean_media_library'])
  89. || isset($_POST['import_media_library'])) {
  90. // we reload the data.
  91. $mlf = WFUSync::getMediaLibraryFiles();
  92. $uff = WFUSync::getUploadFolderFiles('../' . WFUSync::getUploadPath());
  93. if (!$enable_sych) {
  94. $uff = array();
  95. }
  96. $mfo = WFUSync::getMediaLibraryOnly($mlf);
  97. $fuo = WFUSync::findUploadOnly($mlf, $uff);
  98. }
  99. $count_mfo = 0;
  100. foreach($mfo as $item) {
  101. if ( $item->type == 'main') $count_mfo++;
  102. }
  103. $nr_ok = count($mlf) - $count_mfo;
  104. if ($enable_sych) {
  105. echo '
  106. <p>
  107. If you upload files by WFU or FTP or by any other tool than the internal uploader of Wordpress the files do not get listed in the media library.
  108. <div class="wfu_reg">
  109. ';
  110. if (!$istab) {
  111. echo '
  112. <p><b>Import files to Media Library:</b> All files below the "'.WFUSync::getUploadPath().'" folder are checked if they do already exist in the media library. If they don\'t exist they are entered and can be managed in the media library. Image exif/iptc data are used as defaults for title and caption if possible.</p>
  113. <p><b>Remove invalid Media Library entries:</b> The database is checked if all files still exist. Data of deleted files (link, title, caption ...) are removed from the media library.</p>
  114. <p><b>Synchronize Media Library:</b> Import and Remove.</p>
  115. ';
  116. }
  117. echo '
  118. <div class="submit">';
  119. if (!$istab) {
  120. echo '
  121. <input type="submit" name="synchronize_media_library" value="';
  122. echo _e('Synchronize Media Library', 'WFU');
  123. echo '" />';
  124. }
  125. echo '
  126. <input type="submit" name="import_media_library" value="';
  127. echo _e('Import files to Media Library', 'WFU');
  128. echo '" />';
  129. if (!$istab) {
  130. echo '
  131. <input type="submit" name="clean_media_library" value="';
  132. echo _e('Remove invalid Media Library entries', 'WFU');
  133. echo '" />';
  134. }
  135. echo '</div>';
  136. echo '<h3>Current status</h3>';
  137. echo '<table><tr valign="top"><td>Files in upload folder and media library<br>which are in sync.<br>&nbsp;<br></td><td style="padding-left:20px;">'.$nr_ok.'<br>&nbsp;</td><td> </td></tr>
  138. <tr valign="top"><td>Files only in upload folder</td><td style="padding-left:20px;">'.count($fuo) . '</td><td style="padding-left:20px;">';
  139. foreach($fuo as $item) {
  140. echo htmlentities(WFUSync::stripAboveUpload($item)) . '<br>';
  141. }
  142. echo '&nbsp;';
  143. echo '</td></tr>
  144. <tr valign="top"><td>Files only in media library</td><td style="padding-left:20px;">'.count($mfo) . '</td><td style="padding-left:20px;">';
  145. foreach($mfo as $item) {
  146. echo htmlentities(WFUSync::stripAboveUpload($item->meta_value)) . (($item->type == 'main') ? '': ' <span style="color:#666;"><small>('.$item->type.')</small></span>') .'<br>';
  147. }
  148. echo '&nbsp;';
  149. echo '</td></tr>
  150. </table></form>';
  151. echo '<br>';
  152. echo '<div class="howto"><small>* Please note: The numbers are always the number of original images.<br>Thumbnails, medium and large images are not counted here but they are synchronized as well.<br>Not existing thumbnails, medium and large images are removed from the meta data of the image.</small></div>';
  153. echo '</div>';
  154. if (!$istab && $devOptions['hide_donate'] == 'false') {
  155. echo '
  156. <br>&nbsp;
  157. <table><tr><td>You like this plugin? Support the development with a small donation. </td><td>&nbsp;&nbsp;&nbsp;<A target="_blank" HREF="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=paypal%40mdempfle%2ede&item_name=WP%20Flash%20Uploader&item_number=Support%20Open%20Source&no_shipping=0&no_note=1&tax=0&currency_code=EUR&lc=EN&bn=PP%2dDonationsBF&charset=UTF%2d8"><img src="../wp-content/plugins/wordpress-flash-uploader/img/btn_donate_SM.gif"></A></td></tr></table>
  158. ';
  159. }
  160. }
  161. }
  162. function stripAboveUpload($str) {
  163. $str = str_replace("\\","/",$str);
  164. if (stristr($str, WFUSync::getUploadPath()) === false) {
  165. return $str;
  166. } else {
  167. $pos = stripos($str, WFUSync::getUploadPath() . '/');
  168. return substr($str, $pos + strlen(WFUSync::getUploadPath())+1);
  169. }
  170. }
  171. /*
  172. function stripAboveUpload($str) {
  173. $str = str_replace("\\","/",$str);
  174. if (stristr($str, 'uploads') === false) {
  175. return $str;
  176. } else {
  177. $pos = stripos($str, 'uploads/');
  178. return substr($str, $pos + 8);
  179. }
  180. }
  181. */
  182. function stripAfterUpload($str) {
  183. echo $str . "<br>";
  184. $str = str_replace("\\","/",$str);
  185. $pos = stripos($str, WFUSync::getUploadPath() . '/');
  186. $str = substr($str, $pos + strlen(WFUSync::getUploadPath())+1);
  187. /* $str = stristr($str, WFUSync::getUploadPath());
  188. echo $str . "<br>";
  189. $str = substr(stristr($str, '/'),1);
  190. echo $str . "<br>";
  191. */
  192. echo $str . "<br>";
  193. return $str;
  194. }
  195. /*
  196. function stripAfterUpload($str) {
  197. echo $str . "<br>";
  198. $str = str_replace("\\","/",$str);
  199. $str = stristr($str, 'uploads');
  200. echo $str . "<br>";
  201. $str = substr(stristr($str, '/'),1);
  202. echo $str . "<br>";
  203. return $str;
  204. }
  205. */
  206. function getMediaLibraryFiles() {
  207. global $wpdb;
  208. $sql= "SELECT pm.post_id, pm.meta_id, pm.meta_value, pma.meta_value as meta_att FROM $wpdb->posts p,$wpdb->postmeta pm, $wpdb->postmeta pma WHERE pm.post_id=p.id and pma.post_id=pm.post_id and p.post_type = 'attachment' and pm.meta_key='_wp_attached_file' and pm.meta_value <> pma.meta_value order by pm.meta_value ";
  209. $mlf = $wpdb->get_results( $sql );
  210. return $mlf;
  211. }
  212. function getUploadFolderFiles( $from = '../wp-content/uploads') {
  213. if(!is_dir($from)) {
  214. echo '<div class="updated"><p><strong>';
  215. echo _e("Upload folder does not exist yet. Please upload at least one file.", "WFU");
  216. echo '</strong></p></div>';
  217. return false;
  218. }
  219. $files = array();
  220. $dirs = array( $from);
  221. while( NULL !== ($dir = array_pop( $dirs)))
  222. {
  223. if( $dh = opendir($dir))
  224. {
  225. while( false !== ($file = readdir($dh)))
  226. {
  227. if( $file == '.' || $file == '..')
  228. continue;
  229. $path = $dir . '/' . $file;
  230. if( is_dir($path))
  231. $dirs[] = $path;
  232. else
  233. $files[] = $path;
  234. }
  235. closedir($dh);
  236. }
  237. }
  238. return $files;
  239. }
  240. function getMediaLibraryOnly($mlf) {
  241. $mfo = array();
  242. foreach($mlf as $item) {
  243. $main = false;
  244. // echo $item->meta_value . '<br>';
  245. // files have either a full path or the relative path in the uploads folder.
  246. if (!file_exists($item->meta_value) && !file_exists('../' . WFUSync::getUploadPath() . '/' . $item->meta_value)) {
  247. $item->type = 'main';
  248. $main = true;
  249. $mfo[] = $item;
  250. }
  251. if (!$main) { // we check the meta data if the main image is o.k.
  252. $data = unserialize($item->meta_att);
  253. // todo - check for thumbnails
  254. $base = dirname($data['file']);
  255. if (isset($data['sizes'])) {
  256. if (isset($data['sizes']['thumbnail']) && isset($data['sizes']['thumbnail']['file'])) {
  257. $thumbnail = $base . '/' . $data['sizes']['thumbnail']['file'];
  258. if (!file_exists($thumbnail) && !file_exists('../'.WFUSync::getUploadPath().'/' . $thumbnail)) {
  259. unset($error);
  260. $error->meta_value = $thumbnail;
  261. $error->type = 'thumbnail';
  262. $error->post_id = $item->post_id;
  263. unset($data['sizes']['thumbnail']);
  264. $error->data = $data;
  265. $mfo[] = $error;
  266. }
  267. }
  268. if (isset($data['sizes']['medium']) && isset($data['sizes']['medium']['file'])) {
  269. $medium = $base . '/' . $data['sizes']['medium']['file'];
  270. if (!file_exists($medium) && !file_exists('../'.WFUSync::getUploadPath().'/' . $medium)) {
  271. unset($error);
  272. $error->meta_value = $medium;
  273. $error->type = 'medium';
  274. $error->post_id = $item->post_id;
  275. unset($data['sizes']['medium']);
  276. $error->data = $data;
  277. $mfo[] = $error;
  278. }
  279. }
  280. if (isset($data['sizes']['large']) && isset($data['sizes']['large']['file'])) {
  281. $large = $base . '/' . $data['sizes']['large']['file'];
  282. if (!file_exists($medium) && !file_exists('../'.WFUSync::getUploadPath().'/' . $large)) {
  283. unset($error);
  284. $error->meta_value = $large;
  285. $error->type = 'large';
  286. $error->post_id = $item->post_id;
  287. unset($data['sizes']['large']);
  288. $error->data = $data;
  289. $mfo[] = $error;
  290. }
  291. }
  292. }
  293. }
  294. }
  295. return $mfo;
  296. }
  297. function findUploadOnly($media, $filesystem) {
  298. $fuo = array();
  299. $wfuOptions = $this->getAdminOptions();
  300. foreach($filesystem as $fitem) {
  301. $found = false;
  302. foreach($media as $item) {
  303. $v1 = realpath('../'.WFUSync::getUploadPath().'/' . $item->meta_value);
  304. // echo $v1 . "<br>";
  305. $v2 = realpath($item->meta_value);
  306. $v3 = ($v1) ? $v1:$v2;
  307. if (realpath($fitem) == $v3) {
  308. // echo "found";
  309. $found = true;
  310. break; // we have found this element - we search the next one.
  311. }
  312. $base = dirname($v3);
  313. // now we check the metadata
  314. $data = unserialize($item->meta_att);
  315. if (isset($data['sizes']) && isset($data['sizes']['thumbnail']) && isset($data['sizes']['thumbnail']['file'])) {
  316. $thumbnail = realpath($base . '/' . $data['sizes']['thumbnail']['file']);
  317. if (realpath($fitem) == $thumbnail) { $found = true; break; }
  318. }
  319. if (isset($data['sizes']) && isset($data['sizes']['medium']) && isset($data['sizes']['medium']['file'])) {
  320. $medium = realpath($base . '/' . $data['sizes']['medium']['file']);
  321. if (realpath($fitem) == $medium) { $found = true; break; }
  322. }
  323. if (isset($data['sizes']) && isset($data['sizes']['large']) && isset($data['sizes']['large']['file'])) {
  324. $large = realpath($base . '/' . $data['sizes']['large']['file']);
  325. if (realpath($fitem) == $large) { $found = true; break; }
  326. }
  327. }
  328. if (!$found) {
  329. $add = true;
  330. if ($wfuOptions['detect_resized'] == "true") {
  331. foreach($filesystem as $itemcomp) {
  332. // we check if the file is maybe already a crunched file and if yes we ignore it
  333. // the detection is very basic - I check the file name and if another one has
  334. // the same filename with a - as next character we ignore it.
  335. if (strlen($fitem) > strlen($itemcomp)) { // we check if it is longer
  336. $c1 = WFUSync::removeExtension($itemcomp) . '-';
  337. $c2 = substr($fitem,0,strlen($c1));
  338. if ($c1 == $c2) {
  339. $add = false;
  340. }
  341. }
  342. }
  343. }
  344. if ($add) {
  345. $fuo[] = realpath($fitem);
  346. }
  347. }
  348. }
  349. return $fuo;
  350. }
  351. //Handle an individual file import. This function is based on the one from add-from-server
  352. function handle_import_file($file, $current, $sum, $post_id = 0) {
  353. $post_id = isset($_REQUEST['post_id']) ? intval($_REQUEST['post_id']) : 0;
  354. $file = str_replace('\\', '/',$file);
  355. // we have to replace special characters because wordpress does not handle them properly.
  356. $filenorm = WFUSync::normalizeFileNames($file);
  357. if (rename ($file, $filenorm)) {
  358. $file = $filenorm;
  359. }
  360. // $path = WFUSync::stripAfterUpload($file);
  361. $path = WFUSync::stripAboveUpload($file);
  362. $time = current_time('mysql');
  363. $uploads = wp_upload_dir();
  364. $wp_filetype = wp_check_filetype( $file, null );
  365. extract( $wp_filetype );
  366. $filename = basename($file);
  367. $new_file = $path;
  368. $url = $uploads['baseurl'] . '/' . $path;
  369. // get the right time.
  370. // it it is in an folder with date we use this one
  371. // if not we use the current time
  372. // the handling if it can from a post has to be handled in the flash implementation!
  373. $time = current_time('mysql');
  374. if ( $post = get_post($post_id) ) {
  375. if ( substr( $post->post_date, 0, 4 ) > 0 )
  376. $time = $post->post_date;
  377. } else {
  378. $time = filemtime($file);
  379. }
  380. $post_date = date( 'Y-m-d H:i:s', $time);
  381. $post_date_gmt = gmdate( 'Y-m-d H:i:s', $time);
  382. //Apply upload filters
  383. $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) );
  384. $new_file = $return['file'];
  385. $url = $return['url'];
  386. $type = $return['type'];
  387. $title = preg_replace('!\.[^.]+$!', '', basename($file));
  388. $content = '';
  389. // use image exif/iptc data for title and caption defaults if possible
  390. if ( $image_meta = @wp_read_image_metadata($new_file) ) {
  391. if ( '' != trim($image_meta['title']) )
  392. $title = trim($image_meta['title']);
  393. if ( '' != trim($image_meta['caption']) )
  394. $content = trim($image_meta['caption']);
  395. }
  396. // Construct the attachment array
  397. $attachment = array(
  398. 'post_mime_type' => $type,
  399. 'guid' => $url,
  400. 'post_parent' => $post_id,
  401. 'post_title' => $title,
  402. 'post_name' => $title,
  403. 'post_content' => $content,
  404. 'post_date' => $post_date,
  405. 'post_date_gmt' => $post_date_gmt
  406. );
  407. // Save the data
  408. $id = wp_insert_attachment($attachment, $new_file, $post_id);
  409. if ( !is_wp_error($id) ) {
  410. echo 'Crunching ('.$current.'/'.$sum.'): ' . htmlentities($filename) . '<br>';
  411. echo '<script type="text/javascript">
  412. if (window.parent.frames[window.name] && (parent.document.getElementsByTagName(\'frameset\').length <= 0)) {
  413. window.parent.document.getElementById("status_text").innerHTML = "Crunching ('.$current.'/'.$sum.'): ' . htmlentities($filename).'";
  414. }</script>';
  415. flush(); ob_flush();
  416. $data = wp_generate_attachment_metadata( $id, $file );
  417. $data['file'] = $new_file; // fix to get the right file name into the database!
  418. wp_update_attachment_metadata( $id, $data );
  419. }
  420. return $id;
  421. }
  422. function normalizeFileNames($imageName){
  423. // we make the file name lowercase
  424. $imageName = strtolower($imageName);
  425. // Some characters I know how to fix ;).
  426. $imageName=str_replace(array('ä','ö','ü','ß'),array('ae','oe','ue','ss'),$imageName);
  427. // and some others might need
  428. $imageName=str_replace(array('á','ŕ','ă','â','ç','˘','é','ę','č','ë','í','î','ď','ě','ń','ô','ó','ő','ň','š','r','ú','ů','ű','ü','ý','˙','ž'),
  429. array('a','a','a','a','c','c','e','e','e','e','i','i','i','i','n','o','o','o','o','s','r','u','u','u','u','y','y','z'),$imageName);
  430. // we remove the rest of unwanted chars
  431. $patterns[] = '/[\x7b-\xff]/'; // remove all characters above the letter z. This will eliminate some non-English language letters
  432. $patterns[] = '/[\x21-\x2c]/'; // remove range of shifted characters on keyboard - !"#$%&'()*+
  433. $patterns[] = '/[\x5b-\x60]/'; // remove range including brackets - []\^_`
  434. // we remove all kind of special characters for utf8 encoding as well
  435. $patterns[] = '/[\x7b-\xff]/u'; // remove all characters above the letter z. This will eliminate some non-English language letters
  436. $patterns[] = '/[\x21-\x2c]/u'; // remove range of shifted characters on keyboard - !"#$%&'()*+
  437. $patterns[] = '/[\x5b-\x60]/u'; // remove range including brackets - []\^_`
  438. $replacement ="_";
  439. return preg_replace($patterns, $replacement, $imageName);
  440. }
  441. function getUploadPath() {
  442. $upload_path = get_option('upload_path');
  443. if ($upload_path == '') {
  444. $upload_path = 'wp-content/uploads';
  445. }
  446. // we have to make the path relative! if we find wp-content we remove everything before!
  447. if (stristr($upload_path, 'wp-content') !== false) {
  448. $upload_path = stristr($upload_path, 'wp-content');
  449. }
  450. return $upload_path;
  451. }
  452. function removeExtension($name)
  453. {
  454. return substr($name, 0, strrpos ($name, '.'));
  455. }
  456. }}
  457. ?>