Ejemplo n.º 1
0
 /**
  * @param $file
  * @param array $params
  * @return mixed
  */
 function getPdf($file, array $params)
 {
     global $prefs, $base_url, $tikiroot;
     if ($prefs['auth_token_access'] == 'y') {
         $perms = Perms::get();
         require_once 'lib/auth/tokens.php';
         $tokenlib = AuthTokens::build($prefs);
         $params['TOKEN'] = $tokenlib->createToken($tikiroot . $file, $params, $perms->getGroups(), array('timeout' => 120));
     }
     $url = $base_url . $file . '?' . http_build_query($params, '', '&');
     return $this->{$this->mode}($url);
 }
Ejemplo n.º 2
0
 function action_capture($input)
 {
     global $base_host, $prefs, $user, $tikiroot;
     $smarty = TikiLib::lib('smarty');
     $area = $input->area->text();
     $page = $input->page->text();
     $page = TikiLib::lib('tiki')->take_away_accent($page);
     /* Perform suggested seperator substitutions. */
     $page = TikiLib::lib('tiki')->substituteSeparators($page);
     $uploader = $tikiroot . 'tiki-ajax_services.php';
     $tokenlib = AuthTokens::build($prefs);
     $groups = TikiLib::lib('user')->get_user_groups($user);
     $parameters = array('user' => $user, 'controller' => 'jcapture', 'action' => 'upload');
     $token = $tokenlib->createToken($uploader, $parameters, $groups, array('hits' => 1));
     $parameters['TOKEN'] = $token;
     $uploader = $base_host . $uploader . '?' . http_build_query($parameters, '', '&');
     // NB the "entry" url for createToken has to be without base_host
     $smarty->assign('page', $page);
     $smarty->assign('edit_area', $area);
     $smarty->assign('uploader', $uploader);
     return array();
 }
