PDF link handler; never gets explicitly called by user
13424
def handle_starttag(self, tag, attrs):
    '''
    
    '''
    if tag == 'a' and ( ('class', 'download-pdf') in attrs or ('id', 'download-pdf') in attrs ):
        for attr in attrs:
          if attr[0] == 'href':
            self.download_link = 'http://www.nature.com' + attr[1]
190201
function attachHandlers() {

        function handleDragOver(event) {
            event = event.originalEvent || event;

            var files = event.dataTransfer.files;

            stopURIListPropagation(files, event);

            if (files && files.length) {
                event.stopPropagation();
                event.preventDefault();

                var dropEffect = "none";

                // Don't allow drag-and-drop of files/folders when a modal dialog is showing.
                if ($(".modal.instance").length === 0 && isValidDrop(event.dataTransfer.items)) {
                    dropEffect = "copy";
                }
                event.dataTransfer.dropEffect = dropEffect;
            }
        }

        function handleDrop(event) {
            event = event.originalEvent || event;

            var files = event.dataTransfer.files;

            stopURIListPropagation(files, event);

            if (files && files.length) {
                event.stopPropagation();
                event.preventDefault();

                brackets.app.getDroppedFiles(function (err, paths) {
                    if (!err) {
                        openDroppedFiles(paths);
                    }
                });
            }
        }

        // For most of the window, only respond if nothing more specific in the UI has already grabbed the event (e.g.
        // the Extension Manager drop-to-install zone, or an extension with a drop-to-upload zone in its panel)
        $(window.document.body)
            .on("dragover", handleDragOver)
            .on("drop", handleDrop);

        // Over CodeMirror specifically, always pre-empt CodeMirror's drag event handling if files are being dragged - CM stops
        // propagation on any drag event it sees, even when it's not a text drag/drop. But allow CM to handle all non-file drag
        // events. See bug #10617.
        window.document.body.addEventListener("dragover", function (event) {
            if ($(event.target).closest(".CodeMirror").length) {
                handleDragOver(event);
            }
        }, true);
        window.document.body.addEventListener("drop", function (event) {
            if ($(event.target).closest(".CodeMirror").length) {
                handleDrop(event);
            }
        }, true);
    }
306302
def handle_link(self, link, py3o_base, closing_link):
        
        # OLD open office version
        if link.text is not None and link.text.strip():
            if not link.text == py3o_base:
                msg = "url and text do not match in '%s'" % link.text
                raise TemplateException(msg)

        # new open office version
        elif len(link):
            if not link[0].text == py3o_base:
                msg = "url and text do not match in '%s'" % link.text
                raise TemplateException(msg)
        else:
            raise TemplateException("Link text not found")

        # find out if the instruction is inside a table
        parent = link.getparent()
        keep_start_boundary = False
        keep_end_boundary = False

        if parent.getparent() is not None and parent.getparent().tag == (
            "{%s}table-cell" % self.namespaces['table']
        ):
            # we are in a table
            opening_paragraph = parent
            opening_cell = opening_paragraph.getparent()

            # same for closing
            closing_paragraph = closing_link.getparent()
            closing_cell = closing_paragraph.getparent()

            if opening_cell == closing_cell:
                # block is fully in a single cell
                opening_row = opening_paragraph
                closing_row = closing_paragraph
            else:
                opening_row = opening_cell.getparent()
                closing_row = closing_cell.getparent()

        elif parent.tag == "{%s}p" % self.namespaces['text']:
            # if we are using text we want to keep start/end nodes
            keep_start_boundary, keep_end_boundary = detect_keep_boundary(
                link, closing_link, self.namespaces
            )
            # we are in a text paragraph
            opening_row = parent
            closing_row = closing_link.getparent()

        else:
            raise NotImplementedError(
                "We handle urls in tables or text paragraph only"
            )

        # max split is one
        instruction, instruction_value = py3o_base.split("=", 1)
        instruction_value = instruction_value.strip('"')

        attribs = dict()
        attribs['{%s}strip' % GENSHI_URI] = 'True'
        attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value

        genshi_node = lxml.etree.Element(
            'span',
            attrib=attribs,
            nsmap={'py': GENSHI_URI},
        )

        link.getparent().remove(link)
        closing_link.getparent().remove(closing_link)

        try:
            move_siblings(
                opening_row, closing_row, genshi_node,
                keep_start_boundary=keep_start_boundary,
                keep_end_boundary=keep_end_boundary,
            )
        except ValueError as e:
            log.exception(e)
            raise TemplateException("Could not move siblings for '%s'" %
                                    py3o_base)
