public function createLink(UseyourDrive_Node $cachedentry = null, $shorten = true)
 {
     $link = false;
     $error = false;
     if ($cachedentry === null) {
         /* Check if file is cached and still valid */
         $cached = $this->cache->isCached($this->_requestedEntry);
         /* Get the file if not cached */
         if ($cached === false) {
             $cachedentry = $this->getEntry($this->_requestedEntry);
         } else {
             $cachedentry = $cached;
         }
     }
     if ($cachedentry !== null && $cachedentry !== false) {
         $entry = $cachedentry->getItem();
         /* Check file permission */
         $has_permission = false;
         $permissions = $entry->getPermissions();
         $permission_type = $this->settings['permission_domain'] === '' ? 'anyone' : 'domain';
         $permission_value = $this->settings['permission_domain'] === '' ? '' : $this->settings['permission_domain'];
         if (count($entry->getPermissions()) > 0) {
             if ($this->settings['manage_permissions'] === 'Yes') {
                 foreach ($entry->getPermissions() as $permission) {
                     if ($permission->getType() === $permission_type && in_array($permission->getRole(), array('reader', 'writer')) && $permission->getValue() === $permission_value && $permission->getWithLink()) {
                         $has_permission = true;
                         $shareable = true;
                         break;
                     }
                 }
             } else {
                 $shareable = true;
             }
         }
         /* Set new permission if needed */
         if ($has_permission === false && $this->settings['manage_permissions'] === 'Yes') {
             $newPermission = new Google_Service_Drive_Permission();
             $newPermission->setType($permission_type);
             $newPermission->setRole("reader");
             $newPermission->setValue($permission_value);
             $newPermission->setWithLink(true);
             try {
                 $permission = $this->googleDriveService->permissions->insert($entry->getId(), $newPermission);
                 $cachedentry = $this->getEntry($this->_requestedEntry, true);
                 $entry = $cachedentry->getItem();
                 $shareable = true;
             } catch (Exception $e) {
                 $shareable = false;
             }
         }
         $linkurl = $entry->getWebContentLink();
         if ($shareable) {
             $linkurl = $entry->getAlternateLink();
             if (strpos($entry->getMimeType(), 'video') !== false || strpos($entry->getMimeType(), 'audio') !== false) {
                 $embedlink = $entry->getEmbedLink();
                 if (!empty($embedlink)) {
                     $linkurl = 'https://docs.google.com/file/d/' . $entry->getId() . '/preview';
                 }
             }
         }
         if (!empty($linkurl)) {
             if ($shorten) {
                 $url = new Google_Service_Urlshortener_Url();
                 $url->longUrl = $linkurl;
                 $url = $this->googleUrlshortenerService->url->insert($url, array("userIp" => $this->userip));
                 $link = $url->getId();
             } else {
                 $link = $linkurl;
             }
         } else {
             $error = __("Can't create link", 'useyourdrive');
         }
     }
     $embedlink = $entry->getEmbedLink();
     if (empty($embedlink)) {
         $embedlink = 'https://docs.google.com/viewer?srcid=' . $entry->getId() . '&pid=explorer&embedded=true';
         /* As of 12 November 2014, the Google Doc viewer doesn't display PDF files anymore */
         if (strpos($entry->getMimeType(), 'application/pdf') !== false) {
             $embedlink = 'https://docs.google.com/file/d/' . $entry->getId() . '/preview';
             /* Powerpoints can't be showed embedded */
         } elseif (strpos($entry->getMimeType(), 'google-apps.presentation') !== false) {
             $embedlink = 'https://docs.google.com/presentation/d/' . $entry->getId() . '/preview';
         }
     } else {
         if (strpos($entry->getMimeType(), 'application/vnd.google-apps') === false) {
             $embedlink = 'https://docs.google.com/file/d/' . $entry->getId() . '/preview';
             /* Powerpoints can't be showed embedded */
         } elseif (strpos($entry->getMimeType(), 'google-apps.presentation') !== false) {
         } else {
             $embedlink = $entry->getAlternateLink();
             $embedlink = str_replace('http://', 'https://', $embedlink);
         }
     }
     $resultdata = array('id' => $entry->getId(), 'name' => $entry->getTitle(), 'link' => $link, 'embeddedlink' => $embedlink, 'size' => UseyourDrive_bytesToSize1024($entry->getFileSize()), 'error' => $error);
     return $resultdata;
 }
        public function CheckDriveApp()
        {
            if (!$this->canconnect) {
                $this->AdminNotice(true);
                return false;
            }
            $authorize = true;
            $authorizebutton = "<input id='authorizeDrive_button' type='button' value='" . __('(Re) Authorize the Plugin!', 'useyourdrive') . "' class='button-primary'/>";
            $revokebutton = "<input id='revokeDrive_button' type='button' value='" . __('Revoke authorization', 'useyourdrive') . "' class='button-secondary'/>&nbsp;";
            $appInfo = $this->UseyourDrive->setAppConfig('force');
            if (is_wp_error($appInfo)) {
                echo "<div id='message' class='error'><p>" . $appInfo->get_error_message() . "</p></div>";
                return false;
            }
            /* are we coming from Google API auth page? */
            if (!empty($_GET['code'])) {
                $createToken = $this->UseyourDrive->createToken();
                if (is_wp_error($createToken)) {
                    echo "<div id='message' class='error'><p>" . $createToken->get_error_message() . '</p><p>' . $authorizebutton . "</p></div>";
                } else {
                    $page = isset($_GET["page"]) ? '?page=' . $_GET["page"] : '';
                    $location = get_admin_url(null, 'admin.php' . $page);
                    echo "<script type='text/javascript'>window.location.href = '" . $location . "';</script>";
                }
            }
            $authUrl = $this->UseyourDrive->startWebAuth();
            $hasToken = $this->UseyourDrive->loadToken();
            if (!empty($_GET['error']) && $_GET['error'] === 'access_denied') {
                $this->UseyourDrive->revokeToken();
                $hasToken = new WP_Error('broke', __("The plugin isn't yet authorized to use your Google Drive! Please (re)-authorize the plugin", 'useyourdrive'));
            }
            if (is_wp_error($hasToken)) {
                echo "<div id='message' class='error'><p>" . $hasToken->get_error_message() . '</p><p>' . $authorizebutton . "</p></div>";
            } else {
                $client = $this->UseyourDrive->startClient();
                $accountInfo = $this->UseyourDrive->getAccountInfo();
                if ($accountInfo === false) {
                    $error = new WP_Error('broke', __("Plugin isn't linked to your Google Drive anymore... Please Reauthorize!", 'useyourdrive'));
                    echo "<div id='message' class='error'><p>" . $error->get_error_message() . '</p><p>' . $authorizebutton . "</p></div>";
                } else {
                    if (is_wp_error($accountInfo)) {
                        $error = $accountInfo;
                        echo "<div id='message' class='error'><p>" . $error->get_error_message() . '</p><p>' . $authorizebutton . "</p></div>";
                    } else {
                        $user = $accountInfo->getName();
                        $email = $accountInfo->getEmail();
                        $driveInfo = $this->UseyourDrive->getDriveInfo();
                        if (is_wp_error($driveInfo)) {
                            $error = $driveInfo;
                            echo "<div id='message' class='error'><p><strong>{$user} ({$email})</strong></p><p><i>" . $error->get_error_message() . "</i></p><p>" . __('Use-your-Drive can\'t access your Google Drive as the Google Drive App isn\'t properly configurated.', 'useyourdrive') . " Please use <a href='https://cloud.google.com/console' target='_blank'>Google Developers Console</a> to activate the <strong>Drive API</strong> (not SDK) for your project. You can find this setting under 'APIs & auth'.</p><p>" . $revokebutton . "</p></div>";
                        } else {
                            $storage = UseyourDrive_bytesToSize1024($driveInfo->getQuotaBytesUsed()) . '/' . UseyourDrive_bytesToSize1024($driveInfo->getQuotaBytesTotal());
                            $authorize = false;
                            echo "<div id='message' class='updated'><p>" . __('Use-your-Drive is succesfully authorized and linked with your Google account:', 'useyourdrive') . "<br/><strong>{$user} ({$email} - {$storage})</strong></p><p>" . $revokebutton . $authorizebutton . "</p></div>";
                        }
                    }
                }
            }
            ?>
      <script type="text/javascript" >
        jQuery(document).ready(function ($) {
          $('#authorizeDrive_button').click(function () {
            window.location = '<?php 
            echo $authUrl;
            ?>
';
          });
          $('#revokeDrive_button').click(function () {
            $.ajax({type: "POST",
              url: '<?php 
            echo admin_url('admin-ajax.php');
            ?>
',
              data: {
                action: 'useyourdrive-revoke'
              },
              success: function (response) {
                location.reload(true)
              },
              dataType: 'json'
            });
          });
        });
      </script>
      <?php 
        }
 protected function sendNotificationEmail($emailtype = false, $entry = array(), $entrypath = false)
 {
     if ($emailtype === false) {
         return;
     }
     /* Get emailaddress */
     $email = strtr(trim($this->options['notificationemail']), array("%admin_email%" => get_site_option('admin_email')));
     /* Current site url */
     $currenturl = $_SERVER['HTTP_REFERER'];
     /* Vistor name and email */
     $visitor = __('A guest', 'useyourdrive');
     if (is_user_logged_in()) {
         $current_user = wp_get_current_user();
         $visitor = $current_user->display_name;
         $email = strtr($this->options['notificationemail'], array("%user_email%" => $current_user->user_email));
     }
     /* Subject */
     $subject = get_bloginfo();
     /* Create Message */
     switch ($emailtype) {
         case 'download':
             $subject .= ' | ' . __('File downloaded', 'useyourdrive') . ': ' . $entry->getTitle();
             $message = strtr(trim($this->settings['download_template']), array("%visitor%" => $visitor, "%currenturl%" => $currenturl, "%filename%" => $entrypath, "%filesize%" => UseyourDrive_bytesToSize1024($entry->getFileSize())));
             break;
         case 'upload':
             $subject .= ' | ' . __('New file(s) on Google Drive', 'useyourdrive');
             $filelist = '';
             foreach ($entry as $file) {
                 $succeeded = isset($file->error) ? " | " . $file->error : '';
                 $filelist .= $file->completepath . " (" . UseyourDrive_bytesToSize1024($file->size) . ")" . $succeeded . "\n";
             }
             $message = strtr(trim($this->settings['upload_template']), array("%visitor%" => $visitor, "%currenturl%" => $currenturl, "%filelist%" => $filelist));
             break;
         case 'deletion':
             $subject .= ' | ' . __('File deleted on Google Drive', 'useyourdrive');
             $filelist = $entrypath . " (" . UseyourDrive_bytesToSize1024($entry->getFileSize()) . ")\n";
             $message = strtr(trim($this->settings['delete_template']), array("%visitor%" => $visitor, "%currenturl%" => $currenturl, "%filelist%" => $filelist));
             break;
         case 'deletion_multiple':
             $subject .= ' | ' . __('File(s) deleted on Google Drive', 'useyourdrive');
             $filelist = '';
             foreach ($entry as $filelist_text) {
                 $filelist .= $filelist_text . "\n";
             }
             $message = strtr(trim($this->settings['delete_template']), array("%visitor%" => $visitor, "%currenturl%" => $currenturl, "%filelist%" => $filelist));
             break;
     }
     /* Send mail */
     try {
         $emailrecipients = explode(',', $email);
         foreach ($emailrecipients as $recipient) {
             $result = wp_mail($recipient, $subject, $message);
         }
     } catch (Exception $ex) {
     }
 }
    _e('Start upload', 'useyourdrive');
    ?>