Ejemplo n.º 3
0
function wikiplugin_playscorm($data, $params)
{
    global $smarty, $tikilib, $base_url, $tikiroot, $tikipath, $userlib, $user, $prefs;
    extract($params, EXTR_SKIP);
    if (empty($moodle_url) || empty($fileId) || empty($moodle_course_id)) {
        return 'moodle_url, moodle_course_id needs to be specified in display parameters, remember to set auth parameters in Admin DSN';
    }
    if (empty($prefs['fgal_use_dir'])) {
        return 'File gallery use directory needs to be set';
    }
    $localname = "scorm{$fileId}";
    $sitepath = parse_url($base_url);
    if (substr($moodle_url, -1) == '/') {
        $moodle_url = substr($moodle_url, 0, -1);
    }
    $moodle_cm_id = '';
    $info = TikiLib::lib('filegal')->get_file($fileId);
    if (!$userlib->user_has_perm_on_object($user, $info['galleryId'], 'file gallery', 'tiki_p_download_files')) {
        return '';
    }
    // check if it already is up to date
    $needrefresh = true;
    if (file_exists($prefs['fgal_use_dir'] . $localname)) {
        $lastupdated = filemtime($prefs['fgal_use_dir'] . $localname);
        if ($lastupdated >= $info['lastModif']) {
            $moodle_cm_id = file_get_contents($prefs['fgal_use_dir'] . $localname);
            $needrefresh = false;
        }
    }
    $fileurl = '';
    if ($needrefresh) {
        $fileurl = $base_url . "tiki-download_file.php?fileId=" . $fileId;
        require_once 'lib/auth/tokens.php';
        $tokenlib = AuthTokens::build($prefs);
        $token = $tokenlib->createToken($tikiroot . "tiki-download_file.php", array('fileId' => $fileId), array('Registered'), array('timeout' => 60, 'hits' => 1));
        $fileurl .= "&TOKEN=" . $token;
    }
    if ($fileurl) {
        // first upload file to moodle
        $preurl = "{$moodle_url}/course/modedit.php?add=scorm&course={$moodle_course_id}&section=0&return=0";
        $submiturl = "{$moodle_url}/course/modedit.php";
        $client = $tikilib->get_http_client($preurl);
        $response = $tikilib->http_perform_request($client);
        $body = $response->getBody();
        preg_match('/sesskey=([^\\"\']+)[\'\\"]/', $body, $matches);
        if (empty($matches[1])) {
            return '';
        } else {
            $sesskey = $matches[1];
        }
        $client->setUri($submiturl);
        $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
        $moodleform = array('sesskey' => $sesskey, 'course' => $moodle_course_id, 'redirecturl' => '../mod/scorm/view.php?id=', 'section' => 0, 'modulename' => 'scorm', 'add' => 'scorm', 'return' => 0, 'name' => 'Tiki Scorm Preview', 'introeditor[text]' => 'Description', 'introeditor[format]' => 1, 'itemId' => 31405523, 'scormtype' => 'localsync', 'packageurl' => $fileurl, 'submitbutton' => 'Save and display', '_qf__mod_scorm_mod_form' => 1, 'hidenav' => 0, 'hidetoc' => 0, 'skipview' => 2, 'popup' => 0, 'hidebrowse' => 0, 'displaycoursestructure' => 0);
        $client->setParameterPost($moodleform);
        $response = $client->request('POST');
        $body = $response->getBody();
        preg_match('/view\\.php\\?id=([0-9]+)/', $body, $matches);
        if (empty($matches[1])) {
            return '';
        } else {
            $moodle_cm_id = $matches[1];
            file_put_contents($prefs['fgal_use_dir'] . $localname, $moodle_cm_id);
        }
    }
    if (!$moodle_cm_id) {
        return '';
    }
    $src = "{$moodle_url}/mod/scorm/view.php?id={$moodle_cm_id}";
    // this is the simple play "student" version requiring hacks since the teacher does not get it
    //$src = "$moodle_url/mod/scorm/player.php?mode=review&cm=$moodle_cm_id&display=popup"; // alternative player version?
    if (isset($width)) {
        $smarty->assign('iframewidth', $width);
    } else {
        $smarty->assign('iframewidth', 1160);
    }
    if (isset($height)) {
        $smarty->assign('iframeheight', $height);
    } else {
        $smarty->assign('iframeheight', 740);
    }
    if (isset($scrolling) && $scrolling == 'n') {
        $smarty->assign('iframescrolling', 'false');
    } else {
        $smarty->assign('iframescrolling', 'true');
    }
    if (isset($id)) {
        $smarty->assign('id', $id);
    } else {
        $smarty->assign('id', '');
    }
    $smarty->assign('iframeurl', $src);
    return $smarty->fetch('wiki-plugins/wikiplugin_playscorm.tpl');
}
Ejemplo n.º 4
0
 function renderOutput($context = array())
 {
     global $prefs;
     global $mimetypes;
     include 'lib/mime/mimetypes.php';
     $galleryId = (int) $this->getOption('galleryId');
     if (!isset($context['list_mode'])) {
         $context['list_mode'] = 'n';
     }
     $value = $this->getValue();
     if ($context['list_mode'] === 'csv') {
         return $value;
     }
     $ret = '';
     if (!empty($value)) {
         if ($this->getOption('displayMode')) {
             // images etc
             $params = array('fileId' => $value);
             if ($context['list_mode'] === 'y') {
                 $otherParams = $this->getOption('displayParamsForLists');
             } else {
                 $otherParams = $this->getOption('displayParams');
             }
             if ($otherParams) {
                 parse_str($otherParams, $otherParams);
                 $params = array_merge($params, $otherParams);
             }
             $params['fromFieldId'] = $this->getConfiguration('fieldId');
             $params['fromItemId'] = $this->getItemId();
             $item = Tracker_Item::fromInfo($this->getItemData());
             $params['checkItemPerms'] = $item->canModify() ? 'n' : 'y';
             if ($this->getOption('displayMode') == 'img') {
                 // img
                 if ($context['list_mode'] === 'y') {
                     $params['thumb'] = $context['list_mode'];
                     $params['rel'] = 'box[' . $this->getInsertId() . ']';
                 }
                 include_once 'lib/wiki-plugins/wikiplugin_img.php';
                 $ret = wikiplugin_img('', $params);
             } else {
                 if ($this->getOption('displayMode') == 'vimeo') {
                     // Vimeo videos stored as filegal REMOTEs
                     include_once 'lib/wiki-plugins/wikiplugin_vimeo.php';
                     $ret = wikiplugin_vimeo('', $params);
                 } else {
                     if ($this->getOption('displayMode') == 'moodlescorm') {
                         include_once 'lib/wiki-plugins/wikiplugin_playscorm.php';
                         foreach ($this->getConfiguration('files') as $fileId => $file) {
                             $params['fileId'] = $fileId;
                             $ret .= wikiplugin_playscorm('', $params);
                         }
                     } else {
                         if ($this->getOption('displayMode') == 'googleviewer') {
                             if ($prefs['auth_token_access'] != 'y') {
                                 $ret = tra('Token access needs to be enabled for Google viewer to be used');
                             } else {
                                 $files = array();
                                 foreach ($this->getConfiguration('files') as $fileId => $file) {
                                     global $base_url, $tikiroot, $https_mode;
                                     if ($https_mode) {
                                         $scheme = 'https';
                                     } else {
                                         $scheme = 'http';
                                     }
                                     $googleurl = $scheme . "://docs.google.com/viewer?url=";
                                     $fileurl = urlencode($base_url . "tiki-download_file.php?fileId=" . $fileId);
                                     require_once 'lib/auth/tokens.php';
                                     $tokenlib = AuthTokens::build($prefs);
                                     $token = $tokenlib->createToken($tikiroot . "tiki-download_file.php", array('fileId' => $fileId), array('Registered'), array('timeout' => 300, 'hits' => 3));
                                     $fileurl .= urlencode("&TOKEN=" . $token);
                                     $url = $googleurl . $fileurl . '&embedded=true';
                                     $title = $file['name'];
                                     $files[] = array('url' => $url, 'title' => $title, 'id' => $fileId);
                                 }
                                 $smarty = TikiLib::lib('smarty');
                                 $smarty->assign('files', $files);
                                 $ret = $smarty->fetch('trackeroutput/files_googleviewer.tpl');
                             }
                         }
                     }
                 }
             }
             $ret = preg_replace('/~\\/?np~/', '', $ret);
         } else {
             $smarty = TikiLib::lib('smarty');
             $smarty->loadPlugin('smarty_function_object_link');
             $ret = '<ol class="tracker-item-files">';
             foreach ($this->getConfiguration('files') as $fileId => $file) {
                 $ret .= '<li>';
                 $ret .= smarty_function_object_link(array('type' => 'file', 'id' => $fileId, 'title' => $file['name']), $smarty);
                 $globalperms = Perms::get(array('type' => 'file gallery', 'object' => $galleryId));
                 if ($prefs['feature_draw'] == 'y' && $globalperms->upload_files == 'y' && ($file['filetype'] == $mimetypes["svg"] || $file['filetype'] == $mimetypes["gif"] || $file['filetype'] == $mimetypes["jpg"] || $file['filetype'] == $mimetypes["png"] || $file['filetype'] == $mimetypes["tiff"])) {
                     $ret .= " <a href='tiki-edit_draw.php?fileId=" . $file['fileId'] . "' onclick='return \$(this).ajaxEditDraw();'  title='Edit: " . $file['name'] . "' data-fileid='" . $file['fileId'] . "' data-galleryid='" . $galleryId . "'>\n\t\t\t\t\t\t\t<img width='16' height='16' class='icon' alt='Edit' src='img/icons/page_edit.png' />\n\t\t\t\t\t\t</a>";
                 }
                 $ret .= '</li>';
             }
             $ret .= '</ol>';
         }
     }
     return $ret;
 }