289883
function forEachItem(pdf, handler) {
  var pageNumber = 0;
  for (var p in pdf.formImage.Pages) {
    var page = pdf.formImage.Pages[p];
    var number = ++pageNumber;
    handler(null, {
      page: number,
      width: pdf.formImage.Width,
      height: pdf.formImage.Pages[number - 1].Height
    });
    for (var t in page.Texts) {
      var item = page.Texts[t];
      item.text = decodeURIComponent(item.R[0].T);
      handler(null, item);
    }
  }
  handler();
}
379512
public function fileExistFormatLink( $path , $user , $event , $view , $name , $class = NULL){
		
		$link = $path.$user.'/'.$view.'_'.$event.'-'.$user.'.pdf';
		$url  = getcwd().'/'.$link;

		$add  = '';
		
		if ( \File::exists($url) )
		{
			$asset = asset($link);

			if($class){
				$add = ' class="'.$class.'" ';
			}
			
			return '<a target="_blank" href="'.$asset.'"'.$add.'>'.$name.'</a>';	
		}
		
		return '';
	}
585353
def slicer(document, first_page=None, last_page=None, suffix='sliced', tempdir=None):
    """"""
    # Set output file name
    if tempdir:
        with NamedTemporaryFile(suffix='.pdf', dir=tempdir, delete=False) as temp:
            output = temp.name
    elif suffix:
        output = os.path.join(os.path.dirname(document), add_suffix(document, suffix))
    else:
        with NamedTemporaryFile(suffix='.pdf') as temp:
            output = temp.name

    # Reindex page selections for simple user input
    first_page = first_page - 1 if not None else None

    # Validate page range by comparing selection to number of pages in PDF document
    pages = Info(document).pages
    invalid = 'Number of pages: ' + str(pages) + ' ----> Page Range Input: ' + str(first_page) + '-' + str(last_page)
    assert first_page <= last_page <= pages, invalid

    pdf = PdfFileReader(document)
    writer = PdfFileWriter()

    pages = list(range(pdf.getNumPages()))[first_page:last_page]
    for page in pages:
        writer.addPage(pdf.getPage(page))

    with open(output, 'wb') as out:
        writer.write(out)
    return output
1003460
function attachHandlers(segments, modifiedEventId) {
		var segmentContainer = getDaySegmentContainer();

		segmentElementEach(segments, function(segment, element, i) {
			var event = segment.event;
			if (event._id === modifiedEventId) {
				bindDaySeg(event, element, segment);
			}else{
				element[0]._fci = i; // for lazySegBind
			}
		});

		lazySegBind(segmentContainer, segments, bindDaySeg);
	}
402792
def prompt_user_to_select_link(self, links):
        
        link_pages = self.get_link_pages(links)
        n = 0
        while n in range(len(link_pages)):
            link_page = link_pages[n]
            text = 'Select a link to open (page {} of {}):\n\n'
            text = text.format(n+1, len(link_pages))
            text += self.get_link_page_text(link_page)
            if link_page is not link_pages[-1]:
                text += '[j] next page...'
            if link_page is not link_pages[0]:
                if link_page is not link_pages[-1]:
                    text += '\n'
                text += '[k] ...previous page'

            try:
                choice = chr(self.show_notification(text))
                try:
                    choice = int(choice)
                except ValueError:
                    pass
            except ValueError:
                return None
            if choice == 'j':
                if link_page is not link_pages[-1]:
                    n += 1
                continue
            elif choice == 'k':
                if link_page is not link_pages[0]:
                    n -= 1
                continue
            elif choice not in range(len(link_page)):
                return None
            return link_page[choice]['href']
