Beispiel #1
0
 /**
  * Delete Photo
  * @param int $id The unique id of the photo to be deleted
  */
 public static function delete_photo($id)
 {
     $photo = ORM::factory('media', $id);
     $photo_large = $photo->media_link;
     $photo_medium = $photo->media_medium;
     $photo_thumb = $photo->media_thumb;
     if (file_exists(Kohana::config('upload.directory', TRUE) . $photo_large)) {
         unlink(Kohana::config('upload.directory', TRUE) . $photo_large);
     } elseif (Kohana::config("cdn.cdn_store_dynamic_content") and valid::url($photo_large)) {
         cdn::delete($photo_large);
     }
     if (file_exists(Kohana::config('upload.directory', TRUE) . $photo_medium)) {
         unlink(Kohana::config('upload.directory', TRUE) . $photo_medium);
     } elseif (Kohana::config("cdn.cdn_store_dynamic_content") and valid::url($photo_medium)) {
         cdn::delete($photo_medium);
     }
     if (file_exists(Kohana::config('upload.directory', TRUE) . $photo_thumb)) {
         unlink(Kohana::config('upload.directory', TRUE) . $photo_thumb);
     } elseif (Kohana::config("cdn.cdn_store_dynamic_content") and valid::url($photo_thumb)) {
         cdn::delete($photo_thumb);
     }
     // Finally Remove from DB
     $photo->delete();
 }
 /**
  * Function to save news, photos and videos
  *
  * @param mixed $location_model
  * @param mixed $post
  *
  */
 public static function save_media($post, $incident)
 {
     $upload_dir = Kohana::config('upload.directory', TRUE);
     // Delete Previous Entries
     ORM::factory('media')->where('incident_id', $incident->id)->where('media_type <> 1')->delete_all();
     // a. News
     if (isset($post->incident_news)) {
         foreach ($post->incident_news as $item) {
             if (!empty($item)) {
                 $news = new Media_Model();
                 $news->location_id = $incident->location_id;
                 $news->incident_id = $incident->id;
                 $news->media_type = 4;
                 // News
                 $news->media_link = $item;
                 $news->media_date = date("Y-m-d H:i:s", time());
                 $news->save();
             }
         }
     }
     // b. Video
     if (isset($post->incident_video)) {
         $videoembed = new VideoEmbed();
         foreach ($post->incident_video as $k => $video_link) {
             if (!empty($video_link)) {
                 $video_thumb = $videoembed->thumbnail($video_link);
                 $new_filename = $incident->id . '_v' . $k . '_' . time();
                 $file_type = substr($video_thumb, strrpos($video_thumb, '.'));
                 $media_thumb = NULL;
                 $media_medium = NULL;
                 // Make sure file has an image extension
                 if ($video_thumb and in_array($file_type, array('.gif', '.jpg', '.png', '.jpeg'))) {
                     // Name the files for the DB
                     $media_link = $new_filename . $file_type;
                     $media_medium = $new_filename . '_m' . $file_type;
                     $media_thumb = $new_filename . '_t' . $file_type;
                     try {
                         if ($data = file_get_contents($video_thumb)) {
                             file_put_contents($upload_dir . $media_link, $data);
                         }
                     } catch (Exception $e) {
                     }
                     // IMAGE SIZES: 800X600, 400X300, 89X59
                     // Catch any errors from corrupt image files
                     try {
                         $image = Image::factory($upload_dir . $media_link);
                         // Medium size
                         if ($image->height > 300) {
                             Image::factory($upload_dir . $media_link)->resize(400, 300, Image::HEIGHT)->save($upload_dir . $media_medium);
                         } else {
                             // Cannot reuse the original image as it is deleted a bit further down
                             $image->save($upload_dir . $media_medium);
                         }
                         // Thumbnail
                         if ($image->height > 59) {
                             Image::factory($upload_dir . $media_link)->resize(89, 59, Image::HEIGHT)->save($upload_dir . $media_thumb);
                         } else {
                             // Reuse the medium image when it is small enough
                             $media_thumb = $media_medium;
                         }
                     } catch (Exception $e) {
                         // Do nothing. Too late to throw errors
                         // Set links to NULL
                         $media_medium = NULL;
                         $media_thumb = NULL;
                     }
                     // Okay, now we have these three different files on the server, now check to see
                     //   if we should be dropping them on the CDN
                     $local_directory = rtrim($upload_dir, '/') . '/';
                     if ($media_medium and $media_thumb and Kohana::config("cdn.cdn_store_dynamic_content")) {
                         $cdn_media_medium = cdn::upload($media_medium);
                         $cdn_media_thumb = cdn::upload($media_thumb);
                         // We no longer need the files we created on the server. Remove them.
                         if (file_exists($local_directory . $media_medium)) {
                             unlink($local_directory . $media_medium);
                         }
                         if (file_exists($local_directory . $media_thumb)) {
                             unlink($local_directory . $media_thumb);
                         }
                         $media_medium = $cdn_media_medium;
                         $media_thumb = $cdn_media_thumb;
                     }
                     if (file_exists($local_directory . $media_link)) {
                         // Remove original image
                         unlink($upload_dir . $media_link);
                     }
                 }
                 $video = new Media_Model();
                 $video->location_id = $incident->location_id;
                 $video->incident_id = $incident->id;
                 $video->media_type = 2;
                 // Video
                 $video->media_link = $video_link;
                 $video->media_thumb = $media_thumb;
                 $video->media_medium = $media_medium;
                 $video->media_date = date("Y-m-d H:i:s", time());
                 $video->save();
             }
         }
     }
     // c. Photos
     if (!empty($post->incident_photo)) {
         $filenames = upload::save('incident_photo');
         $i = 1;
         foreach ($filenames as $filename) {
             $new_filename = $incident->id . '_' . $i . '_' . time();
             //$file_type = substr($filename,-4);
             $file_type = "." . substr(strrchr($filename, '.'), 1);
             // replaces the commented line above to take care of images with .jpeg extension.
             // Name the files for the DB
             $media_link = $new_filename . $file_type;
             $media_medium = $new_filename . '_m' . $file_type;
             $media_thumb = $new_filename . '_t' . $file_type;
             // IMAGE SIZES: 800X600, 400X300, 89X59
             // Catch any errors from corrupt image files
             try {
                 $image = Image::factory($filename);
                 // Large size
                 if ($image->width > 800 || $image->height > 600) {
                     Image::factory($filename)->resize(800, 600, Image::AUTO)->save($upload_dir . $media_link);
                 } else {
                     $image->save($upload_dir . $media_link);
                 }
                 // Medium size
                 if ($image->height > 300) {
                     Image::factory($filename)->resize(400, 300, Image::HEIGHT)->save($upload_dir . $media_medium);
                 } else {
                     // Reuse the large image when it is small enough
                     $media_medium = $media_link;
                 }
                 // Thumbnail
                 if ($image->height > 59) {
                     Image::factory($filename)->resize(89, 59, Image::HEIGHT)->save($upload_dir . $media_thumb);
                 } else {
                     // Reuse the medium image when it is small enough
                     $media_thumb = $media_medium;
                 }
             } catch (Kohana_Exception $e) {
                 // Do nothing. Too late to throw errors
                 $media_link = NULL;
                 $media_medium = NULL;
                 $media_thumb = NULL;
             }
             // Okay, now we have these three different files on the server, now check to see
             //   if we should be dropping them on the CDN
             if (Kohana::config("cdn.cdn_store_dynamic_content")) {
                 $cdn_media_link = cdn::upload($media_link);
                 $cdn_media_medium = cdn::upload($media_medium);
                 $cdn_media_thumb = cdn::upload($media_thumb);
                 // We no longer need the files we created on the server. Remove them.
                 $local_directory = rtrim($upload_dir, '/') . '/';
                 if (file_exists($local_directory . $media_link)) {
                     unlink($local_directory . $media_link);
                 }
                 if (file_exists($local_directory . $media_medium)) {
                     unlink($local_directory . $media_medium);
                 }
                 if (file_exists($local_directory . $media_thumb)) {
                     unlink($local_directory . $media_thumb);
                 }
                 $media_link = $cdn_media_link;
                 $media_medium = $cdn_media_medium;
                 $media_thumb = $cdn_media_thumb;
             }
             // Remove the temporary file
             unlink($filename);
             // Save to DB
             $photo = new Media_Model();
             $photo->location_id = $incident->location_id;
             $photo->incident_id = $incident->id;
             $photo->media_type = 1;
             // Images
             $photo->media_link = $media_link;
             $photo->media_medium = $media_medium;
             $photo->media_thumb = $media_thumb;
             $photo->media_date = date("Y-m-d H:i:s", time());
             $photo->save();
             $i++;
         }
     }
 }
Beispiel #3
0
 public function cdn_gradual_upgrade()
 {
     $this->auto_render = FALSE;
     $this->template = "";
     if (Kohana::config('cdn.cdn_gradual_upgrade') != FALSE) {
         cdn::gradual_upgrade();
     }
 }