Ejemplo n.º 5
0
         }
     }
     $smarty->assign('share_access', true);
     if (is_array($tokenlist)) {
         foreach ($tokenlist as $i => $data) {
             $query = parse_url($data);
             parse_str($query['query'], $query_vars);
             $detailtoken = $tokenlib->getToken($query_vars['TOKEN']);
             // Delete old user watch if it's necessary => avoid bad mails
             $tikilib->remove_user_watch_object('auth_token_called', $detailtoken['tokenId'], 'security');
             $tikilib->add_user_watch($user, 'auth_token_called', $detailtoken['tokenId'], 'security', tra('Token called'), $data);
         }
     }
 } else {
     if ($prefs['auth_token_share'] == 'y' && ($prefs['auth_token_access'] == 'y' || isset($_POST['share_access']))) {
         $tokenlib = AuthTokens::build($prefs);
         $url_for_friend = $tokenlib->includeToken($url_for_friend, $globalperms->getGroups(), $_REQUEST['addresses']);
         $smarty->assign('share_access', true);
     }
     $tokenlist[0] = $url_for_friend;
 }
 $smarty->assign_by_ref('email', $_REQUEST['email']);
 if (!empty($_REQUEST['addresses'])) {
     $smarty->assign('addresses', $_REQUEST['addresses']);
 }
 if (!empty($_REQUEST['name'])) {
     $smarty->assign('name', $_REQUEST['name']);
 }
 $emailSent = sendMail($_REQUEST['email'], $_REQUEST['addresses'], $subject, $tokenlist);
 $smarty->assign('emailSent', $emailSent);
 $ok = $ok && $emailSent;
Ejemplo n.º 6
0
 function testLimitOnAccessCount()
 {
     $lib = new AuthTokens($this->db, array('maxHits' => 10));
     $token = $lib->createToken('tiki-index.php', array('page' => 'HomePage'), array('Registered'), array('hits' => 3600));
     $this->assertEquals(10, $this->db->getOne('SELECT hits FROM tiki_auth_tokens WHERE tokenId = 1'));
 }