354944
function loadHandler (event) {
    const target = event.target;

    // change the link to the new file
    link.setAttribute('href', target.result);

    // make sure checkbox is no longer checked
    checkbox.checked = false;

    // make link not hidden
    link.style.display = '';

    // make delete checkbox not hidden
    deleter.style.display = '';

    // image uploaded
    if (file.type.match('image.*')) {
      // create image
      const image = new Image();
      image.title = file.name;
      image.src = target.result;

      // replace file--link contents
      link = clear(link);
      link.appendChild(image);
    }
    else {
      // non-image file
      link.textContent = file.name;
    }
  }
798859
function pdfViewClose() {
          var errorWrapper = this.appConfig.errorWrapper.container;
          errorWrapper.setAttribute('hidden', 'true');
          if (!this.pdfLoadingTask) {
            return Promise.resolve();
          }
          var promise = this.pdfLoadingTask.destroy();
          this.pdfLoadingTask = null;
          if (this.pdfDocument) {
            this.pdfDocument = null;
            this.pdfThumbnailViewer.setDocument(null);
            this.pdfViewer.setDocument(null);
            this.pdfLinkService.setDocument(null, null);
          }
          this.store = null;
          this.isInitialViewSet = false;
          this.pdfSidebar.reset();
          this.pdfOutlineViewer.reset();
          this.pdfAttachmentViewer.reset();
          this.findController.reset();
          this.findBar.reset();
          if (typeof PDFBug !== 'undefined') {
            PDFBug.cleanup();
          }
          return promise;
        }
44057
def handle_link(self, value):
        
        for s, p, o in self.graph.triples((value, None, None)):
            if p == LINK_ELEM:
                return unicode(o).replace('file://', '')
1226070
private void beginInternalLink(ResourceReference reference, boolean freestanding,
        Map<String, String> parameters)
    {
        Map<String, String> spanAttributes = new LinkedHashMap<String, String>();
        Map<String, String> anchorAttributes = new LinkedHashMap<String, String>();

        // Add all parameters to the A attributes
        anchorAttributes.putAll(parameters);

        if (StringUtils.isEmpty(reference.getReference())) {
            spanAttributes.put(CLASS, WIKILINK);
            renderAutoLink(reference, spanAttributes, anchorAttributes);
        } else if (this.wikiModel.isDocumentAvailable(reference)) {
            spanAttributes.put(CLASS, WIKILINK);
            anchorAttributes.put(XHTMLLinkRenderer.HREF, this.wikiModel.getDocumentViewURL(reference));
        } else {
            // The wiki document doesn't exist
            spanAttributes.put(CLASS, "wikicreatelink");
            anchorAttributes.put(XHTMLLinkRenderer.HREF, this.wikiModel.getDocumentEditURL(reference));
        }

        getXHTMLWikiPrinter().printXMLStartElement(SPAN, spanAttributes);
        getXHTMLWikiPrinter().printXMLStartElement(XHTMLLinkRenderer.ANCHOR, anchorAttributes);
    }