</span>
          </button>
          <button type="reset" class="cancel">
            <span><?php 
    _e('Cancel upload', 'useyourdrive');
    ?>
</span>
          </button>
        <?php 
}
?>
        <span class="filesize"><?php 
_e('Max. ', 'useyourdrive');
?>
 <span><?php 
echo UseyourDrive_bytesToSize1024($this->options['maxfilesize']);
?>
</span></span>
      </div>
      <div class='fileupload-list'>
        <div role="presentation">
          <div class="files">&nbsp;</div>

        </div>
        <input type="hidden" name="fileupload-filelist" id="fileupload-filelist" class="fileupload-filelist" value="">
      </div>
    </div>
  </div>
</div>
 public function renderDescription($item)
 {
     $html = '';
     if (!empty($item['description'])) {
         $title = $item['basename'] . ($this->options['show_filesize'] === '1' && $item['size'] > 0 ? ' (' . UseyourDrive_bytesToSize1024($item['size']) . ')' : '&nbsp;');
         $html .= "<a class='entry_description'><i class='fa fa-info-circle fa-lg'></i></a>\n";
         $html .= "<div class='description_textbox'>";
         if ($this->options['editdescription'] === '1' && $this->checkUserRole($this->options['editdescription_role'])) {
             $html .= "<span class='entry_edit_description'><a class='entry_action_description' data-id='" . $item['id'] . "'><i class='fa fa-pencil-square fa-lg'></i></a></span>";
         }
         $html .= "<div class='description_title'>{$title}</div><div class='description_text'>" . nl2br($item['description']) . "</div>";
         $html .= "</div>";
     }
     return $html;
 }