Ejemplo n.º 7
0
 private function RegisterSession(Users $vo_User, $b_ReturnAuthTokenAsString = false)
 {
     // Log the login.
     UserLoginLogDAO::save(new UserLoginLog(array('user_id' => $vo_User->user_id, 'ip' => ip2long($_SERVER['REMOTE_ADDR']))));
     // Expire the local session cache.
     self::$current_session = null;
     //find if this user has older sessions
     $vo_AuthT = new AuthTokens();
     $vo_AuthT->setUserId($vo_User->getUserId());
     //erase expired tokens
     try {
         $tokens_erased = AuthTokensDAO::expireAuthTokens($vo_User->getUserId());
     } catch (Exception $e) {
         // Best effort
         self::$log->error("Failed to delete expired tokens: {$e->getMessage}()");
     }
     // Create the new token
     $entropy = bin2hex(mcrypt_create_iv(SessionController::AUTH_TOKEN_ENTROPY_SIZE, MCRYPT_DEV_URANDOM));
     $s_AuthT = $entropy . '-' . $vo_User->getUserId() . '-' . hash('sha256', OMEGAUP_MD5_SALT . $vo_User->getUserId() . $entropy);
     $vo_AuthT = new AuthTokens();
     $vo_AuthT->setUserId($vo_User->getUserId());
     $vo_AuthT->setToken($s_AuthT);
     try {
         AuthTokensDAO::save($vo_AuthT);
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     if (self::$setCookieOnRegisterSession) {
         $sm = $this->getSessionManagerInstance();
         $sm->setCookie(OMEGAUP_AUTH_TOKEN_COOKIE_NAME, $s_AuthT, 0, '/');
     }
     Cache::deleteFromCache(Cache::SESSION_PREFIX, $s_AuthT);
     if ($b_ReturnAuthTokenAsString) {
         return $s_AuthT;
     }
 }
Ejemplo n.º 8
0
function wikiplugin_addtocart($data, $params)
{
    global $cartuserlist, $globalperms;
    $smarty = TikiLib::lib('smarty');
    $userlib = TikiLib::lib('user');
    $headerlib = TikiLib::lib('header');
    $cartlib = TikiLib::lib('cart');
    if (!session_id()) {
        session_start();
    }
    if (!isset($params['code'], $params['description'], $params['price'])) {
        return WikiParser_PluginOutput::argumentError(array_diff(array('code', 'description', 'price'), array_keys($params)));
    }
    $plugininfo = wikiplugin_addtocart_info();
    $default = array();
    foreach ($plugininfo['params'] as $key => $param) {
        $default["{$key}"] = $param['default'];
    }
    $params = array_merge($default, $params);
    // once forceanon is set it will have to affect the whole shopping cart otherwise it will be inconsistent
    if ($params['forceanon'] == 'y') {
        $_SESSION['forceanon'] = 'y';
    }
    foreach ($params as &$p) {
        $p = trim($p);
        // remove some line ends picked up in pretty tracker
    }
    $params['price'] = preg_replace('/[^\\d^\\.^,]/', '', $params['price']);
    $smarty->assign('params', $params);
    if ($params['onbehalf'] == 'y' && $globalperms->payment_admin) {
        $smarty->assign('onbehalf', 'y');
        // Do not load the user list unless it is needed, this light function is not as light as one would expect
        if (!isset($cartuserlist)) {
            $cartuserlist = $userlib->get_users_light();
        }
        $smarty->assign('cartuserlist', $cartuserlist);
    }
    if (!empty($params['exchangeorderitemid']) && !empty($params['exchangetoproductid'])) {
        $smarty->assign('hideamountfield', 'y');
    } else {
        $smarty->assign('hideamountfield', 'n');
    }
    if (is_numeric($params['productclass'])) {
        $information_form = $cartlib->get_missing_user_information_form($params['productclass'], 'required');
        $missing_information = $cartlib->get_missing_user_information_fields($params['productclass'], 'required');
        $skip_information_form = $cartlib->skip_user_information_form_if_not_missing($params['productclass']) && empty($missing_information);
        if ($information_form && !$skip_information_form) {
            $headerlib->add_jq_onready("\$('form.addProductToCartForm{$params['productclass']}')\n\t\t\t\t\t.cartProductClassMissingForm({\n\t\t\t\t\t\tinformationForm: '{$information_form}'\n\t\t\t\t\t});");
        }
    }
    if ($params['ajaxaddtocart'] == 'y') {
        $headerlib->add_jq_onready("\$('.wp_addtocart_form').cartAjaxAdd();");
        $smarty->assign('form_data', ' data-params=\'' . str_replace("'", "\\u0027", json_encode(array_filter($params))) . '\'');
    } else {
        $smarty->assign('form_data', '');
    }
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        global $jitPost, $user;
        $quantity = $jitPost->quantity->int();
        if ($jitPost->code->text() == $params['code'] && $quantity > 0) {
            $previous_cart_content = $cartlib->get_content();
            $addedOk = $cartlib->add_to_cart($params, $jitPost);
            global $tikiroot, $prefs;
            $access = TikiLib::lib('access');
            $tikilib = TikiLib::lib('tiki');
            if ($addedOk && $params['autocheckout'] == 'y' && empty($previous_cart_content)) {
                $invoice = $cartlib->request_payment();
                if ($invoice) {
                    $paymenturl = 'tiki-payment.php?invoice=' . intval($invoice);
                    $paymenturl = $tikilib->httpPrefix(true) . $tikiroot . $paymenturl;
                    if (!$user || $params['forceanon'] == 'y' && !Perms::get('payment', $invoice)->manual_payment) {
                        // token access needs to be an optional feature
                        // and needs to depend on auth_token_access pref
                        require_once 'lib/auth/tokens.php';
                        $tokenlib = AuthTokens::build($prefs);
                        $tokenpaymenturl = $tokenlib->includeToken($paymenturl, array('Temporary Shopper', 'Anonymous'));
                    }
                    if ($globalperms->payment_admin || Perms::get('payment', $invoice)->manual_payment) {
                        // if able to do manual payment it means it is admin and don't need token
                        $access->redirect($paymenturl, tr('The order was recorded and is now awaiting payment. Reference number is %0.', $invoice));
                    } else {
                        $access->redirect($tokenpaymenturl, tr('The order was recorded and is now awaiting payment. Reference number is %0.', $invoice));
                    }
                } else {
                    if (!empty($params['forwardafterfree'])) {
                        $access->redirect($params['forwardafterfree'], tr('Your free order of %0 (%1) has been processed. An email has been sent to you for your records.', $params['description'], $quantity));
                    } else {
                        $access->redirect($_SERVER['REQUEST_URI'], tr('Your free order of %0 (%1) has been processed', $params['description'], $quantity));
                    }
                }
                die;
            }
            $access->redirect($_SERVER['REQUEST_URI'], tr('%0 (%1) was added to your cart', $params['description'], $quantity));
        }
    }
    return $smarty->fetch('wiki-plugins/wikiplugin_addtocart.tpl');
}
Ejemplo n.º 9
0
 function request_payment()
 {
     global $prefs, $user;
     $tikilib = TikiLib::lib('tiki');
     $paymentlib = TikiLib::lib('payment');
     $total = $this->get_total();
     if ($total > 0 || $this->total_no_discount) {
         // if anonymous shopping to set pref as to which shopperinfo to show in description
         if (empty($user) && $prefs['payment_cart_anonymous'] === 'y') {
             $shopperinfo_descvar = 'email';
             // TODO: make this a pref
             if (!empty($_SESSION['shopperinfo'][$shopperinfo_descvar])) {
                 $shopperinfo_desc = $_SESSION['shopperinfo'][$shopperinfo_descvar];
                 $description = tra($prefs['payment_cart_heading']) . " ({$shopperinfo_desc})";
             } else {
                 $description = tra($prefs['payment_cart_heading']);
             }
         } else {
             $description = tra($prefs['payment_cart_heading']) . " ({$user})";
         }
         $invoice = $paymentlib->request_payment($description, $total, $prefs['payment_default_delay'], $this->get_description());
         foreach ($this->get_behaviors() as $behavior) {
             $paymentlib->register_behavior($invoice, $behavior['event'], $behavior['behavior'], $behavior['arguments']);
         }
     } else {
         $invoice = 0;
         foreach ($this->get_behaviors() as $behavior) {
             if ($behavior['event'] == 'complete') {
                 $name = $behavior['behavior'];
                 $file = dirname(__FILE__) . "/behavior/{$name}.php";
                 $function = 'payment_behavior_' . $name;
                 require_once $file;
                 call_user_func_array($function, $behavior['arguments']);
             }
         }
     }
     // Handle anonymous user (not logged in) shopping that require only email
     if (!$user || isset($_SESSION['forceanon']) && $_SESSION['forceanon'] == 'y') {
         if (!empty($_SESSION['shopperinfo'])) {
             // should also check for pref that this anonymous shopping feature is on
             // First create shopper info in shopper tracker
             global $record_profile_items_created;
             $record_profile_items_created = array();
             if (!empty($_SESSION['shopperinfoprofile'])) {
                 $shopper_profile_name = $_SESSION['shopperinfoprofile'];
             } else {
                 $shopper_profile_name = $prefs['payment_cart_anonshopper_profile'];
             }
             $shopperprofile = Tiki_Profile::fromDb($shopper_profile_name);
             $profileinstaller = new Tiki_Profile_Installer();
             $profileinstaller->forget($shopperprofile);
             // profile can be installed multiple times
             $profileinstaller->setUserData($_SESSION['shopperinfo']);
             $profileinstaller->install($shopperprofile);
             // Then set user to shopper ID
             $cartuser = $record_profile_items_created[0];
             $record_profile_items_created = array();
         } else {
             $this->empty_cart();
             return $invoice;
         }
     } else {
         $cartuser = $user;
     }
     $userInput = array('user' => $cartuser, 'time' => $tikilib->now, 'total' => $total, 'invoice' => $invoice, 'weight' => $this->get_total_weight());
     if (!$user || isset($_SESSION['forceanon']) && $_SESSION['forceanon'] == 'y') {
         $orderprofile = Tiki_Profile::fromDb($prefs['payment_cart_anonorders_profile']);
         $orderitemprofile = Tiki_Profile::fromDb($prefs['payment_cart_anonorderitems_profile']);
     } else {
         $orderprofile = Tiki_Profile::fromDb($prefs['payment_cart_orders_profile']);
         $orderitemprofile = Tiki_Profile::fromDb($prefs['payment_cart_orderitems_profile']);
     }
     if ($user && $prefs['payment_cart_orders'] == 'y' || !$user && $prefs['payment_cart_anonymous'] == 'y') {
         if (!$orderprofile) {
             TikiLib::lib('errorreport')->report(tra('Advanced Shopping Cart setup error: Orders profile missing.'));
             return false;
         }
         $profileinstaller = new Tiki_Profile_Installer();
         $profileinstaller->forget($orderprofile);
         // profile can be installed multiple times
         $profileinstaller->setUserData($userInput);
     } else {
         $profileinstaller = '';
     }
     global $record_profile_items_created;
     $record_profile_items_created = array();
     if ($user && $prefs['payment_cart_orders'] == 'y' || !$user && $prefs['payment_cart_anonymous'] == 'y') {
         $profileinstaller->install($orderprofile, 'none');
     }
     $content = $this->get_content();
     foreach ($content as $info) {
         if (!isset($info['is_gift_certificate']) || !$info['is_gift_certificate']) {
             $process_info = $this->process_item($invoice, $total, $info, $userInput, $cartuser, $profileinstaller, $orderitemprofile);
         }
     }
     $email_template_ids = array();
     if (isset($process_info['product_classes']) && is_array($process_info['product_classes'])) {
         $product_classes = array_unique($process_info['product_classes']);
     } else {
         $product_classes = array();
     }
     foreach ($product_classes as $pc) {
         if ($email_template_id = $this->get_tracker_value_custom($prefs['payment_cart_productclasses_tracker_name'], 'Email Template ID', $pc)) {
             $email_template_ids[] = $email_template_id;
         }
     }
     if (!empty($record_profile_items_created)) {
         if ($total > 0) {
             $paymentlib->register_behavior($invoice, 'complete', 'record_cart_order', array($record_profile_items_created));
             $paymentlib->register_behavior($invoice, 'cancel', 'cancel_cart_order', array($record_profile_items_created));
             if ($user) {
                 $paymentlib->register_behavior($invoice, 'complete', 'cart_send_confirm_email', array($user, $email_template_ids));
             }
         } else {
             require_once 'lib/payment/behavior/record_cart_order.php';
             payment_behavior_record_cart_order($record_profile_items_created);
             if ($user) {
                 require_once 'lib/payment/behavior/cart_send_confirm_email.php';
                 payment_behavior_cart_send_confirm_email($user, $email_template_ids);
             }
         }
     }
     if (!$user || isset($_SESSION['forceanon']) && $_SESSION['forceanon'] == 'y') {
         $shopperurl = 'tiki-index.php?page=' . $prefs['payment_cart_anon_reviewpage'] . '&shopper=' . intval($cartuser);
         global $tikiroot, $prefs;
         $shopperurl = $tikilib->httpPrefix(true) . $tikiroot . $shopperurl;
         require_once 'lib/auth/tokens.php';
         $tokenlib = AuthTokens::build($prefs);
         $shopperurl = $tokenlib->includeToken($shopperurl, array($prefs['payment_cart_anon_group'], 'Anonymous'));
         if (!empty($_SESSION['shopperinfo']['email'])) {
             require_once 'lib/webmail/tikimaillib.php';
             $smarty = TikiLib::lib('smarty');
             $smarty->assign('shopperurl', $shopperurl);
             $smarty->assign('email_template_ids', $email_template_ids);
             $mail_subject = $smarty->fetch('mail/cart_order_received_anon_subject.tpl');
             $mail_data = $smarty->fetch('mail/cart_order_received_anon.tpl');
             $mail = new TikiMail();
             $mail->setSubject($mail_subject);
             if ($mail_data == strip_tags($mail_data)) {
                 $mail->setText($mail_data);
             } else {
                 $mail->setHtml($mail_data);
             }
             $mail->send($_SESSION['shopperinfo']['email']);
             // the field to use probably needs to be configurable as well
         }
     }
     $this->update_gift_certificate($invoice);
     $this->update_group_discount($invoice);
     $this->empty_cart();
     return $invoice;
 }