631686
function publishHandlerLink( $element, &$params )
    {
        $ret = null;

        $href = $element->getAttribute( 'href' );

        if ( $href )
        {
            if ( preg_match( "@^ezobject://[0-9]+(#.*)?$@", $href ) )
            {
                $url = strtok( $href, '#' );
                $anchorName = strtok( '#' );
                $objectID = substr( strrchr( $url, "/" ), 1 );
                $element->setAttribute( 'object_id', $objectID );

                 if ( !in_array( $objectID, $this->linkedObjectIDArray ) )
                 {
                    $this->linkedObjectIDArray[] = $objectID;
                }
            }
            elseif ( preg_match( "@^eznode://.+(#.*)?$@" , $href ) )
            {
                $objectID = null;
                $url = strtok( $href, '#' );
                $anchorName = strtok( '#' );
                $nodePath = substr( strchr( $url, "/" ), 2 );
                if ( preg_match( "@^[0-9]+$@", $nodePath ) )
                {
                    $nodeID = $nodePath;
                    $node = eZContentObjectTreeNode::fetch( $nodeID, false, false );
                    if ( !$node )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Node '%1' does not exist.", '', array( $nodeID ) ) );
                    }
                    else
                    {
                        $objectID = $node['id'];
                    }
                }
                else
                {
                    $node = eZContentObjectTreeNode::fetchByURLPath( $nodePath, false );
                    if ( !$node )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Node '%1' does not exist.", '', array( $nodePath ) ) );
                    }
                    else
                    {
                        $nodeID = $node['node_id'];
                        $objectID = $node['id'];
                    }
                    $element->setAttribute( 'show_path', 'true' );
                }
                $element->setAttribute( 'node_id', $nodeID );

                if ( $objectID && !in_array( $objectID, $this->linkedObjectIDArray ) )
                {
                    $this->linkedObjectIDArray[] = $objectID;
                }
            }
            elseif ( preg_match( "@^#.*$@" , $href ) )
            {
                $anchorName = substr( $href, 1 );
            }
            else
            {
                //washing href. single and double quotes replaced with their urlencoded form
                $href = str_replace( array('\'','"'), array('%27','%22'), $href );

                $temp = explode( '#', $href );
                $url = $temp[0];
                if ( isset( $temp[1] ) )
                {
                    $anchorName = $temp[1];
                }

                if ( $url )
                {
                    // Protection from XSS attack
                    if ( preg_match( "/^(java|vb)script:.*/i" , $url ) )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Using scripts in links is not allowed, link '%1' has been removed", '', array( $url ) ) );

                        $element->removeAttribute( 'href' );
                        return $ret;

                    }
                    // Check mail address validity following RFC 5322 and RFC 5321
                    if ( preg_match( "/^mailto:([^.][a-z0-9!#\$%&'*+-\/=?`{|}~^]+@([a-z0-9.-]+))/i" , $url, $mailAddr ) &&
                         !eZMail::validate( $mailAddr[1] ) )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Invalid e-mail address: '%1'", '' , array( $mailAddr[1] ) ) );

                        $element->removeAttribute( 'href' );
                        return $ret;
                    }
                    // Store urlID instead of href
                    $urlID = $this->convertHrefToID( $url );
                    if ( $urlID )
                    {
                        $urlIDAttributeName = 'url_id';

                        $element->setAttribute( $urlIDAttributeName, $urlID );
                    }
                }
            }

            if ( isset( $anchorName ) && $anchorName )
            {
                $element->setAttribute( 'anchor_name', $anchorName );
            }

            $element->removeAttribute( 'href' );
        }

        return $ret;
    }