Beispiel #4
0
 /**
  * Add Edit Layers (KML, KMZ, GeoRSS)
  */
 public function layers()
 {
     $this->template->content = new View('admin/layers');
     $this->template->content->title = Kohana::lang('ui_admin.layers');
     // Setup and initialize form field names
     $form = array('action' => '', 'layer_id' => '', 'layer_name' => '', 'layer_url' => '', 'layer_file' => '', 'layer_color' => '');
     // Copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = FALSE;
     $form_action = "";
     $parents_array = array();
     // Check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Fetch the submitted data
         $post_data = array_merge($_POST, $_FILES);
         // Layer instance for the actions
         $layer = (isset($post_data['layer_id']) and Layer_Model::is_valid_layer($post_data['layer_id'])) ? new Layer_Model($post_data['layer_id']) : new Layer_Model();
         // Check for action
         if ($post_data['action'] == 'a') {
             // Manually extract the primary layer data
             $layer_data = arr::extract($post_data, 'layer_name', 'layer_color', 'layer_url', 'layer_file_old');
             // Grab the layer file to be uploaded
             $layer_data['layer_file'] = isset($post_data['layer_file']['name']) ? $post_data['layer_file']['name'] : NULL;
             // Extract the layer file for upload validation
             $other_data = arr::extract($post_data, 'layer_file');
             // Set up validation for the layer file
             $post = Validation::factory($other_data)->pre_filter('trim', TRUE)->add_rules('layer_file', 'upload::valid', 'upload::type[kml,kmz]');
             // Test to see if validation has passed
             if ($layer->validate($layer_data) and $post->validate(FALSE)) {
                 // Success! SAVE
                 $layer->save();
                 $path_info = upload::save("layer_file");
                 if ($path_info) {
                     $path_parts = pathinfo($path_info);
                     $file_name = $path_parts['filename'];
                     $file_ext = $path_parts['extension'];
                     $layer_file = $file_name . "." . $file_ext;
                     $layer_url = '';
                     if (strtolower($file_ext) == "kmz") {
                         // This is a KMZ Zip Archive, so extract
                         $archive = new Pclzip($path_info);
                         if (TRUE == ($archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING))) {
                             foreach ($archive_files as $file) {
                                 $ext_file_name = $file['filename'];
                                 $archive_file_parts = pathinfo($ext_file_name);
                                 //because there can be more than one file in a KMZ
                                 if ($archive_file_parts['extension'] == 'kml' and $ext_file_name and $archive->extract(PCLZIP_OPT_PATH, Kohana::config('upload.directory')) == TRUE) {
                                     // Okay, so we have an extracted KML - Rename it and delete KMZ file
                                     rename($path_parts['dirname'] . "/" . $ext_file_name, $path_parts['dirname'] . "/" . $file_name . ".kml");
                                     $file_ext = "kml";
                                     unlink($path_info);
                                     $layer_file = $file_name . "." . $file_ext;
                                 }
                             }
                         }
                     }
                     // Upload the KML to the CDN server if configured
                     if (Kohana::config("cdn.cdn_store_dynamic_content")) {
                         // Upload the file to the CDN
                         $layer_url = cdn::upload($layer_file);
                         // We no longer need the files we created on the server. Remove them.
                         $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
                         unlink($local_directory . $layer_file);
                         // We no longer need to store the file name for the local file since it's gone
                         $layer_file = '';
                     }
                     // Set the final variables for the DB
                     $layer->layer_url = $layer_url;
                     $layer->layer_file = $layer_file;
                     $layer->save();
                 }
                 $form_saved = TRUE;
                 array_fill_keys($form, '');
                 $form_action = strtoupper(Kohana::lang('ui_admin.added_edited'));
             } else {
                 // Validation failed
                 // Repopulate the form fields
                 $form = arr::overwrite($form, array_merge($layer_data->as_array(), $post->as_array()));
                 // Ropulate the error fields, if any
                 $errors = arr::overwrite($errors, array_merge($layer_data->errors('layer'), $post->errors('layer')));
                 $form_error = TRUE;
             }
         } elseif ($post_data['action'] == 'd') {
             // Delete action
             if ($layer->loaded) {
                 // Delete KMZ file if any
                 $layer_file = $layer->layer_file;
                 if (!empty($layer_file) and file_exists(Kohana::config('upload.directory', TRUE) . $layer_file)) {
                     unlink(Kohana::config('upload.directory', TRUE) . $layer_file);
                 }
                 $layer->delete();
                 $form_saved = TRUE;
                 $form_action = strtoupper(Kohana::lang('ui_admin.deleted'));
             }
         } elseif ($post_data['action'] == 'v') {
             // Show/Hide Action
             if ($layer->loaded == TRUE) {
                 $layer->layer_visible = $layer->layer_visible == 1 ? 0 : 1;
                 $layer->save();
                 $form_saved = TRUE;
                 $form_action = strtoupper(Kohana::lang('ui_admin.modified'));
             }
         } elseif ($post_data['action'] == 'i') {
             // Delete KML/KMZ action
             if ($layer->loaded == TRUE) {
                 $layer_file = $layer->layer_file;
                 if (!empty($layer_file) and file_exists(Kohana::config('upload.directory', TRUE) . $layer_file)) {
                     unlink(Kohana::config('upload.directory', TRUE) . $layer_file);
                 }
                 $layer->layer_file = null;
                 $layer->save();
                 $form_saved = TRUE;
                 $form_action = strtoupper(Kohana::lang('ui_admin.modified'));
             }
         }
     }
     // Pagination
     $pagination = new Pagination(array('query_string' => 'page', 'items_per_page' => $this->items_per_page, 'total_items' => ORM::factory('layer')->count_all()));
     $layers = ORM::factory('layer')->orderby('layer_name', 'asc')->find_all($this->items_per_page, $pagination->sql_offset);
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     $this->template->content->form_action = $form_action;
     $this->template->content->pagination = $pagination;
     $this->template->content->total_items = $pagination->total_items;
     $this->template->content->layers = $layers;
     // Javascript Header
     $this->template->colorpicker_enabled = TRUE;
     $this->template->js = new View('admin/layers_js');
 }
Beispiel #5
0
 public function cdn_gradual_upgrade()
 {
     if (Kohana::config('cdn.cdn_gradual_upgrade') != FALSE) {
         return cdn::gradual_upgrade();
     }
     return '';
 }
