7c25db7f8fb86dc0949f4c5c8d6d52b7c8c770d4
[lhc/web/wiklou.git] / js2 / mwEmbed / libAddMedia / remoteSearchDriver.js
1 /*
2 * a library for doing remote media searches
3 *
4 * initial targeted archives are:
5 the local wiki
6 wikimedia commons
7 metavid
8 and archive.org
9 */
10 loadGM({
11 "mwe-add_media_wizard" : "Add media wizard",
12 "mwe-media_search" : "Media search",
13 "rsd_box_layout" : "Box layout",
14 "rsd_list_layout" : "List layout",
15 "rsd_results_desc" : "Results",
16 "rsd_results_next" : "next",
17 "rsd_results_prev" : "previous",
18 "rsd_no_results" : "No search results for <b>$1<\/b>",
19 "mwe-upload_tab" : "Upload",
20 "rsd_layout" : "Layout : ",
21 "rsd_resource_edit" : "Edit resource : $1",
22 "mwe-resource_description_page" : "Resource description page",
23 "rsd_local_resource_title" : "Local resource title",
24 "rsd_do_insert" : "Do insert",
25 "mwe-cc_title" : "Creative Commons",
26 "mwe-cc_by_title" : "Attribution",
27 "mwe-cc_nc_title" : "Noncommercial",
28 "mwe-cc_nd_title" : "No Derivative Works",
29 "mwe-cc_sa_title" : "Share Alike",
30 "mwe-cc_pd_title" : "Public Domain",
31 "mwe-unknown_license" : "Unknown license",
32 "mwe-no_import_by_url" : "This user or wiki <b>can not<\/b> import assets from remote URLs.<\/p><p>Do you need to login?<\/p><p>If permissions are set, you may have to enable $wgAllowCopyUploads (<a href=\"http : \/\/www.mediawiki.org\/wiki\/Manual : $wgAllowCopyUploads\">more information<\/a>).<\/p>",
33 "mwe-results_from" : "Results from <a href=\"$1\" target=\"_new\" >$2<\/a>",
34 "mwe-missing_desc_see_source" : "This asset is missing a description. Please see the [$1 orginal source] and help describe it.",
35 "rsd_config_error" : "Add media wizard configuration error : $1",
36
37 "mwe-your_recent_uploads" : "Your recent uploads",
38 "mwe-upload_a_file": "Upload a new file",
39
40 "mwe-resource_page_desc":"Resource page description:",
41 "mwe-edit_resource_desc": "Edit wiki text resource description:",
42 "mwe-local_resource_title": "Local resource title:",
43 "mwe-watch_this_page": "Watch this page",
44 "mwe-do_import_resource": "Import resource",
45 "mwe-update_preview": "Update preview",
46 "mwe-cancel_import": "Cancel import",
47 "mwe-importing_asset" : "Importing asset",
48 "mwe-preview_insert_resource": "Preview insert of resource: $1"
49 });
50 var default_remote_search_options = {
51 'profile':'mediawiki_edit',
52 'target_container':null, //the div that will hold the search interface
53 //if using a modeal dialog (instead of target_container) how close to the edge of the window should we go:
54 'modal_edge_padding':'20px',
55
56 'target_invocation': null, //the button or link that will invoke the search interface
57
58 'default_provider_id':'all', //all or one of the content_providers ids
59
60 'caret_pos':null,
61 'local_wiki_api_url':null,
62
63 //can be 'api', 'form', 'autodetect', 'remote_link'
64 'import_url_mode': 'autodetect',
65
66 'target_title':null,
67
68 'target_textbox':null,
69 'target_render_area': null, //where output render should go:
70 'instance_name': null, //a globally accessible callback instance name
71 'default_query':null, //default search query
72 //specific to sequence profile
73 'p_seq':null,
74 'cFileNS':'File', //what is the cannonical namespace for images
75 //@@todo (should get that from the api or inpage vars)
76
77 'enable_upload_tab':true, // if we want to enable an uploads tab:
78 'upload_api_target' : 'http://localhost/wiki_trunk/api.php' // can be local or the url of the upload api.
79 }
80 if(typeof wgServer == 'undefined')
81 wgServer = '';
82 if(typeof wgScriptPath == 'undefined')
83 wgScriptPath = '';
84 if(typeof stylepath == 'undefined')
85 stylepath = '';
86
87 /*
88 * base remoteSearch Driver interface
89 */
90 var remoteSearchDriver = function(iObj){
91 return this.init( iObj );
92 }
93 remoteSearchDriver.prototype = {
94 results_cleared:false,
95 //here we define the set of possible media content providers:
96 main_search_options:{
97 'selprovider':{
98 'title': 'Select Providers'
99 },
100 'advanced_search':{
101 'title': 'Advanced Options'
102 }
103 },
104 /*
105 * sets the default display item:
106 * can be any content_providers key or 'all'
107 */
108 disp_item : 'wiki_commons',
109 /** the default content providers list.
110 *
111 * (should be note that special tabs like "upload" and "combined" don't go into the content proviers list:
112 * @note do not use double underscore in content providers names (used for id lookup)
113 *
114 * @@todo we will want to load more per user-preference and per category lookup
115 */
116 content_providers:{
117 /*content_providers documentation:
118 * @@todo we should move the bulk of the configuration to each file
119 *
120
121 @enabled: whether the search provider can be selected
122 @checked: whether the search provider will show up as seleatable tab (todo: user prefrence)
123 @d: default: if the current cp should be displayed (only one should be the default)
124 @title: the title of the search provider
125 @desc: can use html... todo: need to localize
126 @api_url: the url to query against given the library type:
127 @lib: the search library to use corresponding to the
128 search object ie: 'mediaWiki' = new mediaWikiSearchSearch()
129 @tab_img: the tab image (if set to false use title text)
130 if === "ture" use standard location skin/images/{cp_id}_tab.png
131 if === string use as url for image
132
133 @linkback_icon default is: /wiki/skins/common/images/magnify-clip.png
134
135 //domain insert: two modes: simple config or domain list:
136 @local : if the content provider assets need to be imported or not.
137 @local_domains : sets of domains for which the content is local
138 //@@todo should query wgForeignFileRepos setting maybe interwikimap from the api
139 */
140 'this_wiki':{
141 'enabled': 1,
142 'checked': 1,
143 'title' : 'This Wiki',
144 'desc' : '(should be updated with the proper text) maybe import from some config value',
145 'api_url': ( wgServer && wgScriptPath )? wgServer + wgScriptPath+ '/api.php': null,
146 'lib' : 'mediaWiki',
147 'local' : true,
148 'tab_img': false
149 },
150 'wiki_commons':{
151 'enabled': 1,
152 'checked': 1,
153 'title' :'Wikimedia Commons',
154 'desc' : 'Wikimedia Commons is a media file repository making available public domain '+
155 'and freely-licensed educational media content (images, sound and video clips) to all.',
156 'homepage': 'http://commons.wikimedia.org/wiki/Main_Page',
157 'api_url':'http://commons.wikimedia.org/w/api.php',
158 'lib' :'mediaWiki',
159 'resource_prefix': 'WC_', //prefix on imported resources (not applicable if the repository is local)
160
161 //list all the domains where commons is local?
162 // probably should set this some other way by doing an api query
163 // or by seeding this config when calling the remote search?
164 'local_domains': ['wikimedia','wikipedia','wikibooks'],
165 //specific to wiki commons config:
166 'search_title':false, //disable title search
167 //set up default range limit
168 'offset' : 0,
169 'limit' : 30,
170 'tab_img':true
171 },
172 'archive_org':{
173 'enabled':1,
174 'checked':1,
175 'title' : 'Archive.org',
176 'desc' : 'The Internet Archive, a digital library of cultural artifacts',
177 'homepage':'http://www.archive.org/about/about.php',
178
179 'api_url':'http://homeserver7.us.archive.org:8983/solr/select',
180 'lib' : 'archiveOrg',
181 'local' : false,
182 'resource_prefix': 'AO_',
183 'tab_img':true
184 },
185 'metavid':{
186 'enabled':1,
187 'checked':1,
188 'title' :'Metavid.org',
189 'homepage':'http://metavid.org',
190 'desc' : 'Metavid hosts thousands of hours of US house and senate floor proceedings',
191 'api_url':'http://metavid.org/w/index.php?title=Special:MvExportSearch',
192 'lib' : 'metavid',
193 'local' :false, //if local set to true we can use local
194 'resource_prefix': 'MV_', //what prefix to use on imported resources
195
196 'local_domains': ['metavid'], // if the domain name contains metavid
197 // no need to import metavid content to metavid sites
198
199 'stream_import_key': 'mv_ogg_low_quality', // which stream to import, could be mv_ogg_high_quality
200 //or flash stream, see ROE xml for keys
201
202 'remote_embed_ext': false, //if running the remoteEmbed extension no need to copy local
203 //syntax will be [remoteEmbed:roe_url link title]
204 'tab_img':true
205 }
206 },
207 //define the licenses
208 // ... this will get complicated quick...
209 // (just look at complexity for creative commons without exessive "duplicate data")
210 // ie cc_by could be "by/3.0/us/" or "by/2.1/jp/" to infinitum...
211 // some complexity should be negated by license equivalances.
212
213 // but we will have to abstract into another class let content providers provide license urls
214 // and we have to clone the license object and allow local overrides
215
216 licenses:{
217 //for now only support creative commons type licenses
218 //used page: http://creativecommons.org/licenses/
219 'cc':{
220 'base_img_url':'http://upload.wikimedia.org/wikipedia/commons/thumb/',
221 'base_license_url': 'http://creativecommons.org/licenses/',
222 'licenses':{
223 'by': 'by/3.0/',
224 'by-sa': 'by-sa/3.0/',
225 'by-nc-nd': 'by-nc-nd/3.0/',
226 'by-nc': 'by-nc/3.0/',
227 'by-nd': 'by-nd/3.0/',
228 'by-nc-sa': 'by-nc-sa/3.0/',
229 'by-sa': 'by-nc/3.0',
230 'pd': 'publicdomain/'
231 },
232 'license_img':{
233 'by':{
234 'im':'1/11/Cc-by_new_white.svg/20px-Cc-by_new_white.svg.png'
235 },
236 'nc':{
237 'im':'2/2f/Cc-nc_white.svg/20px-Cc-nc_white.svg.png'
238 },
239 'nd':{
240 'im':'b/b3/Cc-nd_white.svg/20px-Cc-nd_white.svg.png'
241 },
242 'sa':{
243 'im':'d/df/Cc-sa_white.svg/20px-Cc-sa_white.svg.png'
244 },
245 'pd':{
246 'im':'5/51/Cc-pd-new_white.svg/20px-Cc-pd-new_white.svg.png'
247 }
248 }
249 }
250 },
251 /*
252 * getlicenseImgSet
253 * @param license_key the license key (ie "by-sa" or "by-nc-sa" etc)
254 */
255 getlicenseImgSet: function( licenseObj ){
256 //js_log('output images: '+ imgs);
257 return '<div class="rsd_license" title="'+ licenseObj.title + '" >' +
258 '<a target="_new" href="'+ licenseObj.lurl +'" ' +
259 'title="' + licenseObj.title + '">'+
260 licenseObj.img_html +
261 '</a>'+
262 '</div>';
263 },
264 /*
265 * getLicenceKeyFromKey
266 * @param license_key the key of the license (must be defined in: this.licenses.cc.licenses)
267 */
268 getLicenceFromKey:function( license_key , force_url){
269 if( typeof( this.licenses.cc.licenses[ license_key ]) == 'undefined')
270 return js_error('could not find:' + license_key);
271 //set the current license pointer:
272 var cl = this.licenses.cc;
273 var title = gM('mwe-cc_title');
274 var imgs = '';
275 var license_set = license_key.split('-');
276 for(var i=0;i < license_set.length; i++){
277 lkey = license_set[i];
278 title += ' ' + gM( 'mwe-cc_' + lkey + '_title');
279 imgs +='<img class="license_desc" width="20" src="' + cl.base_img_url +
280 cl.license_img[ lkey ].im + '">';
281 }
282 var url = (force_url) ? force_url : cl.base_license_url + cl.licenses[ license_key ];
283 return {
284 'title' : title,
285 'img_html' : imgs,
286 'key' : license_key,
287 'lurl' : url
288 };
289 },
290 /*
291 * getLicenceKeyFromUrl
292 * @param licence_url the url of the license
293 */
294 getLicenceFromUrl: function( license_url ){
295 //js_log("getLicenceFromUrl::" + license_url);
296 //first do a direct lookup check:
297 for(var i in this.licenses.cc.licenses){
298 var lkey = this.licenses.cc.licenses[i].split('/')[0];
299 //guess by url trim
300 if( parseUri(license_url).path.indexOf('/'+ lkey +'/') != -1){
301 return this.getLicenceFromKey( i , license_url);
302 }
303 }
304 //could not find it return mwe-unknown_license
305 return {
306 'title' : gM('mwe-unknown_license'),
307 'img_html' : '<span>' + gM('mwe-unknown_license') + '</span>',
308 'lurl' : license_url
309 };
310 },
311 //some default layout values:
312 thumb_width : 80,
313 image_edit_width : 400,
314 video_edit_width : 400,
315 insert_text_pos : 0, //insert at the start (will be overwritten by the user cursor pos)
316 result_display_mode : 'box', //box or list
317
318 cUpLoader : null,
319 cEdit : null,
320 dmodalCss : {},
321
322 init: function( iObj ){
323 var _this = this;
324 js_log('remoteSearchDriver:init');
325 for( var i in default_remote_search_options ) {
326 if( iObj[i]){
327 this[ i ] = iObj[i];
328 }else{
329 this[ i ] = default_remote_search_options[i];
330 }
331 }
332 //update the base text:
333 if(_this.target_textbox)
334 _this.getTexboxSelection();
335
336 //set up the content provider config:
337 if( this.cpconfig ){
338 for(var cpc in cpconfig){
339 for(var cinx in this.cpconfig[cpc]){
340 if( this.content_providers[cpc] )
341 this.content_providers[ cpc ][ cinx ] = this.cpconfig[cpc][ cinx];
342 }
343 }
344 }
345
346 //make sure the selected cp has an api to query against (if its a content_provider
347 if( this.content_providers[ this.disp_item ] &&
348 !this.content_providers[ this.disp_item ].api_url ){
349 for(var inx in this.content_providers){
350 if( this.content_providers[ inx ].api_url ){
351 this.disp_item = inx;
352 break;
353 }
354 }
355 }
356
357
358 //set up the default model config:
359 this.dmodalCss = {
360 'width':'auto',
361 'height':'auto',
362 'top' : this.modal_edge_padding,
363 'left' : this.modal_edge_padding,
364 'right' : this.modal_edge_padding,
365 'bottom': this.modal_edge_padding
366 }
367
368
369 //set up the target invocation:
370 if( $j(this.target_invocation).length==0 ){
371 js_log("RemoteSearchDriver:: no target invocation provided (will have to run your own doInitDisplay() )");
372 }else{
373 if(this.target_invocation){
374 $j(this.target_invocation).css('cursor','pointer').attr('title', gM('mwe-add_media_wizard')).click(function(){
375 _this.doInitDisplay();
376 });
377 }
378 }
379 },
380 doInitDisplay:function(){
381 var _this = this;
382 //setup the parent container:
383 this.init_modal();
384 //fill in the html:
385 this.init_interface_html();
386 //bind actions:
387 this.add_interface_bindings();
388
389 //update the target bining to just unhide the dialog:
390 $j(this.target_invocation).unbind().click(function(){
391 js_log("re-open");
392 //update the base text:
393 if( _this.target_textbox )
394 _this.getTexboxSelection();
395 //$j(_this.target_container).dialog("open");
396 $j(_this.target_container).parents('.ui-dialog').fadeIn('slow');
397 });
398 },
399 //gets the in and out points for insert position or grabs the selected text for search
400 getTexboxSelection:function(){
401 //update the caretPos
402 this.getCaretPos();
403
404 //if we have highlighted text use that as the query: (would be fun to add context menu once we have rich editor in-place)
405 if( this.caret_pos.selection )
406 this.default_query = this.caret_pos.selection
407
408 },
409 getCaretPos:function(){
410 this.caret_pos={};
411 var txtarea = $j(this.target_textbox).get(0);
412 var getTextCusorStartPos = function (o){
413 if (o.createTextRange) {
414 var r = document.selection.createRange().duplicate()
415 r.moveEnd('character', o.value.length)
416 if (r.text == '') return o.value.length
417 return o.value.lastIndexOf(r.text)
418 } else return o.selectionStart
419 }
420 var getTextCusorEndPos = function (o){
421 if (o.createTextRange) {
422 var r = document.selection.createRange().duplicate();
423 r.moveStart('character', -o.value.length);
424 return r.text.length;
425 } else{
426 return o.selectionEnd
427 }
428 }
429 this.caret_pos.s = getTextCusorStartPos( txtarea );
430 this.caret_pos.e = getTextCusorEndPos( txtarea );
431 this.caret_pos.text = txtarea.value;
432 if(this.caret_pos.s && this.caret_pos.e &&
433 (this.caret_pos.s != this.caret_pos.e))
434 this.caret_pos.selection = this.caret_pos.text.substring(this.caret_pos.s, this.caret_pos.e).replace(/ /g, '\xa0') || '\xa0';
435
436 js_log('got caret_pos:' + this.caret_pos.s);
437 //restore text value: (creating textRanges sometimes screws with the text content)
438 $j(this.target_textbox).val(this.caret_pos.text);
439 },
440 init_modal:function(){
441 js_log("init_modal");
442 var _this = this;
443 //add the parent target_container if not provided or missing
444 if(!_this.target_container || $j(_this.target_container).length==0){
445 $j('body').append('<div id="rsd_modal_target" style="position:absolute;top:30px;left:0px;bottom:45px;right:0px;" title="' + gM('mwe-add_media_wizard') + '" ></div>');
446 _this.target_container = '#rsd_modal_target';
447 //js_log('appended: #rsd_modal_target' + $j(_this.target_container).attr('id'));
448 //js_log('added target id:' + $j(_this.target_container).attr('id'));
449 //get layout
450 //layout = _this.getMaxModalLayout();
451 $j(_this.target_container).dialog({
452 bgiframe: true,
453 autoOpen: true,
454 modal: true,
455 buttons: {
456 '_': function() {
457 //just a place-holder
458 }
459 },
460 close: function() {
461 js_log('closed modal');
462 $j(this).parents('.ui-dialog').fadeOut('slow');
463 }
464 }).parent('.ui-dialog').css( _this.dmodalCss )
465 //@@bind on resize to disable css dialog to update dmodelCss
466 .bind('resizestart', function(event, ui) {
467 _this.dmodalCss = {};
468 $j(this).css({});
469 })
470 //bind on drag to remove preset style as well
471 .bind('dragstart', function(event, ui) {
472 _this.dmodalCss = {};
473 $j(this).css({});
474 });
475 //update the child position: (some of this should be pushed up-stream via dialog config options
476 $j(_this.target_container +'~ .ui-dialog-buttonpane').css({
477 'position':'absolute',
478 'left':'0px',
479 'right':'0px',
480 'bottom':'0px'
481 });
482 //re add cancel button
483 _this.cancelClipEditCB();
484 js_log('done setup of target_container: ' +
485 $j(_this.target_container +'~ .ui-dialog-buttonpane').length);
486
487
488 /*var resizeTimer = false;
489 $j(window).bind('resize', function() {
490 var adjustModal = function(){
491 var layout = _this.getMaxModalLayout();
492 //js_log("should adjust: h " + layout.h + ' width:' + layout.w);
493 $j(_this.target_container).dialog('option', 'width', layout.w);
494 $j(_this.target_container).dialog('option', 'height', layout.h);
495 }
496 if (resizeTimer) clearTimeout(resizeTimer);
497 var resizeTimer = setTimeout(adjustModal, 100);
498 });*/
499 }
500 },
501 getMaxModalLayout:function(border){
502 if(!border)
503 border = 50;
504 //js_log('setting h:' + (parseInt( $j(document).height() ) - parseInt(border*2)) + ' from:' + $j(document).height() );
505 return {
506 'h': parseInt( $j(document).height() ) - parseInt(border*4),
507 'w': parseInt( $j(document).width() ) - parseInt(border*2),
508 'r': border,
509 't': border
510 }
511 },
512 //sets up the initial html interface
513 init_interface_html:function(){
514 js_log('init_interface_html');
515 var _this = this;
516 var dq = (this.default_query)? this.default_query : '';
517 js_log('f::init_interface_html');
518
519 var o = '<div class="rsd_control_container" style="width:100%">' +
520 '<form id="rsd_form" action="javascript:return false;" method="GET">'+
521 '<input class="ui-widget-content ui-corner-all" type="text" tabindex="1" value="' + dq + '" maxlength="512" id="rsd_q" name="rsd_q" '+
522 'size="20" autocomplete="off"/> '+
523 $j.btnHtml( gM('mwe-media_search'), 'rms_search_button', 'search') +
524 '</form>';
525 //close up the control container:
526 o+='</div>';
527
528 //search provider tabs based on "checked" and "enabled" and "combined tab"
529 o+='<div id="rsd_results_container" style="top:0px;bottom:0px;left:0px;right:0px;"></div>';
530 $j(this.target_container).html( o );
531
532 //add simple styles:
533 $j(this.target_container + ' .rms_search_button').btnBind().click(function(){
534 _this.runSearch();
535 });
536
537 //draw the tabs:
538 this.drawTabs();
539 //run the default search:
540 if( this.default_query )
541 this.runSearch();
542 },
543 add_interface_bindings:function(){
544 var _this = this;
545 js_log("f:add_interface_bindings:");
546
547
548 $j('#mso_selprovider,#mso_selprovider_close').unbind().click(function(){
549 if($j('#rsd_options_bar:hidden').length !=0 ){
550 $j('#rsd_options_bar').animate({
551 'height':'110px',
552 'opacity':1
553 }, "normal");
554 }else{
555 $j('#rsd_options_bar').animate({
556 'height':'0px',
557 'opacity':0
558 }, "normal", function(){
559 $j(this).hide();
560 });
561 }
562 });
563 //set form bindings
564 $j('#rsd_form').unbind().submit(function(){
565 _this.runSearch();
566 //don't submit the form
567 return false;
568 });
569 },
570 doUploadInteface:function(){
571 js_log("doUploadInteface::");
572 var _this = this;
573 //set it to loading:
574 mv_set_loading('#tab-upload');
575 //do things async to keep interface snapy
576 setTimeout(function(){
577 //do config variable reality checks:
578 if( _this.upload_api_target == 'local' ){
579 if( ! _this.local_wiki_api_url ){
580 $j('#tab-upload').html( gM( 'rsd_config_error', 'missing_local_api_url' ) );
581 return false;
582 }else{
583 _this.upload_api_target = _this.local_wiki_api_url;
584 }
585 }
586 //make sure we have a url for the upload target:
587 if( parseUri( _this.upload_api_target ).host == _this.upload_api_target ){
588 $j('#tab-upload').html( gM('rsd_config_error', 'bad_api_url') );
589 return false;
590 }
591 //output the form
592 //set the form action based on domain:
593 if( parseUri( document.URL ).host == parseUri( _this.upload_api_target ).host ){
594 mvJsLoader.doLoad(['$j.fn.simpleUploadForm'],function(){
595
596 //get extened info about the file
597 var cp = _this.content_providers['this_wiki'];
598 //check for "this_wiki" enabled
599 if(!cp.enabled){
600 $j('#tab-upload').html('error this_wiki not enabled (can\'t get uploaded file info)');
601 return false;
602 }
603
604 //load this_wiki search system to grab the rObj
605 _this.loadSearchLib(cp, function(){
606 //do basic layout form on left upload "bin" on right
607 $j('#tab-upload').html('<table cellspacing="10">' +
608 '<tr>' +
609 '<td valign="top" style="width:350px;">' +
610 '<h4>' + gM('mwe-upload_a_file') + '</h4>' +
611 '<div id="upload_form">' +
612 mv_get_loading_img() +
613 '</div>' +
614 '</td>' +
615 '<td valign="top" id="upload_bin_cnt">' +
616 '<h4>' + gM('mwe-your_recent_uploads') + '</h4>' +
617 '<div id="upload_bin">' +
618 mv_get_loading_img() +
619 '</div>'+
620 '</td>' +
621 '</tr>' +
622 '</table>');
623
624
625 //fill in the user page:
626 if(typeof wgUserName != 'undefined' && wgUserName){
627 //load the upload bin with anything the current user has uploaded
628 cp.sObj.getUserRecentUploads( wgUserName, function(){
629 _this.drawOutputResults();
630 });
631 }else{
632 $j('#upload_bin_cnt').empty();
633 }
634
635 //deal with the api form upload form directly:
636 $j('#upload_form').simpleUploadForm({
637 "api_target" : _this.upload_api_target ,
638 "ondone_cb" : function( resultData ){
639 var wTitle = resultData['wpDestFile'];
640 //add a loading div
641 $j( _this.target_container ).append('<div id="temp_edit_loader" '+
642 'style="position:absolute;top:0px;left:0px;bottom:5px;right:4px;background-color:#FFF;">' +
643 mv_get_loading_img('position:absolute;top:30px;left:30px') +
644 '</div>');
645 cp.sObj.addByTitle( wTitle, function( rObj ){
646 $j( _this.target_container ).find('#temp_edit_loader').remove();
647 //redraw (with added result if new)
648 _this.drawOutputResults();
649 //pull up recource editor:
650 _this.resourceEdit( rObj, $j('#res_upload_' + rObj.id).get(0) );
651 });
652 //return false to close progress window:
653 return false;
654 }
655 })
656 });
657 });
658 }else{
659 //setup the proxy
660 js_log('do proxy:: ' + parseUri( _this.upload_api_target ).host);
661 $j('#tab-upload').html('proxy upload not yet ready');
662 }
663 },1);
664 },
665 runSearch: function(){
666 js_log("f:runSearch::" + this.disp_item);
667 //draw_direct_flag
668 var draw_direct_flag = true;
669 if( !this.content_providers[this.disp_item] ){
670 //check if its the special upload tab case:
671 if( this.disp_item == 'upload'){
672 this.doUploadInteface();
673 }else{
674 js_log("can't run search for:" + this.disp_item);
675 }
676 return false;
677 }
678 cp = this.content_providers[this.disp_item];
679
680 //check if we need to update:
681 if( typeof cp.sObj != 'undefined' ){
682 if(cp.sObj.last_query == $j('#rsd_q').val() && cp.sObj.last_offset == cp.offset){
683 js_log('last query is: ' + cp.sObj.last_query + ' matches: ' + $j('#rsd_q').val() );
684 }else{
685 js_log('last query is: ' + cp.sObj.last_query + ' not match: ' + $j('#rsd_q').val() );
686 draw_direct_flag = false;
687 }
688 }else{
689 draw_direct_flag = false;
690 }
691 if( !draw_direct_flag ){
692 //set the content to loading while we do the search:
693 $j('#tab-' + this.disp_item).html( mv_get_loading_img() );
694
695 //make sure the search library is loaded and issue the search request
696 this.getLibSearchResults( cp );
697 }
698 },
699 //issue a api request & cache the result
700 //this check can be avoided by setting the this.import_url_mode = 'api' | 'form' | insted of 'autodetect' or 'none'
701 checkForCopyURLSupport:function ( callback ){
702 var _this = this;
703 js_log('checkForCopyURLSupport:: ');
704 //see if we already have the import mode:
705 if( this.import_url_mode != 'autodetect'){
706 js_log('import mode: ' + _this.import_url_mode);
707 callback();
708 }
709 //if we don't have the local wiki api defined we can't auto-detect use "link"
710 if(!_this.local_wiki_api_url){
711 js_log('import mode: remote link (no import_wiki_api_url)');
712 _this.import_url_mode = 'remote_link';
713 callback();
714 }
715 if( this.import_url_mode == 'autodetect' ){
716 do_api_req( {
717 'data': { 'action':'paraminfo', 'modules':'upload' },
718 'url': _this.local_wiki_api_url
719 }, function(data){
720 if( typeof data.paraminfo.modules[0].classname == 'undefined'){
721 //@@todo would be nice if API permission on: action=query&meta=userinfo&uiprop=rights
722 // upload_by_url property reflected if $wgAllowCopyUploads config value .. oh well.
723 $j.ajax({
724 type: "GET",
725 dataType: 'html',
726 url: wgArticlePath.replace( '$1', 'Special:Upload' ), //@@todo may have problems in localized special pages
727 //(could hit meta=siteinfo & specialpagealiases )
728 // but might be overkill for now cuz we want to switch to new-upload branch soon.
729 success: function( form_html ){
730 if( form_html.indexOf( 'wpUploadFileURL' ) != -1){
731 _this.import_url_mode = 'form';
732 }else{
733 _this.import_url_mode = 'none';
734 }
735 js_log('import mode: ' + _this.import_url_mode);
736 callback();
737 },
738 error: function(){
739 js_log('error in getting Special:Upload page');
740 _this.import_url_mode = 'none';
741
742 js_log('import mode: ' + _this.import_url_mode);
743 callback();
744 }
745 });
746 }else{
747 for( var i in data.paraminfo.modules[0].parameters ){
748 var pname = data.paraminfo.modules[0].parameters[i].name;
749 if( pname == 'url' ){
750 js_log( 'Autodetect Upload Mode: api: copy by url:: ' );
751 //check permission too:
752 _this.checkForCopyURLPermission(function( canCopyUrl ){
753 if(canCopyUrl){
754 _this.import_url_mode = 'api';
755 js_log('import mode: ' + _this.import_url_mode);
756 callback();
757 }else{
758 _this.import_url_mode = 'none';
759 js_log('import mode: ' + _this.import_url_mode);
760 callback();
761 }
762 });
763 break;
764 }
765 }
766 }
767 });
768 }
769 },
770 /*
771 * checkForCopyURLPermission:
772 * not really nessesary the api request to upload will return apopprirate error if the user lacks permission. or $wgAllowCopyUploads is set to false
773 * (use this function if we want to issue a warning up front)
774 */
775 checkForCopyURLPermission:function( callback ){
776 var _this = this;
777 //do api check:
778 do_api_req( {
779 'data':{ 'action' : 'query', 'meta' : 'userinfo', 'uiprop' : 'rights' },
780 'url': _this.local_wiki_api_url,
781 'userinfo' : true
782 }, function(data){
783 for( var i in data.query.userinfo.rights){
784 var right = data.query.userinfo.rights[i];
785 //js_log('checking: ' + right ) ;
786 if(right == 'upload_by_url'){
787 callback( true );
788 return true; //break out of the function
789 }
790 }
791 callback( false );
792 });
793 },
794 getLibSearchResults:function( cp ){
795 var _this = this;
796
797 //first check if we should even run the search at all (can we import / insert into the page? )
798 if( !this.checkRepoLocal( cp ) && this.import_url_mode == 'autodetect' ){
799 //cp is not local check if we can support the import mode:
800 this.checkForCopyURLSupport( function(){
801 _this.getLibSearchResults( cp );
802 });
803 return false;
804 }else if( !this.checkRepoLocal( cp ) && this.import_url_mode == 'none'){
805 if( this.disp_item == 'combined' ){
806 //combined results are harder to error handle just ignore that repo
807 cp.sObj.loading = false;
808 }else{
809 $j('#tab-' + this.disp_item).html( '<div style="padding:10px">'+ gM('mwe-no_import_by_url') +'</div>');
810 }
811 return false;
812 }
813 _this.loadSearchLib(cp, function(){
814 //do search
815 cp.sObj.getSearchResults();
816 _this.checkResultsDone();
817 });
818 },
819 loadSearchLib:function(cp, callback){
820 var _this = this;
821 //set up the library req:
822 mvJsLoader.doLoad( [
823 'baseRemoteSearch',
824 cp.lib +'Search'
825 ], function(){
826 js_log("loaded lib:: " + cp.lib );
827 //else we need to run the search:
828 var iObj = {'cp':cp, 'rsd':_this};
829 eval('cp.sObj = new '+cp.lib+'Search( iObj );');
830 if(!cp.sObj){
831 js_log('Error: could not find search lib for ' + cp_id);
832 return false;
833 }
834
835 //inherit defaults if not set:
836 cp.limit = (cp.limit) ? cp.limit : cp.sObj.limit;
837 cp.offset = (cp.offset) ? cp.offset : cp.sObj.offset;
838 callback();
839 });
840 },
841 /* check for all the results to finish */
842 checkResultsDone: function(){
843 //js_log('rsd:checkResultsDone');
844 var _this = this;
845 var loading_done = true;
846
847 for(var cp_id in this.content_providers){
848 var cp = this.content_providers[ cp_id ];
849 if(typeof cp['sObj'] != 'undefined'){
850 if( cp.sObj.loading )
851 loading_done=false;
852 }
853 }
854 if( loading_done ){
855 this.drawOutputResults();
856 }else{
857 //make sure the instance name is up-to-date refrence to _this;
858 eval( _this.instance_name + ' = _this');
859 setTimeout( _this.instance_name + '.checkResultsDone()', 50);
860 }
861 },
862 drawTabs: function(){
863 var _this = this;
864 //add the tabs to the rsd_results container:
865 var o='<div id="rsd_tabs_container" style="width:100%;">';
866 var selected_tab = 0;
867 var inx =0;
868 o+= '<ul>';
869 var tabc = '';
870 for(var cp_id in this.content_providers){
871 var cp = this.content_providers[cp_id];
872 if( cp.enabled && cp.checked && cp.api_url){
873 //add selected default if set
874 if( this.disp_item == cp_id)
875 selected_tab=inx;
876
877 o+='<li class="rsd_cp_tab">';
878 o+='<a id="rsd_tab_' + cp_id + '" href="#tab-' + cp_id + '">';
879 if(cp.tab_img === true){
880 o+='<img alt="' + cp.title +'" src="' + mv_skin_img_path + 'remote_cp/' + cp_id + '_tab.png">';
881 }else{
882 o+= cp.title;
883 }
884 o+='</a>';
885 o+='</li>';
886 inx++;
887 }
888 tabc+='<div id="tab-'+ cp_id +'" class="rsd_results"/>';
889
890 }
891 //do an upload tab if enabled:
892 if( this.enable_upload_tab ){
893 o+='<li class="rsd_cp_tab" ><a id="rsd_tab_upload" href="#tab-upload">' + gM('mwe-upload_tab') + '</a></li>';
894 tabc+='<div id="tab-upload" />';
895 if(this.disp_item == 'upload')
896 selected_tab = inx++;
897 }
898 o+='</ul>';
899 //output the tab content containers:
900 o+=tabc;
901 o+='</div>'; //close tab container
902
903 //output the respective results holders
904 $j('#rsd_results_container').html(o);
905 //setup bindings for tabs make them sortable: (@@todo remember order)
906 js_log('selected tab is: ' + selected_tab);
907 $j("#rsd_tabs_container").tabs({
908 selected:selected_tab,
909 select: function(event, ui) {
910 _this.selectTab( $j(ui.tab).attr('id').replace('rsd_tab_', '') );
911 }
912 //add sorting
913 }).find(".ui-tabs-nav").sortable({axis:'x'});
914
915 /*$j('.rsd_cp_tab').click(function(){
916 _this.selectTab( $j(this).attr('id').replace(/rsd_tab_/, '') );
917 });*/
918
919 //setup key binding (no longer nessesary tabs provide this functionality)
920 /*$j().keyup(function(e){
921 js_log('keyup on : ' +e.which );
922 //if escape pressed clear the interface:
923 if(e.which == 27)
924 _this.closeAll();
925 });*/
926
927 },
928 //resource title
929 getResourceFromTitle:function( rTitle , callback){
930 var _this = this;
931 reqObj={
932 'action':'query',
933 'titles': _this.cFileNS + ':' + rTitle
934 };
935 do_api_req( {
936 'data':reqObj,
937 'url':this.local_wiki_api_url
938 }, function(data){
939 //@@todo propogate the rObj
940 var rObj = {};
941 }
942 );
943 },
944 //@@todo we could load the id with the content provider id to find the object faster...
945 getResourceFromId:function( rid ){
946 js_log('getResourceFromId:' + rid );
947 //strip out /res/ if preset:
948 rid = rid.replace(/res_/, '');
949 //js_log("looking at: " + rid);
950 p = rid.split('__');
951 var cp_id = p[0];
952 var rid = p[1];
953
954 if(cp_id == 'upload')
955 cp_id = 'this_wiki';
956
957 var cp = this.content_providers[cp_id];
958 if(cp && cp['sObj'] && cp.sObj.resultsObj[rid]){
959 return cp.sObj.resultsObj[rid];
960 }
961 js_log("ERROR: could not find " + rid);
962 return false;
963 },
964 drawOutputResults: function(){
965 js_log('f:drawOutputResults::' + this.disp_item);
966 var _this = this;
967 var o='';
968
969 var cp_id = this.disp_item;
970 var tab_target = '';
971 if(this.disp_item == 'upload'){
972 tab_target = '#upload_bin';
973 var cp = this.content_providers['this_wiki'];
974 }else{
975 var cp = this.content_providers[this.disp_item];
976 tab_target = '#tab-' + cp_id;
977 }
978 //empty the existing results:
979 $j(tab_target).empty();
980
981 //output the results bar / controls
982 _this.setResultBarControl();
983
984 var drawResultCount =0;
985
986 //output all the results for the current disp_item
987 if( typeof cp['sObj'] != 'undefined' ){
988 $j.each(cp.sObj.resultsObj, function(rInx, rItem){
989 if( _this.result_display_mode == 'box' ){
990 o+='<div id="mv_result_' + rInx + '" class="mv_clip_box_result" style="width:' +
991 _this.thumb_width + 'px;height:'+ (_this.thumb_width-20) +'px;position:relative;">';
992 //check for missing poster types for audio
993 if( rItem.mime=='audio/ogg' && !rItem.poster ){
994 rItem.poster = mv_skin_img_path + 'sound_music_icon-80.png';
995 }
996 //get a thumb with proper resolution transform if possible:
997 o+='<img title="'+rItem.title+'" class="rsd_res_item" id="res_' + cp_id + '__' + rInx +
998 '" style="width:' + _this.thumb_width + 'px;" src="' +
999 cp.sObj.getImageTransform( rItem, {'width':_this.thumb_width } )
1000 + '">';
1001 //add a linkback to resource page in upper right:
1002 if( rItem.link )
1003 o+='<a target="_new" style="position:absolute;top:0px;right:0px" title="' +
1004 gM('mwe-resource_description_page') +
1005 '" href="' + rItem.link + '"><img src="http://upload.wikimedia.org/wikipedia/commons/6/6b/Magnify-clip.png"></a>';
1006 //add license icons if present
1007 if( rItem.license )
1008 o+= _this.getlicenseImgSet( rItem.license );
1009 o+='</div>';
1010 }else if(_this.result_display_mode == 'list'){
1011 o+='<div id="mv_result_' + rInx + '" class="mv_clip_list_result" style="width:90%">';
1012 o+='<img title="'+rItem.title+'" class="rsd_res_item" id="res_' + cp_id + '_' + rInx +'" style="float:left;width:' +
1013 _this.thumb_width + 'px;" src="' +
1014 cp.sObj.getImageTransform( rItem, {'width':_this.thumb_width } )
1015 + '">';
1016 //add license icons if present
1017 if( rItem.license )
1018 o+= _this.getlicenseImgSet( rItem.license );
1019
1020 o+= rItem.desc ;
1021 o+='<div style="clear:both" />';
1022 o+='</div>';
1023 }
1024 drawResultCount++;
1025 });
1026 js_log('append to: ' + '#tab-' + cp_id);
1027 //put in the tab output (plus clear the output)
1028 $j(tab_target).append( o + '<div style="clear:both"/>');
1029 }
1030
1031 js_log( ' drawResultCount :: ' + drawResultCount + ' append: ' + $j('#rsd_q').val() );
1032
1033 //remove any old search res
1034 $j('#rsd_no_search_res').remove();
1035 if( drawResultCount == 0 )
1036 $j('#tab-' + cp_id).append( '<span style="padding:10px">' + gM( 'rsd_no_results', $j('#rsd_q').val() ) + '</span>');
1037
1038 this.addResultBindings();
1039 },
1040 addResultBindings:function(){
1041 var _this = this;
1042 $j('.mv_clip_'+_this.result_display_mode+'_result').hover(function(){
1043 $j(this).addClass('mv_clip_'+_this.result_display_mode+'_result_over');
1044 //also set the animated image if avaliable
1045 var res_id = $j(this).children('.rsd_res_item').attr('id');
1046 var rObj = _this.getResourceFromId( res_id );
1047 if( rObj.poster_ani )
1048 $j('#' + res_id ).attr('src', rObj.poster_ani);
1049 },function(){
1050 $j(this).removeClass('mv_clip_'+_this.result_display_mode+'_result_over');
1051 var res_id = $j(this).children('.rsd_res_item').attr('id');
1052 var rObj = _this.getResourceFromId( res_id );
1053 //restore the original (non animated)
1054 if( rObj.poster_ani )
1055 $j('#' + res_id ).attr('src', rObj.poster);
1056 });
1057 //resource click action: (bring up the resource editor)
1058 $j('.rsd_res_item').unbind().click(function(){
1059 var rObj = _this.getResourceFromId( $j(this).attr("id") );
1060 _this.resourceEdit( rObj, this );
1061 });
1062 },
1063 addResourceEditLoader:function(maxWidth, overflow_style){
1064 var _this = this;
1065 if(!maxWidth)maxWidth=400;
1066 if(!overflow_style)overflow_style='overflow:auto;';
1067 //remove any old instance:
1068 $j( _this.target_container ).find('#rsd_resource_edit').remove();
1069 //add the edit layout window with loading place holders
1070 $j( _this.target_container ).append('<div id="rsd_resource_edit" '+
1071 'style="position:absolute;top:0px;left:0px;bottom:5px;right:4px;background-color:#FFF;">' +
1072 '<div id="clip_edit_disp" style="position:absolute;' + overflow_style + 'width:100%;height:100%;padding:5px;'+
1073 'width:' + (maxWidth) + 'px;" >' +
1074 mv_get_loading_img('position:absolute;top:30px;left:30px') +
1075 '</div>'+
1076 '<div id="clip_edit_ctrl" class="ui-widget ui-widget-content ui-corner-all" style="position:absolute;'+
1077 'left:' + ( maxWidth + 10 ) +'px;top:5px;bottom:10px;right:0px;overflow:auto;padding:5px;">'+
1078 mv_get_loading_img() +
1079 '</div>'+
1080 '</div>');
1081 },
1082 resourceEdit:function( rObj, rsdElement){
1083 js_log('f:resourceEdit:' + rObj.title);
1084 var _this = this;
1085 //remove any existing resource edit interface:
1086 $j('#rsd_resource_edit').remove();
1087 //set the media type:
1088 if(rObj.mime.indexOf('image')!=-1){
1089 //set width to default image_edit_width
1090 var maxWidth = _this.image_edit_width;
1091 var mediaType = 'image';
1092 }else if(rObj.mime.indexOf('audio')!=-1){
1093 var maxWidth = _this.video_edit_width;
1094 var mediaType = 'audio';
1095 }else{
1096 //set to default video size:
1097 var maxWidth = _this.video_edit_width;
1098 var mediaType = 'video';
1099 }
1100 //so that transcripts show ontop
1101 var overflow_style = ( mediaType =='video' )?'':'overflow:auto;';
1102 //append to the top level of model window:
1103 _this.addResourceEditLoader(maxWidth, overflow_style);
1104 //update add media wizard title:
1105 $j( _this.target_container ).dialog( 'option', 'title', gM('mwe-add_media_wizard')+': '+ gM('rsd_resource_edit', rObj.title ) );
1106 js_log('did append to: '+ _this.target_container );
1107
1108 $j('#rsd_resource_edit').css('opacity',0);
1109
1110 $j('#rsd_edit_img').remove();//remove any existing rsd_edit_img
1111
1112 //left side holds the image right size the controls /
1113 $j(rsdElement).clone().attr('id', 'rsd_edit_img').appendTo('#clip_edit_disp').css({
1114 'position':'absolute',
1115 'top':'40%',
1116 'left':'20%',
1117 'cursor':'default',
1118 'opacity':0
1119 });
1120
1121
1122 //try and keep aspect ratio for the thumbnail that we clicked:
1123 var tRatio = $j('#rsd_edit_img').width() / $j('#rsd_edit_img').height() ;
1124 if( ! tRatio )
1125 var tRatio = 1; //set ratio to 1 if the width of the thumbnail can't be found for some reason
1126
1127 js_log('set from ' + $j('#rsd_edit_img').width()+'x'+ $j('#rsd_edit_img').height() + ' to init thumbimage to ' + maxWidth + ' x ' + parseInt( tRatio * maxWidth) );
1128 //scale up image and to swap with high res version
1129 $j('#rsd_edit_img').animate({
1130 'opacity':1,
1131 'top':'5px',
1132 'left':'5px',
1133 'width': maxWidth + 'px',
1134 'height': parseInt( tRatio * maxWidth) + 'px'
1135 }, "slow"); // do it slow to give it a chance to finish loading the HQ version
1136
1137 if( mediaType == 'image' ){
1138 _this.loadHQImg(rObj, {'width':maxWidth}, 'rsd_edit_img', function(){
1139 $j('.mv_loading_img').remove();
1140 });
1141 }
1142 //also fade in the container:
1143 $j('#rsd_resource_edit').animate({
1144 'opacity':1,
1145 'background-color':'#FFF',
1146 'z-index':99
1147 });
1148 js_log('do load the media editor:');
1149 //do load the media Editor
1150 _this.doMediaEdit( rObj , mediaType );
1151 },
1152 loadHQImg:function(rObj, size, target_img_id, callback){
1153 //get the HQ image url:
1154 rObj.pSobj.getImageObj( rObj, size, function( imObj ){
1155 rObj['edit_url'] = imObj.url;
1156
1157 js_log("edit url: " + rObj.edit_url);
1158 //update the rObj
1159 rObj['width'] = imObj.width;
1160 rObj['height'] = imObj.height;
1161
1162 //see if we need to animate some transition
1163 if( size.width != imObj.width ){
1164 js_log('loadHQImg:size mismatch: ' + size.width + ' != ' + imObj.width );
1165 //set the target id to the new size:
1166 $j('#'+target_img_id).animate( {
1167 'width':imObj.width + 'px',
1168 'height':imObj.height + 'px'
1169 });
1170 }else{
1171 js_log('using req size: ' + imObj.width + 'x' + imObj.height);
1172 $j('#'+target_img_id).animate( {'width':imObj.width+'px', 'height' : imObj.height + 'px'});
1173 }
1174 //don't swap it in until its loaded:
1175 var img = new Image();
1176 // load the image image:
1177 $j(img).load(function () {
1178 $j('#'+target_img_id).attr('src', rObj.edit_url );
1179 //let the caller know we are done and what size we ended up with:
1180 callback();
1181 }).error(function () {
1182 js_log("Error with: " + rObj.edit_url);
1183 }).attr('src', rObj.edit_url);
1184 });
1185 },
1186 cancelClipEditCB:function(){
1187 var _this = this;
1188 var b_target = _this.target_container + '~ .ui-dialog-buttonpane';
1189 $j('#rsd_resource_edit').remove();
1190 //restore the resource container:
1191 $j('#rsd_results_container').show();
1192 //restore the title:
1193 $j( _this.target_container ).dialog( 'option', 'title', gM('mwe-add_media_wizard'));
1194 js_log("should update: " + b_target + ' with: cancel');
1195 //restore the buttons:
1196 $j(b_target).html( $j.btnHtml( 'Cancel' , 'mv_cancel_rsd', 'close'))
1197 .children('.mv_cancel_rsd')
1198 .btnBind()
1199 .click(function(){
1200 $j( _this.target_container).dialog('close');
1201 })
1202
1203 },
1204 /*set-up the control actions for clipEdit with relevent callbacks */
1205 getClipEditControlActions:function( cp ){
1206 var _this = this;
1207 var cConf= {};
1208
1209 cConf['insert'] = function(rObj){
1210 _this.insertResource(rObj);
1211 }
1212 //if not directly inserting the resource is support a preview option:
1213 if( _this.import_url_mode != 'remote_link'){
1214 cConf['preview'] = function(rObj){
1215 _this.previewResource( rObj )
1216 };
1217 }
1218 cConf['cancel'] = function(){
1219 _this.cancelClipEditCB()
1220 }
1221 return cConf;
1222 },
1223 //loads the media editor:
1224 doMediaEdit:function( rObj , mediaType){
1225 var _this = this;
1226 var cp = rObj.pSobj.cp;
1227 var mvClipInit = {
1228 'rObj':rObj, //the resource object
1229 'parent_ct' : 'rsd_modal_target',
1230 'clip_disp_ct' : 'clip_edit_disp',
1231 'control_ct' : 'clip_edit_ctrl',
1232 'media_type' : mediaType,
1233 'p_rsdObj' : _this,
1234 'controlActionsCb' : _this.getClipEditControlActions( cp )
1235 };
1236
1237 var clibs = ['mvClipEdit'];
1238 if( mediaType == 'image'){
1239 //display the mvClipEdit obj once we are done loading:
1240 mvJsLoader.doLoad( clibs, function(){
1241 //run the image clip tools
1242 _this.cEdit = new mvClipEdit( mvClipInit );
1243 });
1244 }
1245 if( mediaType == 'video' || mediaType == 'audio'){
1246 //get any additonal embedding helper meta data prior to doing the acutal embed
1247 // normally this meta should be provided in the search result (but archive.org has a seperate query for more meida meta)
1248 rObj.pSobj.getEmbedTimeMeta( rObj, function(){
1249 //make sure we have the embedVideo libs:
1250 mvJsLoader.embedVideoCheck( function(){
1251 js_log('append html: ' + rObj.pSobj.getEmbedHTML( rObj, {id:'embed_vid'}) );
1252 $j('#clip_edit_disp').html(
1253 rObj.pSobj.getEmbedHTML( rObj, {id:'embed_vid'})
1254 );
1255 //rewrite by id
1256 rewrite_by_id('embed_vid',function(){
1257 //grab any information that we got from the ROE xml or parsed from the media file
1258 rObj.pSobj.getEmbedObjParsedInfo( rObj, 'embed_vid' );
1259 //add the re-sizable to the doLoad request:
1260 clibs.push( '$j.ui.resizable');
1261 clibs.push( '$j.fn.hoverIntent');
1262 mvJsLoader.doLoad(clibs, function(){
1263 //make sure the rsd_edit_img is hidden:
1264 $j('#rsd_edit_img').remove();
1265 //run the image clip tools
1266 _this.cEdit = new mvClipEdit( mvClipInit );
1267 });
1268 });
1269 });
1270 });
1271 }
1272 },
1273 checkRepoLocal:function( cp ){
1274 if( cp.local ){
1275 return true;
1276 }else{
1277 //check if we can embed the content locally per a domain name check:
1278 var local_host = parseUri( this.local_wiki_api_url ).host;
1279 if( cp.local_domains ) {
1280 for(var i=0;i < cp.local_domains.length; i++){
1281 var ld = cp.local_domains[i];
1282 if( local_host.indexOf( ld ) != -1)
1283 return true;
1284 }
1285 }
1286 return false;
1287 }
1288 },
1289 checkImportResource:function( rObj, cir_callback){
1290 //@@todo get the localized File/Image namespace name or do a general {NS}:Title
1291 var cp = rObj.pSobj.cp;
1292 var _this = this;
1293
1294 //update base target_resource_title:
1295 rObj.target_resource_title = rObj.titleKey.replace(/File:|Image:/,'')
1296
1297 //check if local repository
1298 //or if import mode if just "linking" (we should alaredy have the 'url'
1299
1300 if( this.checkRepoLocal( cp ) || this.import_url_mode == 'remote_link'){
1301 //local repo jump directly to check Import Resource callback:
1302 cir_callback( rObj );
1303 }else{
1304 //update target_resource_title with resource repository prefix:
1305 rObj.target_resource_title = cp.resource_prefix + rObj.target_resource_title;
1306
1307 //check if the resource is not already on this wiki
1308 reqObj={
1309 'action':'query',
1310 'titles': _this.cFileNS + ':' + rObj.target_resource_title,
1311 'prop' : 'imageinfo',
1312 'iiprop' : 'url',
1313 'iiurlwidth': '400'
1314 };
1315
1316 do_api_req( {
1317 'data':reqObj,
1318 'url':this.local_wiki_api_url
1319 }, function(data){
1320 var found_title = false;
1321 for(var i in data.query.pages){
1322 if( i != '-1' && i != '-2' ){
1323 js_log('found title: ' + i + ':' + data.query.pages[i]['title']);
1324 found_title=data.query.pages[i]['title'];
1325 //update to local src
1326 rObj.local_src = data.query.pages[i]['imageinfo'][0].url;
1327 //@@todo maybe update poster too?
1328 rObj.local_poster = data.query.pages[i]['imageinfo'][0].thumburl;
1329 }
1330 }
1331 if( found_title ){
1332 js_log("checkImportResource:found title:" + found_title);
1333 //resource is already present (or resource with same name is already present)
1334 rObj.target_resource_title = found_title.replace(/File:|Image:/,'');
1335 cir_callback( rObj );
1336 }else{
1337 js_log("resource not present: update:"+ _this.cFileNS + ':' + rObj.target_resource_title);
1338
1339 //update the rObj with import info
1340 rObj.pSobj.updateDataForImport( rObj );
1341
1342 //setup the resource description from resource description:
1343 var wt = '{{Information '+"\n";
1344
1345 if( rObj.desc ){
1346 wt += '|Description= ' + rObj.desc + "\n";
1347 }else{
1348 wt += '|Description= ' + gM('mwe-missing_desc_see_source', rObj.link ) + "\n";
1349 }
1350
1351 //output search specific info
1352 wt+='|Source=' + rObj.pSobj.getImportResourceDescWiki( rObj ) + "\n";
1353
1354 if( rObj.author )
1355 wt+='|Author=' + rObj.author +"\n";
1356
1357 if( rObj.date )
1358 wt+='|Date=' + rObj.date +"\n";
1359
1360 //add the Permision info:
1361 wt+='|Permission=' + rObj.pSobj.getPermissionWikiTag( rObj ) +"\n";
1362
1363 if( rObj.other_versions )
1364 wt+='|other_versions=' + rObj.other_versions + "\n";
1365
1366 wt+='}}';
1367
1368 //get any extra categories or helpful links
1369 wt+= rObj.pSobj.getExtraResourceDescWiki( rObj );
1370
1371
1372 $j('#rsd_resource_import').remove();//remove any old resource imports
1373
1374 //@@ show user dialog to import the resource
1375 $j( _this.target_container ).append('<div id="rsd_resource_import" '+
1376 'class="ui-state-highlight ui-widget-content ui-state-error" ' +
1377 'style="position:absolute;top:50px;left:50px;right:50px;bottom:50px;z-index:5">' +
1378 '<h3 style="color:red">Resource: <span style="color:black">' + rObj.title + '</span> needs to be imported</h3>'+
1379 '<div id="rsd_preview_import_container" style="position:absolute;width:50%;bottom:0px;left:0px;overflow:auto;top:30px;">' +
1380 rObj.pSobj.getEmbedHTML( rObj, {'id': _this.target_container + '_rsd_pv_vid', 'max_height':'200','only_poster':true} )+ //get embedHTML with small thumb:
1381 '<br style="clear both">'+
1382 '<strong>'+gM('mwe-resource_page_desc') +'</strong>'+
1383 '<div id="rsd_import_desc" syle="display:inline;">'+
1384 mv_get_loading_img('position:absolute;top:5px;left:5px') +
1385 '</div>'+
1386 '</div>'+
1387 '<div id="rds_edit_import_container" style="position:absolute;left:50%;' +
1388 'bottom:0px;top:30px;right:0px;overflow:auto;">'+
1389 '<strong>' + gM('mwe-local_resource_title') + '</strong><br>'+
1390 '<input type="text" size="30" value="' + rObj.target_resource_title + '" readonly="true"><br>'+
1391 '<strong>' + gM('mwe-edit_resource_desc') + '</strong>' +
1392 '<textarea id="rsd_import_ta" id="mv_img_desc" style="width:90%;" rows="8" cols="50">' +
1393 wt +
1394 '</textarea><br>' +
1395 '<input type="checkbox" value="true" id="wpWatchthis" name="wpWatchthis" tabindex="7"/>' +
1396 '<label for="wpWatchthis">'+gM('mwe-watch_this_page')+'</label><br><br><br>' +
1397
1398 $j.btnHtml(gM('mwe-do_import_resource'), 'rsd_import_doimport', 'check' ) + ' ' +
1399
1400 $j.btnHtml(gM('mwe-update_preview'), 'rsd_import_apreview', 'refresh' ) + '<div style="clear:both;height:20px;"/>' +
1401
1402 $j.btnHtml(gM('mwe-cancel_import'), 'rsd_import_acancel', 'close' ) + ' ' +
1403
1404 '</div>'+
1405 //output the rendered and non-renderd version of description for easy swiching:
1406 '</div>');
1407 //add hover:
1408 //update video tag
1409 rewrite_by_id(_this.target_container + '_rsd_pv_vid');
1410 //load the preview text:
1411 _this.getParsedWikiText( wt, _this.cFileNS +':'+ rObj.target_resource_title, function( o ){
1412 $j('#rsd_import_desc').html(o);
1413 });
1414 //add bidings:
1415 $j( _this.target_container + ' .rsd_import_apreview').btnBind().click(function(){
1416 /*$j('#rsd_import_desc').show().html(
1417 mv_get_loading_img()
1418 );*/
1419 //load the preview text:
1420 _this.getParsedWikiText( $j('#rsd_import_ta').val(), _this.cFileNS +':'+ rObj.target_resource_title, function( o ){
1421 js_log('got updated preivew: ');
1422 $j('#rsd_import_desc').html(o);
1423 });
1424 });
1425 $j(_this.target_container + ' .rsd_import_doimport').btnBind().click(function(){
1426 //check import mode:
1427 if(_this.import_url_mode=='form'){
1428 _this.doImportSpecialPage( rObj, cir_callback );
1429 }else if( _this.import_url_mode=='api'){
1430 _this.doImportAPI( rObj , cir_callback);
1431 }else{
1432 js_log("Error: import mode is not form or API (can not copy asset)");
1433 }
1434 });
1435 $j( _this.target_container + ' .rsd_import_acancel').btnBind().click(function(){
1436 $j('#rsd_resource_import').fadeOut("fast",function(){
1437 $j(this).remove();
1438 });
1439 });
1440 }
1441 }
1442 );
1443 }
1444 },
1445 doImportAPI:function(rObj, cir_callback){
1446 var _this = this;
1447 //baseUploadInterface
1448 mvJsLoader.doLoad([
1449 'mvBaseUploadInterface',
1450 '$j.ui.progressbar'
1451 ],function(){
1452 //initicate a download similar to url copy:
1453 myUp = new mvBaseUploadInterface({
1454 'api_url' : _this.local_wiki_api_url,
1455 'done_upload_cb':function(){
1456 //we have finished the upload:
1457
1458 //close up the rsd_resource_import
1459 $j('#rsd_resource_import').remove();
1460 //run the parent callback:
1461 cir_callback();
1462 //return false to avoid BaseUploadInterface done actions
1463 return false;
1464 }
1465 });
1466 //set the edit token if we have it handy
1467 _this.getEditToken(function( token ){
1468 myUp.etoken = token;
1469 myUp.doHttpUpload({
1470 'url' : rObj.src,
1471 'filename' : rObj.target_resource_title,
1472 'comment' : $j('#rsd_import_ta').val()
1473 });
1474 })
1475
1476
1477 });
1478 },
1479 getEditToken:function(callback){
1480 //first try the page form:
1481 var etoken = $j("input[name='wpEditToken']").val();
1482 if(etoken){
1483 callback( etoken );
1484 return ;
1485 }
1486 //@@todo try to load over ajax if( _this.local_wiki_api_url ) is set
1487 // (your on the api domain but are inserting from a normal page view)
1488 if( _this.local_wiki_api_url){
1489 get_mw_token(null, _this.local_wiki_api_url, function(token){
1490 callback( token );
1491 })
1492 }
1493 callback(false);
1494 return false;
1495 },
1496 /**
1497 * doImportSpecialPage
1498 * can be depricated once we support upload api support is widespred.
1499 */
1500 doImportSpecialPage:function(rObj, cir_callback){
1501 var _this = this;
1502 //get an edittoken:
1503 do_api_req( {
1504 'data': { 'action':'query',
1505 'prop':'info',
1506 'intoken':'edit',
1507 'titles': rObj.titleKey
1508 },
1509 'url':_this.local_wiki_api_url
1510 }, function(data){
1511 //could recheck if it has been created in the mean time
1512 if( data.query.pages[-1] ){
1513 var editToken = data.query.pages[-1]['edittoken'];
1514 if(!editToken){
1515 //@@todo give an ajax login or be more friendly in some way:
1516 js_error("You don't have permission to upload (are you logged in?)");
1517 //remove top level:
1518 $j('#modalbox').fadeOut("normal",function(){
1519 $j(this).remove();
1520 $j('#mv_overlay').remove();
1521 });
1522 }else{
1523 //not sure if we can do remote url uploads (so just do a local post)
1524 js_log('got token for new page:' +editToken);
1525 var postVars = {
1526 'wpSourceType' :'web',
1527 'wpUploadFileURL' : rObj.src,
1528 'wpDestFile' : rObj.target_resource_title,
1529 'wpUploadDescription' : $j('#rsd_import_ta').val(),
1530 'wpWatchthis' : $j('#wpWatchthis').val(),
1531 'wpUpload' : 'Upload file'
1532 }
1533 //set to uploading:
1534 $j('#rsd_resource_import').append('<div id="rsd_import_progress"'+
1535 'style="position:absolute;top:0px;'+
1536 'left:0px;width:100%;height:100%;'+
1537 'z-index:5;background:#FFF;overflow:auto;">'+
1538 '<div style="position:absolute;left:30%;right:30%"><h3>'+gM('mwe-importing_asset')+'</h3><br>' +
1539 mv_get_loading_img('','mv_loading_bar_img') +
1540 '</div>'+
1541 '</div>'
1542 );
1543 $j.post(wgArticlePath.replace(/\$1/,'Special:Upload'),
1544 postVars,
1545 function(data){
1546 //@@todo this will be replaced once we add upload image support to the api.
1547
1548 //very basic test to see if we got passed to the image page:
1549 //@@todo more normalization stuff
1550 var sstring ='var wgPageName = "' + _this.cFileNS + ':' + rObj.target_resource_title.replace(/ /g,'_') +'"';
1551 if(data.indexOf( sstring ) !=-1){
1552 js_log('found: ' + sstring);
1553 $j('#rsd_resource_import').remove();
1554 cir_callback( rObj );
1555 }else{
1556 js_log("Error or warning: (did not find: \"" + sstring + ' in output' );
1557 pos_etitle = '<h1 class="firstHeading">';
1558 var error_txt = form_txt = '';
1559 var res = grabWikiFormError( data );
1560
1561 if( res.error_txt )
1562 error_txt = res.error_txt;
1563
1564 if( res.form_txt )
1565 form_txt = res.form_txt;
1566
1567 js_log( 'error text is: ' + error_txt );
1568 $j( '#rsd_resource_import' ).html( '<h3>Error</h3>' + error_txt + '<br>' + form_txt +
1569 '<br>'+
1570 '<a href="#" id="rsd_import_error" >' + gM('mwe-cancel_import') + '</a>'
1571 );
1572 //set up cancel action:
1573 $j('#rsd_import_error').click(function(){
1574 $j('#rsd_resource_import').remove();
1575 });
1576 }
1577
1578 }
1579 );
1580 }
1581 }
1582 }
1583 );
1584 },
1585 previewResource:function( rObj ){
1586 var _this = this;
1587 this.checkImportResource( rObj, function(){
1588 //put another window ontop:
1589 $j( _this.target_container ).append('<div id="rsd_preview_display"' +
1590 'style="position:absolute;overflow:hidden;z-index:4;top:0px;bottom:75px;right:0px;left:0px;background-color:#FFF;">' +
1591 mv_get_loading_img('top:30px;left:30px') +
1592 '</div>');
1593
1594 var bPlaneTarget = _this.target_container +'~ .ui-dialog-buttonpane';
1595 var pTitle = $j( _this.target_container ).dialog('option', 'title');
1596
1597 //update title:
1598 $j( _this.target_container ).dialog('option', 'title', gM('mwe-preview_insert_resource', rObj.title) );
1599
1600 //update buttons preview:
1601 $j(bPlaneTarget).html( $j.btnHtml( gM('rsd_do_insert'), 'preview_do_insert', 'check') + ' ' )
1602 .children('.preview_do_insert')
1603 .click(function(){
1604 _this.insertResource( rObj );
1605 });
1606 //update cancel button
1607 $j(bPlaneTarget).append('<a href="#" class="preview_close">Do More Modification</a>')
1608 .children('.preview_close')
1609 .click(function(){
1610 $j('#rsd_preview_display').remove();
1611 //restore title:
1612 $j( _this.target_container ).dialog('option', 'title', pTitle);
1613 //restore buttons (from the clipEdit object::)
1614 _this.cEdit.updateInsertControlActions();
1615 });
1616
1617 //update the preview_wtext
1618 _this.updatePreviewText( rObj );
1619 _this.getParsedWikiText(_this.preview_wtext, _this.target_title,
1620 function(phtml){
1621 $j('#rsd_preview_display').html( phtml );
1622 //update the display of video tag items (if any)
1623 mwdomReady(true);
1624 }
1625 );
1626 });
1627 },
1628 updatePreviewText:function( rObj ){
1629 var _this = this;
1630
1631 if( _this.import_url_mode == 'remote_link' ){
1632 _this.cur_embed_code = rObj.pSobj.getEmbedHTML(rObj);
1633 }else{
1634 _this.cur_embed_code = rObj.pSobj.getEmbedWikiCode( rObj );
1635 }
1636
1637 //insert at start if textInput cursor has not been set (ie == length)
1638 if( _this.caret_pos && _this.caret_pos.text){
1639 if( _this.caret_pos.text.length == _this.caret_pos.s)
1640 _this.caret_pos.s=0;
1641 _this.preview_wtext = _this.caret_pos.text.substring(0, _this.caret_pos.s) +
1642 _this.cur_embed_code +
1643 _this.caret_pos.text.substring( _this.caret_pos.s );
1644 }else{
1645 _this.preview_wtext = $j(_this.target_textbox).val() + _this.cur_embed_code;
1646 }
1647 //check for missing </refrences>
1648 if( _this.preview_wtext.indexOf('<references/>') ==-1 && _this.preview_wtext.indexOf('<ref>') != -1 )
1649 _this.preview_wtext = _this.preview_wtext + '<references/>';
1650 },
1651 getParsedWikiText:function( wikitext, title, callback ){
1652 do_api_req( {
1653 'data':{'action':'parse',
1654 'text':wikitext
1655 },
1656 'url':this.local_wiki_api_url
1657 },function(data){
1658 callback( data.parse.text['*'] );
1659 }
1660 );
1661 },
1662 insertResource:function( rObj){
1663 js_log('insertResource: ' + rObj.title);
1664 var _this = this
1665 //dobule check that the resource is present:
1666 this.checkImportResource( rObj, function(){
1667 _this.updatePreviewText( rObj );
1668 $j(_this.target_textbox).val( _this.preview_wtext );
1669
1670 //update the render area (if present)
1671 if(_this.target_render_area && _this.cur_embed_code){
1672 //output with some padding:
1673 $j(_this.target_render_area).append( _this.cur_embed_code + '<div style="clear:both;height:10px">')
1674 //update if its video or audio:
1675 if( rObj.mime.indexOf('audio')!=-1 ||
1676 rObj.mime.indexOf('video')!=-1 ||
1677 rObj.mime.indexOf('/ogg') !=-1){
1678 mvJsLoader.embedVideoCheck(function(){
1679 mv_video_embed();
1680 });
1681 }
1682 }
1683 _this.closeAll();
1684 });
1685 },
1686 closeAll:function(){
1687 var _this = this;
1688 js_log("close all:: " + _this.target_container);
1689 _this.cancelClipEditCB();
1690 $j(_this.target_container).dialog('close');
1691 },
1692 setResultBarControl:function( ){
1693 var _this = this;
1694 var box_dark_url = mv_skin_img_path + 'box_layout_icon_dark.png';
1695 var box_light_url = mv_skin_img_path + 'box_layout_icon.png';
1696 var list_dark_url = mv_skin_img_path + 'list_layout_icon_dark.png';
1697 var list_light_url = mv_skin_img_path + 'list_layout_icon.png';
1698
1699 var about_desc ='';
1700 if( this.content_providers[this.disp_item] ){
1701 var cp = this.content_providers[this.disp_item];
1702 about_desc ='<span style="position:relative;top:0px;font-style:italic;">' +
1703 '<i>' + gM('mwe-results_from', [cp.homepage, cp.title]) + '</i></span>';
1704 $j('#tab-'+this.disp_item).append( '<div id="rds_results_bar">'+
1705 '<span style="float:left;top:0px;font-style:italic;">'+
1706 gM('rsd_layout')+' '+
1707 '<img id="msc_box_layout" ' +
1708 'title = "' + gM('rsd_box_layout') + '" '+
1709 'src = "' + ( (_this.result_display_mode=='box')?box_dark_url:box_light_url ) + '" ' +
1710 'style="width:20px;height:20px;cursor:pointer;"> ' +
1711 '<img id="msc_list_layout" '+
1712 'title = "' + gM('rsd_list_layout') + '" '+
1713 'src = "' + ( (_this.result_display_mode=='list')?list_dark_url:list_light_url ) + '" '+
1714 'style="width:20px;height:20px;cursor:pointer;">'+
1715 about_desc +
1716 '</span>'+
1717 '<span id="rsd_paging_ctrl" style="float:right;"></span>'+
1718 '</div>'
1719 );
1720 //get paging with bindings:
1721 this.getPaging('#rsd_paging_ctrl');
1722
1723 $j('#msc_box_layout').hover(function(){
1724 $j(this).attr("src", box_dark_url );
1725 }, function(){
1726 $j(this).attr("src", ( (_this.result_display_mode=='box')?box_dark_url:box_light_url ) );
1727 }).click(function(){
1728 $j(this).attr("src", box_dark_url);
1729 $j('#msc_list_layout').attr("src", list_light_url);
1730 _this.setDispMode('box');
1731 });
1732
1733 $j('#msc_list_layout').hover(function(){
1734 $j(this).attr("src", list_dark_url);
1735 }, function(){
1736 $j(this).attr("src", ( (_this.result_display_mode=='list')?list_dark_url:list_light_url ) );
1737 }).click(function(){
1738 $j(this).attr("src", list_dark_url);
1739 $j('#msc_box_layout').attr("src", box_light_url);
1740 _this.setDispMode('list');
1741 });
1742 }
1743 },
1744 getPaging:function(target){
1745 var _this = this;
1746 var cp_id = this.disp_item;
1747 var cp = this.content_providers[ this.disp_item ];
1748 //js_log('getPaging:'+ cp_id + ' len: ' + cp.sObj.num_results);
1749 var to_num = ( cp.limit > cp.sObj.num_results )?
1750 (cp.offset + cp.sObj.num_results):
1751 (cp.offset + cp.limit);
1752 var out = gM('rsd_results_desc') + ' ' + (cp.offset+1) + ' to ' + to_num;
1753 //check if we have more results (next prev link)
1754 if( cp.offset >= cp.limit )
1755 out+=' <a href="#" id="rsd_pprev">' + gM('rsd_results_prev') + ' ' + cp.limit + '</a>';
1756
1757 if( cp.sObj.more_results )
1758 out+=' <a href="#" id="rsd_pnext">' + gM('rsd_results_next') + ' ' + cp.limit + '</a>';
1759
1760 $j(target).html(out);
1761 //set bindings
1762 $j('#rsd_pnext').click(function(){
1763 cp.offset += cp.limit;
1764 _this.runSearch();
1765 });
1766 $j('#rsd_pprev').click(function(){
1767 cp.offset -= cp.limit;
1768 if(cp.offset<0)
1769 cp.offset=0;
1770 _this.runSearch();
1771 });
1772
1773 return;
1774
1775 },
1776 selectTab:function( selected_cp_id ){
1777 js_log('select tab: ' + selected_cp_id);
1778 this.disp_item = selected_cp_id;
1779 if( this.disp_item == 'upload' ){
1780 this.doUploadInteface();
1781 }else{
1782 //update the search results:
1783 this.runSearch();
1784 }
1785 },
1786 setDispMode:function(mode){
1787 js_log('setDispMode:' + mode);
1788 this.result_display_mode=mode;
1789 //run /update search display:
1790 this.drawOutputResults();
1791 }
1792 };