919942
function pdfViewInitialize() {
    var pdfRenderingQueue = new PDFRenderingQueue();
    pdfRenderingQueue.onIdle = this.cleanup.bind(this);
    this.pdfRenderingQueue = pdfRenderingQueue;

    var pdfLinkService = new PDFLinkService();
    this.pdfLinkService = pdfLinkService;

    var container = document.getElementById('viewerContainer');
    var viewer = document.getElementById('viewer');
    this.pdfViewer = new PDFViewer({
      container: container,
      viewer: viewer,
      renderingQueue: pdfRenderingQueue,
      linkService: pdfLinkService
    });
    pdfRenderingQueue.setViewer(this.pdfViewer);
    pdfLinkService.setViewer(this.pdfViewer);

    var thumbnailContainer = document.getElementById('thumbnailView');
    this.pdfThumbnailViewer = new PDFThumbnailViewer({
      container: thumbnailContainer,
      renderingQueue: pdfRenderingQueue,
      linkService: pdfLinkService
    });
    pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);

    Preferences.initialize();

    this.pdfHistory = new PDFHistory({
      linkService: pdfLinkService
    });
    pdfLinkService.setHistory(this.pdfHistory);

    this.findController = new PDFFindController({
      pdfViewer: this.pdfViewer,
      integratedFind: this.supportsIntegratedFind
    });
    this.pdfViewer.setFindController(this.findController);

    this.findBar = new PDFFindBar({
      bar: document.getElementById('findbar'),
      toggleButton: document.getElementById('viewFind'),
      findField: document.getElementById('findInput'),
      highlightAllCheckbox: document.getElementById('findHighlightAll'),
      caseSensitiveCheckbox: document.getElementById('findMatchCase'),
      findMsg: document.getElementById('findMsg'),
      findStatusIcon: document.getElementById('findStatusIcon'),
      findPreviousButton: document.getElementById('findPrevious'),
      findNextButton: document.getElementById('findNext'),
      findController: this.findController
    });

    this.findController.setFindBar(this.findBar);

    HandTool.initialize({
      container: container,
      toggleHandTool: document.getElementById('toggleHandTool')
    });

    this.pdfDocumentProperties = new PDFDocumentProperties({
      overlayName: 'documentPropertiesOverlay',
      closeButton: document.getElementById('documentPropertiesClose'),
      fields: {
        'fileName': document.getElementById('fileNameField'),
        'fileSize': document.getElementById('fileSizeField'),
        'title': document.getElementById('titleField'),
        'author': document.getElementById('authorField'),
        'subject': document.getElementById('subjectField'),
        'keywords': document.getElementById('keywordsField'),
        'creationDate': document.getElementById('creationDateField'),
        'modificationDate': document.getElementById('modificationDateField'),
        'creator': document.getElementById('creatorField'),
        'producer': document.getElementById('producerField'),
        'version': document.getElementById('versionField'),
        'pageCount': document.getElementById('pageCountField')
      }
    });

    SecondaryToolbar.initialize({
      toolbar: document.getElementById('secondaryToolbar'),
      toggleButton: document.getElementById('secondaryToolbarToggle'),
      presentationModeButton:
        document.getElementById('secondaryPresentationMode'),
      openFile: document.getElementById('secondaryOpenFile'),
      print: document.getElementById('secondaryPrint'),
      download: document.getElementById('secondaryDownload'),
      viewBookmark: document.getElementById('secondaryViewBookmark'),
      firstPage: document.getElementById('firstPage'),
      lastPage: document.getElementById('lastPage'),
      pageRotateCw: document.getElementById('pageRotateCw'),
      pageRotateCcw: document.getElementById('pageRotateCcw'),
      documentPropertiesButton: document.getElementById('documentProperties')
    });

    if (this.supportsFullscreen) {
      var toolbar = SecondaryToolbar;
      this.pdfPresentationMode = new PDFPresentationMode({
        container: container,
        viewer: viewer,
        pdfThumbnailViewer: this.pdfThumbnailViewer,
        contextMenuItems: [
          { element: document.getElementById('contextFirstPage'),
            handler: toolbar.firstPageClick.bind(toolbar) },
          { element: document.getElementById('contextLastPage'),
            handler: toolbar.lastPageClick.bind(toolbar) },
          { element: document.getElementById('contextPageRotateCw'),
            handler: toolbar.pageRotateCwClick.bind(toolbar) },
          { element: document.getElementById('contextPageRotateCcw'),
            handler: toolbar.pageRotateCcwClick.bind(toolbar) }
        ]
      });
    }

    PasswordPrompt.initialize({
      overlayName: 'passwordOverlay',
      passwordField: document.getElementById('password'),
      passwordText: document.getElementById('passwordText'),
      passwordSubmit: document.getElementById('passwordSubmit'),
      passwordCancel: document.getElementById('passwordCancel')
    });

    var self = this;
    var initializedPromise = Promise.all([
      Preferences.get('enableWebGL').then(function resolved(value) {
        PDFJS.disableWebGL = !value;
      }),
      Preferences.get('sidebarViewOnLoad').then(function resolved(value) {
        self.preferenceSidebarViewOnLoad = value;
      }),
      Preferences.get('pdfBugEnabled').then(function resolved(value) {
        self.preferencePdfBugEnabled = value;
      }),
      Preferences.get('showPreviousViewOnLoad').then(function resolved(value) {
        self.preferenceShowPreviousViewOnLoad = value;
      }),
      Preferences.get('defaultZoomValue').then(function resolved(value) {
        self.preferenceDefaultZoomValue = value;
      }),
      Preferences.get('disableTextLayer').then(function resolved(value) {
        if (PDFJS.disableTextLayer === true) {
          return;
        }
        PDFJS.disableTextLayer = value;
      }),
      Preferences.get('disableRange').then(function resolved(value) {
        if (PDFJS.disableRange === true) {
          return;
        }
        PDFJS.disableRange = value;
      }),
      Preferences.get('disableAutoFetch').then(function resolved(value) {
        PDFJS.disableAutoFetch = value;
      }),
      Preferences.get('disableFontFace').then(function resolved(value) {
        if (PDFJS.disableFontFace === true) {
          return;
        }
        PDFJS.disableFontFace = value;
      }),
      Preferences.get('useOnlyCssZoom').then(function resolved(value) {
        PDFJS.useOnlyCssZoom = value;
      })
      // TODO move more preferences and other async stuff here
    ]).catch(function (reason) { });

    return initializedPromise.then(function () {
      PDFViewerApplication.initialized = true;
    });
  }