Ejemplo n.º 10
0
 /**
  * This is a function to invite users to temporarily access the site via a token
  * @param array $emails Emails to send the invite to
  * @param array $groups Groups that the temporary user should have (Registered is not included unless explicitly added)
  * @param int $timeout How long the invitation is valid for, in seconds.
  * @param string $prefix Username of the created users will be the token ID prefixed with this
  * @param string $path Users will have to autologin using this path on the site using the token
  * @throws Exception
  */
 function invite_tempuser($emails, $groups, $timeout, $prefix = 'guest', $path = 'index.php')
 {
     global $smarty, $user, $prefs;
     include_once 'lib/webmail/tikimaillib.php';
     $mail = new TikiMail();
     foreach ($emails as $email) {
         if (!validate_email($email)) {
             throw new Exception(tr('Invalid email address "%0"', $email));
         }
     }
     $foo = parse_url($_SERVER['REQUEST_URI']);
     $machine = $this->httpPrefix(true) . dirname($foo['path']);
     $machine = preg_replace('!/$!', '', $machine);
     // just in case
     $smarty->assign_by_ref('mail_machine', $machine);
     $smarty->assign('mail_sender', $user);
     $smarty->assign('expiry', $user);
     $mail->setBcc($this->get_user_email($user));
     $smarty->assign('token_expiry', $this->get_long_datetime($this->now + $timeout));
     require_once 'lib/auth/tokens.php';
     foreach ($emails as $email) {
         $tokenlib = AuthTokens::build($prefs);
         $token_url = $tokenlib->includeToken($machine . "/{$path}", $groups, $email, $timeout, -1, true, $prefix);
         include_once 'tiki-sefurl.php';
         $token_url = filter_out_sefurl($token_url);
         $smarty->assign('token_url', $token_url);
         $mail->setUser($user);
         $mail->setSubject($smarty->fetch('mail/invite_tempuser_subject.tpl'));
         $mail->setHtml($smarty->fetch('mail/invite_tempuser.tpl'));
         if (!$mail->send($email)) {
             throw new Exception(tr('Unable to send mail to invite "%0"', $email));
         }
         $smarty->assign_by_ref('user', $user);
     }
 }