Beispiel #6
0
 /**
  * Map Settings
  */
 function index($saved = false)
 {
     // Display all maps
     $this->template->api_url = Kohana::config('settings.api_url_all');
     // Current Default Country
     $current_country = Kohana::config('settings.default_country');
     $this->template->content = new View('admin/settings');
     $this->template->content->title = Kohana::lang('ui_admin.settings');
     // setup and initialize form field names
     $form = array('default_map' => '', 'api_google' => '', 'api_live' => '', 'default_country' => '', 'multi_country' => '', 'default_lat' => '', 'default_lon' => '', 'default_zoom' => '', 'default_map_all' => '', 'allow_clustering' => '', 'default_map_all_icon' => '', 'delete_default_map_all_icon' => '');
     //	Copy the form as errors, so the errors will be stored with keys
     //	corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = $saved == 'saved';
     // check, has the form been submitted, if so, setup validation
     if ($_POST) {
         // Instantiate Validation, use $post, so we don't overwrite $_POST
         // fields with our own things
         $post = Validation::factory($_POST)->pre_filter('trim', TRUE)->add_rules('default_country', 'required', 'numeric', 'length[1,4]')->add_rules('multi_country', 'numeric', 'length[1,1]')->add_rules('default_map', 'required', 'length[0,100]')->add_rules('default_zoom', 'required', 'between[0,21]')->add_rules('default_lat', 'required', 'between[-85,85]')->add_rules('default_lon', 'required', 'between[-180,180]')->add_rules('allow_clustering', 'required', 'between[0,1]')->add_rules('default_map_all', 'required', 'alpha_numeric', 'length[6,6]')->add_rules('api_google', 'length[0,200]')->add_rules('api_live', 'length[0,200]');
         // Add rules for file upload
         $files = Validation::factory($_FILES);
         $files->add_rules('default_map_all_icon', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[250K]');
         // Test to see if things passed the rule checks
         if ($post->validate() and $files->validate(FALSE)) {
             // Yes! everything is valid
             $settings = new Settings_Model(1);
             $settings->default_country = $post->default_country;
             $settings->multi_country = $post->multi_country;
             $settings->default_map = $post->default_map;
             $settings->api_google = $post->api_google;
             // E.Kala 20th April 2012
             // Gangsta workaround prevent resetting og Bing Maps API Key
             // Soon to be addressed conclusively
             if (isset($post['api_live']) and !empty($post['api_live'])) {
                 $settings->api_live = $post->api_live;
             }
             $settings->default_zoom = $post->default_zoom;
             $settings->default_lat = $post->default_lat;
             $settings->default_lon = $post->default_lon;
             $settings->allow_clustering = $post->allow_clustering;
             $settings->default_map_all = $post->default_map_all;
             $settings->date_modify = date("Y-m-d H:i:s", time());
             $settings->save();
             // Deal with default category icon now
             // Check if deleting or updating a new image (or doing nothing)
             if (isset($post->delete_default_map_all_icon) and $post->delete_default_map_all_icon == 1) {
                 // Delete old badge image
                 ORM::factory('media')->delete($settings->default_map_all_icon_id);
                 // Remove from DB table
                 $settings = new Settings_Model(1);
                 $settings->default_map_all_icon_id = NULL;
                 $settings->save();
             } else {
                 // We aren't deleting, so try to upload if we are uploading an image
                 $filename = upload::save('default_map_all_icon');
                 if ($filename) {
                     $new_filename = "default_map_all_" . time();
                     $file_type = strrev(substr(strrev($filename), 0, 4));
                     // Large size
                     $l_name = $new_filename . $file_type;
                     Image::factory($filename)->save(Kohana::config('upload.directory', TRUE) . $l_name);
                     // Medium size
                     $m_name = $new_filename . "_m" . $file_type;
                     Image::factory($filename)->resize(32, 32, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $m_name);
                     // Thumbnail
                     $t_name = $new_filename . "_t" . $file_type;
                     Image::factory($filename)->resize(16, 16, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $t_name);
                     // Name the files for the DB
                     $media_link = $l_name;
                     $media_medium = $m_name;
                     $media_thumb = $t_name;
                     // Okay, now we have these three different files on the server, now check to see
                     //   if we should be dropping them on the CDN
                     if (Kohana::config("cdn.cdn_store_dynamic_content")) {
                         $media_link = cdn::upload($media_link);
                         $media_medium = cdn::upload($media_medium);
                         $media_thumb = cdn::upload($media_thumb);
                         // We no longer need the files we created on the server. Remove them.
                         $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
                         unlink($local_directory . $l_name);
                         unlink($local_directory . $m_name);
                         unlink($local_directory . $t_name);
                     }
                     // Remove the temporary file
                     unlink($filename);
                     // Save image in the media table
                     $media = new Media_Model();
                     $media->media_type = 1;
                     // Image
                     $media->media_link = $media_link;
                     $media->media_medium = $media_medium;
                     $media->media_thumb = $media_thumb;
                     $media->media_date = date("Y-m-d H:i:s", time());
                     $media->save();
                     // Save new image in settings
                     $settings = new Settings_Model(1);
                     $settings->default_map_all_icon_id = $media->id;
                     $settings->save();
                 }
             }
             // Delete Settings Cache
             $this->cache->delete('settings');
             $this->cache->delete_tag('settings');
             // Everything is A-Okay!
             $form_saved = TRUE;
             // Action::map_settings_modified - Map settings have changed
             Event::run('ushahidi_action.map_settings_modified');
             // Redirect to reload everything over again
             url::redirect('admin/settings/index/saved');
         } else {
             // repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // populate the error fields, if any
             $errors = arr::overwrite($errors, $post->errors('settings'));
             $form_error = TRUE;
         }
     } else {
         // Retrieve Current Settings
         $settings = ORM::factory('settings', 1);
         $form = array('default_map' => $settings->default_map, 'api_google' => $settings->api_google, 'api_live' => $settings->api_live, 'default_country' => $settings->default_country, 'multi_country' => $settings->multi_country, 'default_lat' => $settings->default_lat, 'default_lon' => $settings->default_lon, 'default_zoom' => $settings->default_zoom, 'allow_clustering' => $settings->allow_clustering, 'default_map_all' => $settings->default_map_all, 'default_map_all_icon_id' => $settings->default_map_all_icon_id);
     }
     // Get default category image
     $settings = ORM::factory('settings', 1);
     if ($settings->default_map_all_icon_id != NULL) {
         $icon = ORM::factory('media')->find($settings->default_map_all_icon_id);
         $this->template->content->default_map_all_icon = url::convert_uploaded_to_abs($icon->media_link);
         $this->template->content->default_map_all_icon_m = url::convert_uploaded_to_abs($icon->media_medium);
         $this->template->content->default_map_all_icon_t = url::convert_uploaded_to_abs($icon->media_thumb);
     } else {
         $this->template->content->default_map_all_icon = NULL;
         $this->template->content->default_map_all_icon_m = NULL;
         $this->template->content->default_map_all_icon_t = NULL;
     }
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     // Get Countries
     $countries = array();
     foreach (ORM::factory('country')->orderby('country')->find_all() as $country) {
         // Create a list of all categories
         $this_country = $country->country;
         if (strlen($this_country) > 35) {
             $this_country = substr($this_country, 0, 30) . "...";
         }
         $countries[$country->id] = $this_country;
     }
     $this->template->content->countries = $countries;
     // Zoom Array for Slider
     $default_zoom_array = array();
     for ($i = Kohana::config('map.minZoomLevel'); $i < Kohana::config('map.minZoomLevel') + Kohana::config('map.numZoomLevels'); $i++) {
         $default_zoom_array[$i] = $i;
     }
     $this->template->content->default_zoom_array = $default_zoom_array;
     // Get Map API Providers
     $layers = map::base();
     $map_array = array();
     foreach ($layers as $layer) {
         $map_array[$layer->name] = $layer->title;
     }
     $this->template->content->map_array = $map_array;
     $this->template->content->yesno_array = array('1' => strtoupper(Kohana::lang('ui_main.yes')), '0' => strtoupper(Kohana::lang('ui_main.no')));
     // Javascript Header
     $this->template->map_enabled = TRUE;
     $this->template->colorpicker_enabled = TRUE;
     $this->template->js = new View('admin/settings_js');
     $this->template->js->default_map = $form['default_map'];
     $this->template->js->default_zoom = $form['default_zoom'];
     $this->template->js->default_lat = $form['default_lat'];
     $this->template->js->default_lon = $form['default_lon'];
     $this->template->js->all_maps_json = $this->_generate_settings_map_js();
 }
Beispiel #7
0
 public function cdn_publish()
 {
     $rid = intval($this->input['id']);
     if (!$rid) {
         $this->errorOutput('NO_ID');
     }
     $content = $this->obj->get_all_content_by_relationid($rid, true);
     if (!$content) {
         $this->errorOutput('NO_CONTENT');
     }
     if ($this->settings['is_need_audit']) {
         if ($content['status'] != 1) {
             $this->errorOutput('NO_AUDIT');
         }
     }
     if (strstr($content['content_url'], "http") !== false) {
         include_once ROOT_PATH . 'lib/class/cdn.class.php';
         $cdn = new cdn();
         $cdn->push($content['content_url'], '', '');
     }
     $this->addItem(true);
     $this->output();
 }
Beispiel #8
0
 public function index()
 {
     // Debug
     $debug = "";
     // @todo abstract most of this into a library, especially locking
     // Ensure settings entry for `scheduler_lock` exists
     Database::instance()->query("INSERT IGNORE INTO `" . Kohana::config('database.default.table_prefix') . "settings`\n\t\t\t(`key`, `value`) VALUES ('scheduler_lock', 0)");
     // Now try and update the scheduler_lock
     $result = Database::instance()->query("UPDATE `" . Kohana::config('database.default.table_prefix') . "settings`\n\t\t\tSET `value` = UNIX_TIMESTAMP() + 180\n\t\t\tWHERE `value` < UNIX_TIMESTAMP() AND `key` = 'scheduler_lock';");
     // If no entries were changed, scheduler is already running
     if ($result->count() <= 0) {
         Kohana::log('info', 'Could not acquire scheduler lock');
         if (isset($_GET['debug']) and $_GET['debug'] == 1) {
             echo 'Could not acquire scheduler lock';
         }
         return;
     }
     // Get all active scheduled items
     foreach (ORM::factory('scheduler')->where('scheduler_active', '1')->find_all() as $scheduler) {
         $scheduler_id = $scheduler->id;
         $scheduler_last = $scheduler->scheduler_last;
         // Next run time
         $scheduler_weekday = $scheduler->scheduler_weekday;
         // Day of the week
         $scheduler_day = $scheduler->scheduler_day;
         // Day of the month
         $scheduler_hour = $scheduler->scheduler_hour;
         // Hour
         $scheduler_minute = $scheduler->scheduler_minute;
         // Minute
         // Controller that performs action
         $scheduler_controller = $scheduler->scheduler_controller;
         if ($scheduler_day <= -1) {
             // Ran every day?
             $scheduler_day = "*";
         }
         if ($scheduler_weekday <= -1) {
             // Ran every day?
             $scheduler_weekday = "*";
         }
         if ($scheduler_hour <= -1) {
             // Ran every hour?
             $scheduler_hour = "*";
         }
         if ($scheduler_minute <= -1) {
             // Ran every minute?
             $scheduler_minute = "*";
         }
         $scheduler_cron = $scheduler_minute . " " . $scheduler_hour . " " . $scheduler_day . " * " . $scheduler_weekday;
         //Start new cron parser instance
         $cron = new CronParser();
         if (!$cron->calcLastRan($scheduler_cron)) {
             echo "Error parsing CRON";
         }
         $lastRan = $cron->getLastRan();
         //Array (0=minute, 1=hour, 2=dayOfMonth, 3=month, 4=week, 5=year)
         $cronRan = mktime($lastRan[1], $lastRan[0], 0, $lastRan[3], $lastRan[2], $lastRan[5]);
         if (isset($_GET['debug']) and $_GET['debug'] == 1) {
             $debug .= "~~~~~~~~~~~~~~~~~~~~~~~~~~~" . "<BR />~~~~~~~~~~~~~~~~~~~~~~~~~~~" . "<BR />RUNNING: " . $scheduler->scheduler_name . "<BR />~~~~~~~~~~~~~~~~~~~~~~~~~~~" . "<BR /> LAST RUN: " . date("r", $scheduler_last) . "<BR /> LAST DUE AT: " . date('r', $cron->getLastRanUnix()) . "<BR /> SCHEDULE: <a href=\"http://en.wikipedia.org/wiki/Cron\" target=\"_blank\">" . $scheduler_cron . "</a>";
         }
         if ($scheduler_controller and (!($scheduler_last > $cronRan) or $scheduler_last == 0)) {
             $run = FALSE;
             // Catch errors from missing scheduler or other bugs
             try {
                 $dispatch = Dispatch::controller($scheduler_controller, "scheduler/");
                 if ($dispatch instanceof Dispatch && method_exists($dispatch, 'method')) {
                     $run = $dispatch->method('index', '');
                 }
             } catch (Exception $e) {
                 // Nada.
             }
             // @todo allow tasks to save state between runs.
             if ($run !== FALSE) {
                 // Set last time of last execution
                 $schedule_time = time();
                 $scheduler->scheduler_last = $schedule_time;
                 $scheduler->save();
                 // Record Action to Log
                 $scheduler_log = new Scheduler_Log_Model();
                 $scheduler_log->scheduler_id = $scheduler_id;
                 $scheduler_log->scheduler_status = "200";
                 $scheduler_log->scheduler_date = $schedule_time;
                 $scheduler_log->save();
                 if (isset($_GET['debug']) and $_GET['debug'] == 1) {
                     $debug .= "<BR /> STATUS: {{ EXECUTED }}";
                 }
             } else {
                 if (isset($_GET['debug']) and $_GET['debug'] == 1) {
                     $debug .= "<BR /> STATUS: {{ SCHEDULER NOT FOUND! }}";
                 }
             }
         } else {
             if (isset($_GET['debug']) and $_GET['debug'] == 1) {
                 $debug .= "<BR /> STATUS: {{ NOT RUN }}";
             }
         }
         if (isset($_GET['debug']) and $_GET['debug'] == 1) {
             //$debug .= "<BR /><BR />CRON DEBUG:<BR />".nl2br($cron->getDebug());
             $debug .= "<BR />~~~~~~~~~~~~~~~~~~~~~~~~~~~<BR />~~~~~~~~~~~~~~~~~~~~~~~~~~~<BR /><BR /><BR />";
         }
     }
     if (Kohana::config('cdn.cdn_gradual_upgrade') != FALSE) {
         cdn::gradual_upgrade();
     }
     // If DEBUG is TRUE echo DEBUG info instead of transparent GIF
     if (isset($_GET['debug']) and $_GET['debug'] == 1) {
         echo $debug;
         if (isset($this->profiler)) {
             echo $this->profiler->render(TRUE);
         }
     } else {
         // Transparent GIF
         Header("Content-type: image/gif");
         Header("Expires: Wed, 11 Nov 1998 11:11:11 GMT");
         Header("Cache-Control: no-cache");
         Header("Cache-Control: must-revalidate");
         Header("Content-Length: 49");
         echo pack('H*', '47494638396101000100910000000000ffffffff' . 'ffff00000021f90405140002002c000000000100' . '01000002025401003b');
     }
     // Release lock
     $result = Database::instance()->query("UPDATE `" . Kohana::config('database.default.table_prefix') . "settings`\n\t\t\tSET `value` = 0\n\t\t\tWHERE `key` = 'scheduler_lock';");
 }
Beispiel #9
0
 /**
  * See {@link combine_files()}
  *
  */
 private function _process_combined_files($type)
 {
     // Make a map of files that could be potentially combined
     $combinerCheck = array();
     foreach ($this->combine_files[$type] as $combinedFile => $sourceItems) {
         foreach ($sourceItems as $id => $sourceItem) {
             if (isset($combinerCheck[$sourceItem]) && $combinerCheck[$sourceItem] != $combinedFile) {
                 Kohana::log('alert', "Requirements_Backend::process_combined_files - file '{$sourceItem}' appears in two combined files:" . " '{$combinerCheck[$sourceItem]}' and '{$combinedFile}'");
             }
             $combinerCheck[$sourceItem] = $combinedFile;
             $combinerCheck[$id] = $combinedFile;
         }
     }
     // Work out the relative URL for the combined files from the base folder
     $combinedFilesFolder = $this->getCombinedFilesFolder() ? $this->getCombinedFilesFolder() . '/' : '';
     // Figure out which ones apply to this pageview
     $combinedFiles = array();
     $newRequirements = array();
     foreach ($this->{$type} as $id => $params) {
         $file = $type == 'js' ? $params : $params['file'];
         if (isset($combinerCheck[$file])) {
             $newRequirements[$combinerCheck[$file]] = $type == 'js' ? $combinedFilesFolder . $combinerCheck[$file] : array('file' => $combinedFilesFolder . $combinerCheck[$file]);
             $combinedFiles[$combinerCheck[$file]] = true;
         } elseif (isset($combinerCheck[$id])) {
             $newRequirements[$combinerCheck[$id]] = $type == 'js' ? $combinedFilesFolder . $combinerCheck[$id] : array('file' => $combinedFilesFolder . $combinerCheck[$id]);
             $combinedFiles[$combinerCheck[$id]] = true;
         } else {
             $newRequirements[$id] = $params;
         }
     }
     // Process the combined files
     $base = DOCROOT;
     foreach (array_diff_key($combinedFiles, $this->blocked) as $combinedFile => $dummy) {
         $fileList = $this->combine_files[$type][$combinedFile];
         $combinedFilePath = $base . $combinedFilesFolder . $combinedFile;
         // Check for RTL alternatives
         if ($type == 'css' and ush_locale::is_rtl_language()) {
             $has_rtl_files = FALSE;
             foreach ($fileList as $index => $file) {
                 $rtlFile = substr($file, 0, strpos($file, ".{$type}")) . "-rtl" . substr($file, strpos($file, ".{$type}"));
                 if (file_exists(DOCROOT . $rtlFile)) {
                     $fileList[$index] = $rtlFile;
                     $has_rtl_files = TRUE;
                 }
             }
             // Update combined files details, only if the include RTL alternatives
             // We store the RTL version separate from the LTR version, so we don't regenerate every time someone changes language
             if ($has_rtl_files) {
                 $combinedFile = substr($combinedFile, 0, -4) . '-rtl.css';
                 $combinedFilePath = $base . $combinedFilesFolder . $combinedFile;
                 $newRequirements[$combinedFile] = $type == 'js' ? $combinedFilesFolder . $combinedFile : array('file' => $combinedFilesFolder . $combinedFile);
             }
         }
         // Make the folder if necessary
         if (!file_exists(dirname($combinedFilePath))) {
             mkdir(dirname($combinedFilePath));
         }
         // If the file isn't writebale, don't even bother trying to make the combined file
         // Complex test because is_writable fails if the file doesn't exist yet.
         if (file_exists($combinedFilePath) && !is_writable($combinedFilePath) || !file_exists($combinedFilePath) && !is_writable(dirname($combinedFilePath))) {
             Kohana::log('alert', "Requirements_Backend::process_combined_files(): Couldn't create '{$combinedFilePath}'");
             continue;
         }
         // Determine if we need to build the combined include
         if (file_exists($combinedFilePath) && !isset($_GET['flush'])) {
             // file exists, check modification date of every contained file
             $srcLastMod = 0;
             foreach ($fileList as $file) {
                 $srcLastMod = max(filemtime($base . $file), $srcLastMod);
             }
             $refresh = $srcLastMod > filemtime($combinedFilePath);
         } else {
             // file doesn't exist, or refresh was explicitly required
             $refresh = true;
         }
         if (!$refresh) {
             continue;
         }
         $combinedData = "";
         foreach (array_diff($fileList, $this->blocked) as $id => $file) {
             $fileContent = file_get_contents($base . $file);
             // if we have a javascript file and jsmin is enabled, minify the content
             if ($type == 'js' && $this->combine_js_with_jsmin) {
                 $fileContent = JSMin::minify($fileContent);
             }
             if ($type == 'css') {
                 // Rewrite urls in css to be relative to the docroot
                 // Docroot param needs to be actual server docroot, not root of ushahidi site.
                 // Using $_SERVER['DOCUMENT_ROOT']. Should possibly use DOCROOT, but remove Kohana::config('core.site_domain', TRUE);
                 $fileContent = Minify_CSS_UriRewriter::rewrite($fileContent, pathinfo($base . $file, PATHINFO_DIRNAME), $_SERVER['DOCUMENT_ROOT']);
                 // compress css (if enabled)
                 if ($this->combine_css_with_cssmin) {
                     $fileContent = CSSmin::go($fileContent);
                 }
             }
             // write a header comment for each file for easier identification and debugging
             // also the semicolon between each file is required for jQuery to be combinable properly
             $combinedData .= "/****** FILE: {$file} *****/\n" . $fileContent . "\n" . ($type == 'js' ? ';' : '') . "\n";
         }
         $successfulWrite = false;
         $fh = fopen($combinedFilePath, 'wb');
         if ($fh) {
             if (fwrite($fh, $combinedData) == strlen($combinedData)) {
                 $successfulWrite = true;
             }
             fclose($fh);
             unset($fh);
         }
         // Should we push this to the CDN too?
         if (Kohana::config("cdn.cdn_store_dynamic_content") and Kohana::config("requirements.cdn_store_combined_files")) {
             $cdn_combined_path = cdn::upload($combinedFilesFolder . $combinedFile, FALSE);
         }
         // Unsuccessful write - just include the regular JS files, rather than the combined one
         if (!$successfulWrite) {
             Kohana::log('alert', "Requirements_Backend::process_combined_files(): Couldn't create '{$combinedFilePath}'");
             continue;
         }
     }
     // @todo Alters the original information, which means you can't call this
     // method repeatedly - it will behave different on the second call!
     $this->{$type} = $newRequirements;
 }
Beispiel #10
0
 public function dvr()
 {
     $stream = addslashes($this->input['stream']);
     $start_time = intval($this->input['starttime']);
     $duration = intval($this->input['duration']);
     $endtime = $start_time + $duration;
     if ($endtime > $this->mTimenow) {
         $endtime = $this->mTimenow;
     }
     $time_shift = $this->mChannelinfo['channel']['time_shift'];
     $shift_stime = $this->mTimenow - $time_shift * 3600000;
     if ($start_time < $shift_stime) {
         $start_time = $shift_stime;
     }
     $this->mChannelinfo['channel']['table_name'] = $this->mChannelinfo['channel']['table_name'] ? $this->mChannelinfo['channel']['table_name'] : 'dvr';
     $channel_stream = $this->mChannelinfo['channel']['code'] . '_' . $stream;
     $this->db = hg_ConnectDB();
     $sql = 'SELECT * FROM ' . DB_PREFIX . $this->mChannelinfo['channel']['table_name'] . " WHERE stream_name='{$channel_stream}' AND start_time >= {$start_time} AND start_time < {$endtime} ORDER BY start_time ASC ";
     $q = $this->db->query($sql);
     $ts = array();
     while ($r = $this->db->fetch_array($q)) {
         $ts[$r['level']][] = $r;
     }
     $ts = $this->get_dvr_ts($ts);
     $sdate = date('Y-m-d', $start_time / 1000);
     $edate = date('Y-m-d', $endtime / 1000);
     $shield_time_zone = $this->get_shield($sdate);
     if ($sdate != $edate) {
         $shield_time_zone = array_merge($shield_time_zone, $this->get_shield($edate));
     }
     $m3u8 = $this->build_m3u8($ts, '#EXT-X-ENDLIST', rtrim($this->mChannelinfo['channel']['config']['ts_host'], '/'), $shield_time_zone);
     $dir = DATA_DIR . $this->mChannelinfo['channel']['code'] . '/' . $stream . '/';
     hg_mkdir($dir);
     $m3u8name = $start_time . ',' . $duration . '.m3u8';
     $m3u8 = trim($m3u8);
     if (!$m3u8) {
         $this->header(404);
     }
     file_put_contents($dir . $m3u8name, $m3u8);
     $urls = $this->mChannelinfo['channel']['config']['out_host'] . $this->mChannelinfo['channel']['code'] . '/' . $stream . '/' . $m3u8name;
     $sm3u8 = $m3u8;
     if ($this->settings['ts_host']) {
         $m3u8 = str_replace($this->mChannelinfo['channel']['config']['ts_host'], $this->settings['ts_host'], $m3u8);
         file_put_contents($dir . 'm_' . $m3u8name, $m3u8);
         $urls .= "\n" . $this->mChannelinfo['channel']['config']['out_host'] . $this->mChannelinfo['channel']['code'] . '/' . $stream . '/m_' . $m3u8name;
     }
     if ($this->settings['open_push_cdn']) {
         include_once ROOT_PATH . 'lib/class/cdn.class.php';
         $cdn = new cdn();
         $cdn->push($urls, '');
     }
     if ($this->settings['m3u8_host'] == 'http://' . $this->input['host']) {
         echo $m3u8;
     } else {
         echo $sm3u8;
     }
 }
 /**
  * This function performs the actual checkin and will register a new user
  *	 if the user doesn't exist. Also, if the name and email is passed with
  *	 the checkin, the user will be updated.
  *
  *	 mobileid, lat and lon are the only required fields.
  *
  * Handles the API task parameters
  */
 public function register_checkin($mobileid, $lat, $lon, $message = FALSE, $firstname = FALSE, $lastname = FALSE, $email = FALSE, $color = FALSE)
 {
     // Check if this device has been registered yet
     if (!User_Devices_Model::device_registered($mobileid)) {
         // Device has not been registered yet. Register it!
         // TODO: Formalize the user creation process. For now we are creating
         //		 a new user for every new device but eventually, we need
         //		 to be able to have multiple devices for each user
         // Name of the user
         $user_name = ($firstname and $lastname) ? $firstname . ' ' . $lastname : '';
         // Email address
         $user_email = $email ? $email : $this->getRandomString();
         // Color
         $user_color = $color ? $color : $this->random_color();
         // Check if email exists
         $query = 'SELECT id FROM `' . $this->table_prefix . 'users` WHERE `email` = ? LIMIT 1;';
         $usercheck = $this->db->query($query, $user_email);
         if (isset($usercheck[0]->id)) {
             $user_id = $usercheck[0]->id;
         } else {
             // Create a new user
             $user = ORM::factory('user');
             $user->name = $user_name;
             $user->email = $user_email;
             $user->username = $this->getRandomString();
             $user->password = '******';
             $user->color = $user_color;
             $user->add(ORM::factory('role', 'login'));
             $user_id = $user->save();
         }
         //	 TODO: When we have user registration down, we need to pass a user id here
         //		   so we can assign it to a specific user
         User_Devices_Model::register_device($mobileid, $user_id);
     }
     // Now we have a fully registered device so lets update our user if we need to
     if ($firstname and $lastname and $email) {
         $user_id = User_Devices_Model::device_owner($mobileid);
         $user_name = $firstname . ' ' . $lastname;
         $user_email = $email;
         $user = ORM::factory('user', $user_id);
         $user->name = $user_name;
         $user->email = $user_email;
         if ($color) {
             $user->color = $color;
         }
         $user_id = $user->save();
         $user_id = $user_id->id;
     }
     // Get our user id if it hasn't already been set by one of the processes above
     if (!isset($user_id)) {
         $user_id = User_Devices_Model::device_owner($mobileid);
     }
     // Whew, now that all that is out of the way, do the flippin checkin!
     // FIRST, save the location
     $location = new Location_Model();
     $location->location_name = $lat . ',' . $lon;
     $location->latitude = $lat;
     $location->longitude = $lon;
     $location->location_date = date("Y-m-d H:i:s", time());
     $location_id = $location->save();
     // SECOND, save the checkin
     if (!$message) {
         $message = '';
     }
     $checkin = ORM::factory('checkin');
     $checkin->user_id = $user_id;
     $checkin->location_id = $location_id;
     $checkin->checkin_description = $message;
     $checkin->checkin_date = date("Y-m-d H:i:s", time());
     $checkin_id = $checkin->save();
     // THIRD, save the photo, if there is a photo
     if (isset($_FILES['photo'])) {
         $filename = upload::save('photo');
         $new_filename = 'ci_' . $user_id . '_' . time() . '_' . $this->getRandomString(4);
         $file_type = strrev(substr(strrev($filename), 0, 4));
         // IMAGE SIZES: 800X600, 400X300, 89X59
         // Large size
         Image::factory($filename)->resize(800, 600, Image::AUTO)->save(Kohana::config('upload.directory', TRUE) . $new_filename . $file_type);
         // Medium size
         Image::factory($filename)->resize(400, 300, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_m" . $file_type);
         // Thumbnail
         Image::factory($filename)->resize(89, 59, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . "_t" . $file_type);
         // Name the files for the DB
         $media_link = $new_filename . $file_type;
         $media_medium = $new_filename . '_m' . $file_type;
         $media_thumb = $new_filename . '_t' . $file_type;
         // Okay, now we have these three different files on the server, now check to see
         //	 if we should be dropping them on the CDN
         if (Kohana::config("cdn.cdn_store_dynamic_content")) {
             $media_link = cdn::upload($media_link);
             $media_medium = cdn::upload($media_medium);
             $media_thumb = cdn::upload($media_thumb);
             // We no longer need the files we created on the server. Remove them.
             $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
             unlink($local_directory . $new_filename . $file_type);
             unlink($local_directory . $new_filename . '_m' . $file_type);
             unlink($local_directory . $new_filename . '_t' . $file_type);
         }
         // Remove the temporary file
         unlink($filename);
         // Save to DB
         $media_photo = new Media_Model();
         $media_photo->location_id = $location_id;
         $media_photo->checkin_id = $checkin_id;
         $media_photo->media_type = 1;
         // Images
         $media_photo->media_link = $media_link;
         $media_photo->media_medium = $media_medium;
         $media_photo->media_thumb = $media_thumb;
         $media_photo->media_date = date("Y-m-d H:i:s", time());
         $media_photo->save();
     }
     $return = array("checkin_id" => $checkin_id->id, "user_id" => $user_id);
     // Hook on successful checkin
     Event::run('ushahidi_action.checkin_recorded', $checkin);
     return $return;
 }
 public function createMyPhoto($imgFilename)
 {
     $result = array("error" => true);
     $imgFilename_ext = pathinfo($imgFilename, PATHINFO_EXTENSION);
     $imgNewName = helper::generateHash(7);
     $imgOrigin = "origin_" . $imgNewName . "." . $imgFilename_ext;
     $imgNormal = "normal_" . $imgNewName . "." . $imgFilename_ext;
     $imgPreview = "preview_" . $imgNewName . "." . $imgFilename_ext;
     if ($this->checkImg($imgFilename)) {
         list($w, $h, $type) = getimagesize($imgFilename);
         if (rename($imgFilename, "../../" . TEMP_PATH . $imgOrigin)) {
             $imgFilename = "../../" . TEMP_PATH . $imgOrigin;
         }
         if ($type == IMAGETYPE_JPEG) {
             $this->img_resize($imgFilename, "../../" . TEMP_PATH . $imgNormal, 800, 0);
             $photo = new photo($this->db, $imgFilename, 512);
             imagejpeg($photo->getImgData(), "../../" . TEMP_PATH . $imgPreview, 100);
             unset($photo);
             $result['error'] = false;
         } elseif ($type == IMAGETYPE_PNG) {
             //PNG
             $this->img_resize($imgFilename, "../../" . TEMP_PATH . $imgNormal, 800, 0);
             $photo = new photo($this->db, $imgFilename, 512);
             imagepng($photo->getImgData(), "../../" . TEMP_PATH . $imgPreview);
             unset($photo);
             $result['error'] = false;
         } else {
             $result['error'] = true;
         }
     }
     if ($result['error'] === false) {
         $cdn = new cdn($this->db);
         $response = array();
         $response = $cdn->uploadMyPhoto("../../" . TEMP_PATH . $imgOrigin);
         if ($response['error'] === false) {
             $result['originPhotoUrl'] = $response['fileUrl'];
         }
         $response = $cdn->uploadMyPhoto("../../" . TEMP_PATH . $imgNormal);
         if ($response['error'] === false) {
             $result['normalPhotoUrl'] = $response['fileUrl'];
         }
         $response = $cdn->uploadMyPhoto("../../" . TEMP_PATH . $imgPreview);
         if ($response['error'] === false) {
             $result['previewPhotoUrl'] = $response['fileUrl'];
         }
         @unlink("../../" . TEMP_PATH . $imgOrigin);
         @unlink("../../" . TEMP_PATH . $imgNormal);
         @unlink("../../" . TEMP_PATH . $imgPreview);
     }
     return $result;
 }
Beispiel #13
0
 /**
  * 文件不存在时转向到此方法 创建缩略图
  *
  * 源文件不存在 显示默认图  font/indexbg.jpg
  * 应用自定义默认图放在 font/{$app_uniqueid}/indexbg.jpg
  *
  * @param host string
  * @param refer_to string required 文件路径
  *      如material/news/img/100x75/2012/05/20120529143609jSG7.jpg?21jj
  */
 function create()
 {
     $url = urldecode($this->input['refer_to']);
     $host = urldecode($this->input['host']);
     //$url = 'material/news/img/100x75/2012/05/20120529143609jSG7.jpg?21jj';
     if (empty($url) || empty($host)) {
         $this->readfile(CUR_CONF_PATH . 'font/indexbg.jpg', 'indexbg.jpg');
     } else {
         preg_match_all('/^\\/(.*?\\/.*?\\/)?(.*?\\/img\\/)([0-9]*)[x|-]([0-9]*)\\/(\\d{0,4}\\/\\d{0,2}\\/)(.*?)(\\.[a-zA-Z0-9_]*)(\\?\\w*)?/i', $url, $out);
         $tmp = explode('/', $out[2][0]);
         if ($tmp[0] == 'material') {
             $app_uniqueid = $tmp[1];
         } else {
             $app_uniqueid = $tmp[0];
         }
         $info = array('host' => $host, 'dir' => $out[2][0], 'filepath' => $out[5][0], 'filename' => $out[6][0], 'type' => $out[7][0], 'app_uniqueid' => $app_uniqueid);
         $size = array('label' => $out[3][0] . 'x' . $out[4][0], 'width' => $out[3][0], 'height' => $out[4][0], 'other_dir' => $out[5][0]);
         $IMG_DIR = $this->settings['imgdirs']['http://' . $info['host'] . '/'];
         if (!$IMG_DIR) {
             $IMG_DIR = IMG_DIR;
         }
         $filepath = $IMG_DIR . $info['dir'] . $info['filepath'] . $info['filename'] . ".json";
         $water_url = $position = "";
         if (file_exists($filepath)) {
             $json = json_decode(file_get_contents($filepath), true);
             //$water = $json['water'];   //原图加水印 缩略图不重复加水印
         }
         $path = $IMG_DIR . $info['dir'];
         $file = $path . $info['filepath'] . $info['filename'] . $info['type'];
         if (!file_exists($file) || !is_file($file)) {
             //文件不存在 显示默认图  font/indexbg.jpg
             //应用自定义默认图放在 font/{$app_uniqueid}/indexbg.jpg
             $default_img = CUR_CONF_PATH . 'font/indexbg.jpg';
             if (file_exists(CUR_CONF_PATH . 'font/' . $info['app_uniqueid'] . '/indexbg.jpg')) {
                 $default_img = CUR_CONF_PATH . 'font/' . $info['app_uniqueid'] . '/indexbg.jpg';
             }
             $this->readfile($default_img, 'indexbg.jpg');
         }
         $isSucc = hg_mk_images($file, $info['filename'] . $info['type'], $IMG_DIR . $info['dir'], $size, $water);
         if ($isSucc) {
             if (file_exists($filepath)) {
                 $thumb = json_decode(file_get_contents($filepath), true);
             } else {
                 $thumb = array();
             }
             $path = rtrim(realpath($path), '/') . '/';
             //记录绝对路径
             $thumb_tmp = $path . $size['label'] . "/" . $info['filepath'] . $info['filename'] . $info['type'];
             if (is_array($thumb['thumb']) && !in_array($thumb_tmp, $thumb['thumb']) || empty($thumb['thumb'])) {
                 // 判断这个列表不不存文件中
                 $thumb['thumb'][] = $thumb_tmp;
             }
             hg_file_write($filepath, json_encode($thumb));
             $header_url = 'http://' . $info['host'] . "/" . $info['dir'] . $size['label'] . "/" . $info['filepath'] . $info['filename'] . $info['type'];
             if ($this->settings['realtime_refresh_cdn'] && $this->settings['App_cdn']) {
                 include_once ROOT_PATH . 'lib/class/cdn.class.php';
                 $cdn = new cdn();
                 $cdn->push($header_url, '');
             }
             $file = $path . $size['label'] . "/" . $info['filepath'] . $info['filename'] . $info['type'];
             $this->readfile($file, $info['filename'] . $info['type'], $info['type']);
         } else {
             //缩略图创建失败  显示原图
             $this->readfile($file, $info['filename'] . $info['type']);
         }
     }
 }
Beispiel #14
0
 function index()
 {
     $this->template->content = new View('admin/badges');
     $this->template->content->title = Kohana::lang('ui_main.badges');
     // setup and initialize form field names
     $form = array('id' => '', 'name' => '', 'description' => '');
     //	copy the form as errors, so the errors will be stored with keys corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = FALSE;
     $form_action = "";
     if ($_POST) {
         $post = Validation::factory($_POST);
         //	 Add some filters
         $post->pre_filter('trim', TRUE);
         // Add some rules, the input field, followed by a list of checks, carried out in order
         $post->add_rules('action', 'required', 'alpha', 'length[1,1]');
         $post->add_rules('name', 'standard_text', 'length[1,250]');
         $post->add_rules('description', 'standard_text');
         $post->add_rules('image', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[100K]');
         if ($post->validate()) {
             // ADD
             if ($post->action == 'a') {
                 // Step 1. Save badge name and description
                 $badge = new Badge_Model();
                 $badge->name = $post->name;
                 $badge->description = $post->description;
                 $badge->save();
                 // Step 2. Save badge image
                 $filename = upload::save('image');
                 if ($filename) {
                     $new_filename = "badge_" . $badge->id . "_" . time();
                     $file_type = strrev(substr(strrev($filename), 0, 4));
                     // Large size
                     $l_name = $new_filename . $file_type;
                     Image::factory($filename)->save(Kohana::config('upload.directory', TRUE) . $l_name);
                     // Medium size
                     $m_name = $new_filename . '_m' . $file_type;
                     Image::factory($filename)->resize(80, 80, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $m_name);
                     // Thumbnail
                     $t_name = $new_filename . '_t' . $file_type;
                     Image::factory($filename)->resize(60, 60, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $t_name);
                     // Name the files for the DB
                     $media_link = $l_name;
                     $media_medium = $m_name;
                     $media_thumb = $t_name;
                     // Okay, now we have these three different files on the server, now check to see
                     //   if we should be dropping them on the CDN
                     if (Kohana::config("cdn.cdn_store_dynamic_content")) {
                         $cdn = new cdn();
                         $media_link = $cdn->upload($media_link);
                         $media_medium = $cdn->upload($media_medium);
                         $media_thumb = $cdn->upload($media_thumb);
                         // We no longer need the files we created on the server. Remove them.
                         $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
                         unlink($local_directory . $new_filename . $file_type);
                         unlink($local_directory . $new_filename . '_m' . $file_type);
                         unlink($local_directory . $new_filename . '_t' . $file_type);
                     }
                     // Remove the temporary file
                     unlink($filename);
                     // Delete old badge image
                     ORM::factory('media')->where(array('badge_id' => $badge->id))->delete_all();
                     // Save new badge image
                     $media = new Media_Model();
                     $media->badge_id = $badge->id;
                     $media->media_type = 1;
                     // Image
                     $media->media_link = $media_link;
                     $media->media_medium = $media_medium;
                     $media->media_thumb = $media_thumb;
                     $media->media_date = date("Y-m-d H:i:s", time());
                     $media->save();
                 }
             }
             // ASSIGN USER
             if ($post->action == 'b') {
                 $badge_user = new Badge_User_Model();
                 $badge_user->badge_id = $post->badge_id;
                 $badge_user->user_id = $post->assign_user;
                 $badge_user->save();
             }
             // REVOKE USER
             if ($post->action == 'r') {
                 ORM::factory('badge_user')->where(array('badge_id' => (int) $post->badge_id, 'user_id' => (int) $post->revoke_user))->delete_all();
             } elseif ($post->action == 'd') {
                 // Remove from badge table
                 ORM::factory('badge')->delete((int) $post->badge_id);
                 // Remove from media
                 ORM::factory('media')->where(array('badge_id' => (int) $post->badge_id))->delete_all();
                 // Remove from assignment
                 ORM::factory('badge_user')->where(array('badge_id' => (int) $post->badge_id))->delete_all();
             }
         } else {
             $errors = arr::overwrite($errors, $post->errors('badges'));
             $form_error = TRUE;
         }
     }
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     $this->template->content->form_action = $form_action;
     // Get badges
     $this->template->content->badges = Badge_Model::badges();
     $this->template->content->total_items = count($this->template->content->badges);
     // Get all users for dropdowns
     $users_result = ORM::factory('user')->orderby('name', 'asc')->find_all();
     $users = array();
     foreach ($users_result as $user) {
         $users[$user->id] = $user->username;
     }
     $this->template->content->users = $users;
     // Javascript Header
     $this->template->js = new View('admin/badges_js');
 }
Beispiel #15
0
 /**
  * Site Settings
  */
 function site()
 {
     $this->template->content = new View('admin/site');
     $this->template->content->title = Kohana::lang('ui_admin.settings');
     $this->template->js = new View('admin/site_js');
     // setup and initialize form field names
     $form = array('site_name' => '', 'site_tagline' => '', 'banner_image' => '', 'delete_banner_image' => '', 'site_email' => '', 'alerts_email' => '', 'site_language' => '', 'site_timezone' => '', 'site_message' => '', 'site_copyright_statement' => '', 'site_submit_report_message' => '', 'site_contact_page' => '', 'items_per_page' => '', 'items_per_page_admin' => '', 'blocks_per_row' => '', 'allow_alerts' => '', 'allow_reports' => '', 'allow_comments' => '', 'allow_feed' => '', 'allow_stat_sharing' => '', 'allow_clustering' => '', 'cache_pages' => '', 'cache_pages_lifetime' => '', 'private_deployment' => '', 'checkins' => '', 'default_map_all' => '', 'google_analytics' => '', 'twitter_hashtags' => '', 'api_akismet' => '');
     //	Copy the form as errors, so the errors will be stored with keys
     //	corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = FALSE;
     // Retrieve Current Settings
     $settings = ORM::factory('settings', 1);
     // check, has the form been submitted, if so, setup validation
     if ($_POST) {
         //print_r($_POST);exit;
         // Instantiate Validation, use $post, so we don't overwrite $_POST
         // fields with our own things
         $post = new Validation($_POST);
         // Add some filters
         $post->pre_filter('trim', TRUE);
         // Add some rules, the input field, followed by a list of checks, carried out in order
         $post->add_rules('site_name', 'required', 'length[3,250]');
         $post->add_rules('site_tagline', 'length[3,250]');
         $post->add_rules('site_email', 'email', 'length[4,100]');
         //$post->add_rules('alerts_email','required', 'email', 'length[4,100]');
         //$post->add_rules('site_message', 'standard_text');
         $post->add_rules('site_copyright_statement', 'length[4,600]');
         $post->add_rules('site_language', 'required', 'length[5, 5]');
         //$post->add_rules('site_timezone','required', 'between[10,50]');
         $post->add_rules('site_contact_page', 'required', 'between[0,1]');
         $post->add_rules('items_per_page', 'required', 'between[10,50]');
         $post->add_rules('items_per_page_admin', 'required', 'between[10,50]');
         $post->add_rules('blocks_per_row', 'required', 'numeric');
         $post->add_rules('allow_alerts', 'required', 'between[0,1]');
         $post->add_rules('allow_reports', 'required', 'between[0,1]');
         $post->add_rules('allow_comments', 'required', 'between[0,2]');
         $post->add_rules('allow_feed', 'required', 'between[0,1]');
         $post->add_rules('allow_stat_sharing', 'required', 'between[0,1]');
         $post->add_rules('allow_clustering', 'required', 'between[0,1]');
         $post->add_rules('cache_pages', 'required', 'between[0,1]');
         $post->add_rules('cache_pages_lifetime', 'required', 'in_array[300,600,900,1800]');
         $post->add_rules('private_deployment', 'required', 'between[0,1]');
         $post->add_rules('checkins', 'required', 'between[0,1]');
         $post->add_rules('default_map_all', 'required', 'alpha_numeric', 'length[6,6]');
         $post->add_rules('google_analytics', 'length[0,20]');
         $post->add_rules('twitter_hashtags', 'length[0,500]');
         $post->add_rules('api_akismet', 'length[0,100]', 'alpha_numeric');
         // Add rules for file upload
         $files = Validation::factory($_FILES);
         $files->add_rules('banner_image', 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[250K]');
         // Test to see if things passed the rule checks
         if ($post->validate() and $files->validate()) {
             // Yes! everything is valid
             $settings = new Settings_Model(1);
             $settings->site_name = $post->site_name;
             $settings->site_tagline = $post->site_tagline;
             $settings->site_email = $post->site_email;
             $settings->alerts_email = $post->alerts_email;
             $settings->site_message = $post->site_message;
             $settings->site_copyright_statement = $post->site_copyright_statement;
             $settings->site_submit_report_message = $post->site_submit_report_message;
             $settings->site_language = $post->site_language;
             $settings->site_timezone = $post->site_timezone;
             if ($settings->site_timezone == "0") {
                 // "0" is the "Server Timezone" setting and it needs to be null in the db
                 $settings->site_timezone = NULL;
             }
             $settings->site_contact_page = $post->site_contact_page;
             $settings->items_per_page = $post->items_per_page;
             $settings->items_per_page_admin = $post->items_per_page_admin;
             $settings->blocks_per_row = $post->blocks_per_row;
             $settings->allow_alerts = $post->allow_alerts;
             $settings->allow_reports = $post->allow_reports;
             $settings->allow_comments = $post->allow_comments;
             $settings->allow_feed = $post->allow_feed;
             $settings->allow_stat_sharing = $post->allow_stat_sharing;
             $settings->allow_clustering = $post->allow_clustering;
             $settings->cache_pages = $post->cache_pages;
             $settings->cache_pages_lifetime = $post->cache_pages_lifetime;
             $settings->private_deployment = $post->private_deployment;
             $settings->checkins = $post->checkins;
             $settings->default_map_all = $post->default_map_all;
             $settings->google_analytics = $post->google_analytics;
             $settings->twitter_hashtags = $post->twitter_hashtags;
             $settings->api_akismet = $post->api_akismet;
             $settings->date_modify = date("Y-m-d H:i:s", time());
             $settings->save();
             // Deal with banner image now
             // Check if deleting or updating a new image (or doing nothing)
             if (isset($post->delete_banner_image) and $post->delete_banner_image == 1) {
                 // Delete old badge image
                 ORM::factory('media')->delete($settings->site_banner_id);
                 // Remove from DB table
                 $settings = new Settings_Model(1);
                 $settings->site_banner_id = NULL;
                 $settings->save();
             } else {
                 // We aren't deleting, so try to upload if we are uploading an image
                 $filename = upload::save('banner_image');
                 if ($filename) {
                     $new_filename = "banner_" . time();
                     $file_type = strrev(substr(strrev($filename), 0, 4));
                     // Large size
                     $l_name = $new_filename . $file_type;
                     Image::factory($filename)->save(Kohana::config('upload.directory', TRUE) . $l_name);
                     // Medium size
                     $m_name = $new_filename . "_m" . $file_type;
                     Image::factory($filename)->resize(80, 80, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $m_name);
                     // Thumbnail
                     $t_name = $new_filename . "_t" . $file_type;
                     Image::factory($filename)->resize(60, 60, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $t_name);
                     // Name the files for the DB
                     $media_link = $l_name;
                     $media_medium = $m_name;
                     $media_thumb = $t_name;
                     // Okay, now we have these three different files on the server, now check to see
                     //   if we should be dropping them on the CDN
                     if (Kohana::config("cdn.cdn_store_dynamic_content")) {
                         $media_link = cdn::upload($media_link);
                         $media_medium = cdn::upload($media_medium);
                         $media_thumb = cdn::upload($media_thumb);
                         // We no longer need the files we created on the server. Remove them.
                         $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
                         unlink($local_directory . $l_name);
                         unlink($local_directory . $m_name);
                         unlink($local_directory . $t_name);
                     }
                     // Remove the temporary file
                     unlink($filename);
                     // Save banner image in the media table
                     $media = new Media_Model();
                     $media->media_type = 1;
                     // Image
                     $media->media_link = $media_link;
                     $media->media_medium = $media_medium;
                     $media->media_thumb = $media_thumb;
                     $media->media_date = date("Y-m-d H:i:s", time());
                     $media->save();
                     // Save new banner image in settings
                     $settings = new Settings_Model(1);
                     $settings->site_banner_id = $media->id;
                     $settings->save();
                 }
             }
             // Delete Settings Cache
             $this->cache->delete('settings');
             $this->cache->delete_tag('settings');
             // Everything is A-Okay!
             $form_saved = TRUE;
             // Action::site_settings_modified - Site settings have changed
             Event::run('ushahidi_action.site_settings_modified');
             // repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
         } else {
             // repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // populate the error fields, if any
             if (is_array($files->errors()) and count($files->errors()) > 0) {
                 // Error with file upload
                 $errors = arr::overwrite($errors, $files->errors('settings'));
             } else {
                 // Error with other form filed
                 $errors = arr::overwrite($errors, $post->errors('settings'));
             }
             $form_error = TRUE;
         }
     } else {
         $form = array('site_name' => $settings->site_name, 'site_tagline' => $settings->site_tagline, 'site_banner_id' => $settings->site_banner_id, 'site_email' => $settings->site_email, 'alerts_email' => $settings->alerts_email, 'site_message' => $settings->site_message, 'site_copyright_statement' => $settings->site_copyright_statement, 'site_submit_report_message' => $settings->site_submit_report_message, 'site_language' => $settings->site_language, 'site_timezone' => $settings->site_timezone, 'site_contact_page' => $settings->site_contact_page, 'items_per_page' => $settings->items_per_page, 'items_per_page_admin' => $settings->items_per_page_admin, 'blocks_per_row' => $settings->blocks_per_row, 'allow_alerts' => $settings->allow_alerts, 'allow_reports' => $settings->allow_reports, 'allow_comments' => $settings->allow_comments, 'allow_feed' => $settings->allow_feed, 'allow_stat_sharing' => $settings->allow_stat_sharing, 'allow_clustering' => $settings->allow_clustering, 'cache_pages' => $settings->cache_pages, 'cache_pages_lifetime' => $settings->cache_pages_lifetime, 'private_deployment' => $settings->private_deployment, 'checkins' => $settings->checkins, 'default_map_all' => $settings->default_map_all, 'google_analytics' => $settings->google_analytics, 'twitter_hashtags' => $settings->twitter_hashtags, 'api_akismet' => $settings->api_akismet);
     }
     // Get banner image
     if ($settings->site_banner_id != NULL) {
         $banner = ORM::factory('media')->find($settings->site_banner_id);
         $this->template->content->banner = url::convert_uploaded_to_abs($banner->media_link);
         $this->template->content->banner_m = url::convert_uploaded_to_abs($banner->media_medium);
         $this->template->content->banner_t = url::convert_uploaded_to_abs($banner->media_thumb);
     } else {
         $this->template->content->banner = NULL;
         $this->template->content->banner_m = NULL;
         $this->template->content->banner_t = NULL;
     }
     $this->template->colorpicker_enabled = TRUE;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     $this->template->content->items_per_page_array = array('10' => '10 Items', '20' => '20 Items', '30' => '30 Items', '50' => '50 Items');
     $blocks_per_row_array = array();
     for ($i = 1; $i <= 21; $i++) {
         $blocks_per_row_array[$i] = $i;
     }
     $this->template->content->blocks_per_row_array = $blocks_per_row_array;
     $this->template->content->yesno_array = array('1' => strtoupper(Kohana::lang('ui_main.yes')), '0' => strtoupper(Kohana::lang('ui_main.no')));
     $this->template->content->comments_array = array('1' => strtoupper(Kohana::lang('ui_main.yes') . " - " . Kohana::lang('ui_admin.approve_auto')), '2' => strtoupper(Kohana::lang('ui_main.yes') . " - " . Kohana::lang('ui_admin.approve_manual')), '0' => strtoupper(Kohana::lang('ui_main.no')));
     $this->template->content->cache_pages_lifetime_array = array('300' => '5 ' . Kohana::lang('ui_admin.minutes'), '600' => '10 ' . Kohana::lang('ui_admin.minutes'), '900' => '15 ' . Kohana::lang('ui_admin.minutes'), '1800' => '30 ' . Kohana::lang('ui_admin.minutes'));
     //Generate all timezones
     $site_timezone_array = array();
     $site_timezone_array[0] = Kohana::lang('ui_admin.server_time');
     foreach (timezone_identifiers_list() as $timezone) {
         $site_timezone_array[$timezone] = $timezone;
     }
     $this->template->content->site_timezone_array = $site_timezone_array;
     // Generate Available Locales
     $locales = locale::get_i18n();
     $this->template->content->locales_array = $locales;
     $this->cache->set('locales', $locales, array('locales'), 604800);
 }
Beispiel #16
0
 /**
  * Function to save news, photos and videos
  *
  * @param mixed $location_model
  * @param mixed $post
  *
  */
 public static function save_media($post, $incident)
 {
     // Delete Previous Entries
     ORM::factory('media')->where('incident_id', $incident->id)->where('media_type <> 1')->delete_all();
     // a. News
     foreach ($post->incident_news as $item) {
         if (!empty($item)) {
             $news = new Media_Model();
             $news->location_id = $incident->location_id;
             $news->incident_id = $incident->id;
             $news->media_type = 4;
             // News
             $news->media_link = $item;
             $news->media_date = date("Y-m-d H:i:s", time());
             $news->save();
         }
     }
     // b. Video
     foreach ($post->incident_video as $item) {
         if (!empty($item)) {
             $video = new Media_Model();
             $video->location_id = $incident->location_id;
             $video->incident_id = $incident->id;
             $video->media_type = 2;
             // Video
             $video->media_link = $item;
             $video->media_date = date("Y-m-d H:i:s", time());
             $video->save();
         }
     }
     // c. Photos
     $filenames = upload::save('incident_photo');
     if (empty($filenames)) {
         $filenames = array();
     }
     $i = 1;
     foreach ($filenames as $filename) {
         $new_filename = $incident->id . '_' . $i . '_' . time();
         $file_type = strrev(substr(strrev($filename), 0, 4));
         // IMAGE SIZES: 800X600, 400X300, 89X59
         // Large size
         Image::factory($filename)->resize(800, 600, Image::AUTO)->save(Kohana::config('upload.directory', TRUE) . $new_filename . $file_type);
         // Medium size
         Image::factory($filename)->resize(400, 300, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . '_m' . $file_type);
         // Thumbnail
         Image::factory($filename)->resize(89, 59, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $new_filename . '_t' . $file_type);
         // Name the files for the DB
         $media_link = $new_filename . $file_type;
         $media_medium = $new_filename . '_m' . $file_type;
         $media_thumb = $new_filename . '_t' . $file_type;
         // Okay, now we have these three different files on the server, now check to see
         //   if we should be dropping them on the CDN
         if (Kohana::config("cdn.cdn_store_dynamic_content")) {
             $media_link = cdn::upload($media_link);
             $media_medium = cdn::upload($media_medium);
             $media_thumb = cdn::upload($media_thumb);
             // We no longer need the files we created on the server. Remove them.
             $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
             unlink($local_directory . $new_filename . $file_type);
             unlink($local_directory . $new_filename . '_m' . $file_type);
             unlink($local_directory . $new_filename . '_t' . $file_type);
         }
         // Remove the temporary file
         unlink($filename);
         // Save to DB
         $photo = new Media_Model();
         $photo->location_id = $incident->location_id;
         $photo->incident_id = $incident->id;
         $photo->media_type = 1;
         // Images
         $photo->media_link = $media_link;
         $photo->media_medium = $media_medium;
         $photo->media_thumb = $media_thumb;
         $photo->media_date = date("Y-m-d H:i:s", time());
         $photo->save();
         $i++;
     }
 }
Beispiel #17
0
 /**
  * Upgrades files over time based on users hitting the site
  *
  * @return bool TRUE if the upgrade is successful, FALSE otherwise
  */
 public static function gradual_upgrade()
 {
     self::connection();
     if (!self::$cdn) {
         throw new Kohana_Exception('CDN provider not specified');
     }
     // Get the table prefix
     $table_prefix = Kohana::config('database.default.table_prefix');
     // Select at random since admin may not want every user to initiate a CDN upload
     if (rand(1, intval(Kohana::config('cdn.cdn_gradual_upgrade'))) == 1) {
         $query = 'SELECT id, media_link, media_medium, media_thumb ' . 'FROM ' . $table_prefix . 'media ' . 'WHERE media_type = 1 AND media_link NOT LIKE \'http%\' LIMIT 1';
         // Database instance for fetch and update operations
         $db = Database::instance();
         $media_links = $db->query($query);
         $uploaded_flag = false;
         foreach ($media_links as $row) {
             // Upload files to the CDN
             $new_large = self::$cdn->upload($row->media_link);
             $new_medium = self::$cdn->upload($row->media_medium);
             $new_thumb = self::$cdn->upload($row->media_thumb);
             // Update the entry for the media file in the DB
             $db->update('media', array('media_link' => $new_large, 'media_medium' => $new_medium, 'media_thumb' => $new_thumb), array('id' => $row->id));
             // Remove old files
             $local_directory = Kohana::config('upload.directory', TRUE);
             $local_directory = rtrim($local_directory, '/') . '/';
             unlink($local_directory . $row->media_link);
             unlink($local_directory . $row->media_medium);
             unlink($local_directory . $row->media_thumb);
             $uploaded_flag = true;
         }
         // If we didn't have any more user uploaded images to upload, move on to category images
         if ($uploaded_flag == false) {
             $query = 'SELECT id, category_image, category_image_thumb ' . 'FROM ' . $table_prefix . 'category ' . 'WHERE category_image NOT LIKE \'http%\' LIMIT 1';
             // Fetch
             $category_images = $db->query($query);
             foreach ($category_images as $row) {
                 // Upload files to the CDN
                 $new_category_image = $this->cdn->upload($row->category_image);
                 $new_category_image_thumb = $this->cdn->upload($row->category_image_thumb);
                 // Update the entry for the media file in the DB
                 $db->update('category', array('category_image' => $new_category_image, 'category_image_thumb' => $new_category_image_thumb), array('id' => $row->id));
                 // Remove old files
                 $local_directory = Kohana::config('upload.directory', TRUE);
                 $local_directory = rtrim($local_directory, '/') . '/';
                 unlink($local_directory . $row['category_image']);
                 unlink($local_directory . $row['category_image_thumb']);
                 $uploaded_flag = true;
             }
         }
         // If we are done with category images, move on to KML layers
         if ($uploaded_flag == false) {
             // Grab a KML file we have locally that isn't linking to an external URL
             $query = 'SELECT id, layer_file ' . 'FROM ' . $table_prefix . 'layer ' . 'WHERE layer_url = \'\' LIMIT 1';
             $layers = $db->query($query);
             foreach ($layers as $row) {
                 $layer_file = $row->layer_file;
                 // Upload the file to the CDN
                 $layer_url = cdn::upload($layer_file);
                 // We no longer need the files we created on the server. Remove them.
                 $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
                 unlink($local_directory . $layer_file);
                 $layer = new Layer_Model($row->id);
                 $layer->layer_url = $layer_url;
                 $layer->layer_file = '';
                 $layer->save();
             }
         }
         // Garbage collection
         unset($db, $media_links, $category_images);
         return TRUE;
     }
     return FALSE;
 }
Beispiel #18
0
#!/usr/bin/env php
<?php 
require_once dirname(dirname(dirname(dirname(__FILE__)))) . '/zesk.inc';
Module::load('markdown');
cdn::add('/share/', '/share/', ZESK_ROOT . 'share/');
zesk::factory("Command_Markdown")->go();
 private function _handle_new_decayimage_fileupload($id)
 {
     $filename = upload::save('decayimage_file');
     if ($filename) {
         $new_filename = "decayimage_" . $id . "_" . time();
         // Name the files for the DB
         $cat_img_file = $new_filename . ".png";
         $cat_img_thumb_file = $new_filename . "_16x16.png";
         // Resize Image to 32px if greater
         Image::factory($filename)->resize(32, 32, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $cat_img_file);
         // Create a 16x16 version too
         Image::factory($filename)->resize(16, 16, Image::HEIGHT)->save(Kohana::config('upload.directory', TRUE) . $cat_img_thumb_file);
     } else {
         Kohana::log('error', 'we were not able to save the file upload');
         return false;
     }
     // Okay, now we have these three different files on the server, now check to see
     //   if we should be dropping them on the CDN
     if (Kohana::config("cdn.cdn_store_dynamic_content")) {
         $cat_img_file = cdn::upload($cat_img_file);
         $cat_img_thumb_file = cdn::upload($cat_img_thumb_file);
         // We no longer need the files we created on the server. Remove them.
         $local_directory = rtrim(Kohana::config('upload.directory', TRUE), '/') . '/';
         unlink($local_directory . $new_filename . ".png");
         unlink($local_directory . $new_filename . "_16x16.png");
     }
     // Remove the temporary file
     if (file_exists($filename)) {
         unlink($filename);
     }
     // Delete Old Image, unless its the default image
     $decayimage = ORM::factory('decayimage')->where('id', $id);
     if ($decayimage && $id != 0) {
         $category_old_image = $decayimage->decayimage_image;
         if (!empty($category_old_image)) {
             if (file_exists(Kohana::config('upload.directory', TRUE) . $category_old_image)) {
                 unlink(Kohana::config('upload.directory', TRUE) . $category_old_image);
             } elseif (Kohana::config("cdn.cdn_store_dynamic_content") and valid::url($category_old_image)) {
                 cdn::delete($category_old_image);
             }
         }
     }
     return array($cat_img_file, $cat_img_thumb_file);
 }