727822
static function call($command, $additional_command_params = null, $post_params = null, $attachments = null) {
      if(empty(self::$url) || empty(self::$key) || empty(self::$connector)) {
        throw new WrapperNotInitialized();
      } // if

      // ---------------------------------------------------
      //  Prepare command URl
      // ---------------------------------------------------

      $data = is_array($additional_command_params) && count($additional_command_params) ? $additional_command_params : array();

      $data['path_info'] = $command;
      $data['auth_api_token'] = self::$key;
      $data['format'] = 'json';
      $command_url = self::$url . '?' . http_build_query($data);

      // ---------------------------------------------------
      //  Prepare attachments
      // ---------------------------------------------------

      if(empty($attachments)) {
        $file_params = null;
      } else {
        $file_params = array();

        $counter = 1;

        foreach($attachments as $attachment) {
          if(is_readable($attachment)) {
            $file_params['attachment_' . $counter++] = $attachment;
          } else {
            throw new FileNotReadable($attachment);
          } // if
        } // foreach
      } // if

      // ---------------------------------------------------
      //  Prepare POST variables
      // ---------------------------------------------------

      if(empty($post_params)) {
        $post_params = array();
      } else {
        if(!isset($post_params['submitted']) || $post_params['submitted'] != 'submitted') {
          $post_params['submitted'] = 'submitted';
        } // if

        foreach($post_params as $post_param => $post_param_value) {
          if(is_array($post_param_value)) {
            foreach($post_param_value as $k => $v) {
              $post_params["{$post_param}[{$k}]"] = $v;
            } // foreach

            unset($post_params[$post_param]);
          } // if
        } // foreach
      } // if

      // ---------------------------------------------------
      //  Make the call and decode the result
      // ---------------------------------------------------

      if(empty($post_params) && empty($file_params)) {
        $response = self::$connector->get($command_url);
      } else {
        $response = self::$connector->post($command_url, $post_params, $file_params);
      } // if

      return json_decode($response, true);
    }
3084
static HandlerRegistration capturePageEvent (String name, EventHandler handler) {
    return addEventListener(Document.get(), name, handler, true);
  }
322963
function (context, callback) {

            var path = context.request.urlInfo.pathname,
                relativePath = this.$restHandler.$.path;

            if (path.indexOf(relativePath) !== 0) {
                callback(new Error("Handler path '" + relativePath + "' not at start of " + path));
                return;
            }

            // remove relative handler path from path
            path = path.substring(relativePath.length);

            var pathElements = path.split('/');

            // remove first empty path
            pathElements.shift();

            try {
                callback(null, this._getResourceForPath(pathElements));
            } catch (e) {
                callback(e);
            }
        }