Ejemplo n.º 11
0
function wikiplugin_addtocart($data, $params)
{
    global $cartlib, $headerlib;
    require_once 'lib/payment/cartlib.php';
    $headerlib->add_jsfile('lib/payment/cartlib.js');
    if (!session_id()) {
        return WikiParser_PluginOutput::internalError(tra('A session must be active to use the cart.'));
    }
    if (!isset($params['code'], $params['description'], $params['price'])) {
        return WikiParser_PluginOutput::argumentError(array_diff(array('code', 'description', 'price'), array_keys($params)));
    }
    if (!isset($params['href'])) {
        $params['href'] = null;
    }
    if (!isset($params['label'])) {
        $params['label'] = tra('Add to cart');
    }
    if (!isset($params['forceanon'])) {
        $params['forceanon'] = 'n';
    }
    // once forceanon is set it will have to affect the whole shopping cart otherwise it will be inconsistent
    if ($params['forceanon'] == 'y') {
        $_SESSION['forceanon'] = 'y';
    }
    if (!isset($params['ajaxaddtocart'])) {
        $params['ajaxaddtocart'] = 'y';
    }
    foreach ($params as &$p) {
        $p = trim($p);
        // remove some line ends picked up in pretty tracker
    }
    $code = $params['code'];
    $product_class = $params['productclass'];
    $product_type = $params['producttype'];
    $product_bundle = $params['productbundle'];
    $bundle_class = $params['bundleclass'];
    $gift_certificate = $params['giftcertificate'];
    $eventcode = $params['eventcode'];
    $price = preg_replace('/[^\\d^\\.^,]/', '', $params['price']);
    $add_label = $params['label'];
    $ajax_add_to_cart = $params['ajaxaddtocart'];
    global $smarty;
    $smarty->assign('code', $code);
    $smarty->assign('productclass', $product_class);
    $smarty->assign('giftcertificate', $gift_certificate);
    $smarty->assign('price', $price);
    $smarty->assign('add_label', $add_label);
    global $cartuserlist, $userlib, $globalperms;
    if (!isset($cartuserlist)) {
        $cartuserlist = $userlib->get_users_light();
    }
    $smarty->assign('cartuserlist', $cartuserlist);
    if ($params['onbehalf'] == 'y' && $globalperms->payment_admin) {
        $smarty->assign('onbehalf', 'y');
    }
    if (!empty($params['exchangeorderitemid']) && !empty($params['exchangetoproductid'])) {
        $smarty->assign('exchangeorderitemid', $params['exchangeorderitemid']);
        $smarty->assign('exchangetoproductid', $params['exchangetoproductid']);
        $smarty->assign('hideamountfield', 'y');
    } else {
        $smarty->assign('hideamountfield', 'n');
    }
    if (is_numeric($product_class)) {
        $information_form = $cartlib->get_missing_user_information_form($product_class, 'required');
        $missing_information = $cartlib->get_missing_user_information_fields($product_class, 'required');
        $skip_information_form = $cartlib->skip_user_information_form_if_not_missing($product_class) && empty($missing_information);
        if ($information_form && !$skip_information_form) {
            $headerlib->add_jq_onready("\$('form.addProductToCartForm{$product_class}')\n\t\t\t\t\t.cartProductClassMissingForm({\n\t\t\t\t\t\tinformationForm: '{$information_form}'\n\t\t\t\t\t});");
        }
    }
    if ($ajax_add_to_cart == 'y') {
        $headerlib->add_jq_onready("\$('form.addProduct').cartAjaxAdd();");
    }
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        global $jitPost, $access, $user;
        if (!empty($params['exchangeorderitemid']) && !empty($params['exchangetoproductid'])) {
            if ($jitPost->exchangeorderitemid->int() == $params['exchangeorderitemid'] && $jitPost->exchangetoproductid->int() == $params['exchangetoproductid']) {
                $correct_exchange = true;
            } else {
                $correct_exchange = false;
            }
        } else {
            $correct_exchange = true;
        }
        $quantity = $jitPost->quantity->int();
        if ($jitPost->code->text() == $params['code'] && $quantity > 0 && $correct_exchange) {
            $behaviors = array();
            if ($prefs['payment_cart_anonymous'] === 'y' && (!$user || $params['forceanon'] == 'y') && empty($_SESSION['shopperinfo'])) {
                $access->redirect($_SERVER['REQUEST_URI'], tr('Please enter your shopper information first'));
            }
            // There needs to be a shopperinfo plugin on the page
            if ($globalperms->payment_admin && !empty($_POST['buyonbehalf']) && $userlib->user_exists($_POST['buyonbehalf'])) {
                $onbehalf = $_POST['buyonbehalf'];
            } else {
                $onbehalf = '';
            }
            $gift_certificate_error = tra("Invalid gift certificate: ");
            if ($_REQUEST['gift_certificate'] && isset($gift_certificate)) {
                if (!$cartlib->add_gift_certificate($_REQUEST['gift_certificate'])) {
                    $smarty->assign('gift_certificate', $_REQUEST['gift_certificate']);
                    $smarty->assign('gift_certificate_error', $gift_certificate_error);
                    return $smarty->fetch('wiki-plugins/wikiplugin_addtocart.tpl');
                    //TODO: Notify user if gift certificate is invalid
                }
            }
            $product_info = array('description' => $params['description'], 'price' => $price, 'href' => $params['href'], 'behaviors' => $behaviors, 'eventcode' => $eventcode, 'onbehalf' => $onbehalf, 'producttype' => $product_type, 'productclass' => $product_class, 'productbundle' => $product_bundle, 'bundleclass' => $bundle_class);
            // Generate behavior for exchanges
            if (!empty($params['exchangeorderitemid']) && !empty($params['exchangetoproductid'])) {
                $product_info['behaviors'][] = array('event' => 'complete', 'behavior' => 'cart_exchange_product', 'arguments' => array($params["exchangeorderitemid"], $params["exchangetoproductid"]));
                $product_info['exchangeorderitemid'] = $params["exchangeorderitemid"];
                $product_info['exchangetoproductid'] = $params["exchangetoproductid"];
                if (!isset($params['exchangeorderamount']) || !$params['exchangeorderamount']) {
                    $exchangeorderamount = 1;
                } else {
                    $exchangeorderamount = $params["exchangeorderamount"];
                }
                $product_info['exchangeorderamount'] = $exchangeorderamount;
            }
            // Generate behavior for gift certificate purchase
            if (strtolower($product_type) == 'gift certificate') {
                if ($onbehalf) {
                    $giftcert_email = $userlib->get_user_email($onbehalf);
                } elseif (!$user && !empty($_SESSION['shopperinfo']['email'])) {
                    $giftcert_email = $_SESSION['shopperinfo']['email'];
                } elseif ($user) {
                    $giftcert_email = $userlib->get_user_email($user);
                }
                $product_info['behaviors'][] = array('event' => 'complete', 'behavior' => 'cart_gift_certificate_purchase', 'arguments' => array($code, $giftcert_email));
            }
            // Now add product to cart
            $previous_cart_content = $cartlib->get_content();
            $cartlib->add_product($params['code'], $quantity, $product_info);
            global $access, $tikilib, $tikiroot, $prefs;
            if ($params['autocheckout'] == 'y' && empty($previous_cart_content)) {
                $invoice = $cartlib->request_payment();
                if ($invoice) {
                    $paymenturl = 'tiki-payment.php?invoice=' . intval($invoice);
                    $paymenturl = $tikilib->httpPrefix(true) . $tikiroot . $paymenturl;
                    if (!$user || $params['forceanon'] == 'y' && !Perms::get('payment', $invoice)->manual_payment) {
                        // token access needs to be an optional feature
                        // and needs to depend on auth_token_access pref
                        require_once 'lib/auth/tokens.php';
                        $tokenlib = AuthTokens::build($prefs);
                        $tokenpaymenturl = $tokenlib->includeToken($paymenturl, array('Temporary Shopper', 'Anonymous'));
                    }
                    if ($globalperms->payment_admin || Perms::get('payment', $invoice)->manual_payment) {
                        // if able to do manual payment it means it is admin and don't need token
                        $access->redirect($paymenturl, tr('The order was recorded and is now awaiting payment. Reference number is %0.', $invoice));
                    } else {
                        $access->redirect($tokenpaymenturl, tr('The order was recorded and is now awaiting payment. Reference number is %0.', $invoice));
                    }
                } else {
                    if (!empty($params['forwardafterfree'])) {
                        $access->redirect($params['forwardafterfree'], tr('Your free order of %0 (%1) has been processed. An email has been sent to you for your records.', $params['description'], $quantity));
                    } else {
                        $access->redirect($_SERVER['REQUEST_URI'], tr('Your free order of %0 (%1) has been processed', $params['description'], $quantity));
                    }
                }
                die;
            }
            $access->redirect($_SERVER['REQUEST_URI'], tr('%0 (%1) was added to your cart', $params['description'], $quantity));
        }
    }
    return $smarty->fetch('wiki-plugins/wikiplugin_addtocart.tpl');
}