/** * Verifies registration data from user. * * @param String $username Input username. * @param String $password Input password. * @param String $passwordRepeat Input repeated password. * @param String $name Input name. Can be empty. * @param String $contact Input contact. Can be empty. * * @throws RUsernameAndPasswordLengthException When $username length is less than 3 * AND $password length is less than 6. * @throws RPasswordLengthException When $password length is less than 6. * @throws RUsernameLengthException When $username length is less than 3. * @throws RPasswordMismatchException When $password and $passwordRepeat are * NOT equal. * @throws RUserExistsException When $username already exist in the database. * @throws RInvalidCharactersException When $username contains invalid characters. * * @return boolean True if registration is successful. */ public function verifyRegisterCredentials($username, $password, $passwordRepeat, $name, $contact) { if (strlen($username) < 3 && strlen($password) < 6) { throw new RUsernameAndPasswordLengthException(); } else { if (strlen($password) < 6) { throw new RPasswordLengthException(); } else { if (strlen($username) < 3) { throw new RUsernameLengthException(); } else { if ($password !== $passwordRepeat) { throw new RPasswordMismatchException(); } else { if ($this->dal->findUserByUsername($username)) { throw new RUserExistsException(); } else { if (preg_match("/^[0-9A-Za-z_]+\$/", $username) == 0) { throw new RInvalidCharactersException(); } else { $user = new User($username, $password); $infoJSON = '{"name": "' . $name . '", "contact": "' . $contact . '"}'; $user->setProfile($infoJSON); $this->dal->add($user); return true; } } } } } } }
/** * Create a new Order * * @param integer $productId productId * @param object $objUser \User object * @param string $transactionReference transactionReference * @param array $subscriptionOptions subscriptionOptions * * @return boolean * @throws OrderRepositoryException */ public function createOrder($productId, \Cx\Modules\Crm\Model\Entity\Currency $currency, \User $objUser, $transactionReference, $subscriptionOptions = array()) { if (\FWValidator::isEmpty($productId) || \FWValidator::isEmpty($subscriptionOptions) || \FWValidator::isEmpty($transactionReference) || \FWValidator::isEmpty($currency)) { return; } $contactId = $objUser->getCrmUserId(); if (\FWValidator::isEmpty($contactId)) { return; } try { $order = new \Cx\Modules\Order\Model\Entity\Order(); $order->setContactId($contactId); $order->setCurrency($currency); $productRepository = \Env::get('em')->getRepository('Cx\\Modules\\Pim\\Model\\Entity\\Product'); $product = $productRepository->findOneBy(array('id' => $productId)); //create subscription $subscription = $order->createSubscription($product, $subscriptionOptions); // set discount price for first payment period of subscription if (!empty($subscriptionOptions['oneTimeSalePrice'])) { $subscription->setPaymentAmount($subscriptionOptions['oneTimeSalePrice']); } $order->billSubscriptions(); $invoices = $order->getInvoices(); if (!empty($invoices)) { \DBG::msg(__METHOD__ . ": order has invoices"); $paymentRepo = \Env::get('em')->getRepository('\\Cx\\Modules\\Order\\Model\\Entity\\Payment'); foreach ($invoices as $invoice) { if (!$invoice->getPaid()) { \DBG::msg(__METHOD__ . ": lookup payment with transaction-reference {$transactionReference} and amount " . $invoice->getAmount()); $payment = $paymentRepo->findOneByCriteria(array('amount' => $invoice->getAmount(), 'transactionReference' => $transactionReference, 'invoice' => null)); if ($payment) { \DBG::msg(__METHOD__ . ": payment found"); //set subscription-id to Subscription::$externalSubscriptionId if ($subscription) { \DBG::msg(__METHOD__ . ": trying to link to new subscription to the external subscription ID"); $referenceArry = explode('|', $payment->getTransactionReference()); if (isset($referenceArry[4]) && !empty($referenceArry[4])) { $subscription->setExternalSubscriptionId($referenceArry[4]); } } $transactionData = $payment->getTransactionData(); if (!\FWValidator::isEmpty($transactionData) && isset($transactionData['contact']) && isset($transactionData['contact']['id'])) { \DBG::msg(__METHOD__ . ": set externalPaymentCustomerIdProfileAttributeId of user to " . $transactionData['contact']['id']); $objUser->setProfile(array(\Cx\Core\Setting\Controller\Setting::getValue('externalPaymentCustomerIdProfileAttributeId', 'MultiSite') => array(0 => $transactionData['contact']['id'])), true); if (!$objUser->store()) { \DBG::msg('Order::createOrder() Updating user failed: ' . $objUser->getErrorMsg()); } } $invoice->addPayment($payment); $payment->setInvoice($invoice); \Env::get('em')->persist($invoice); \Env::get('em')->persist($payment); break; } } } } \Env::get('em')->persist($order); \Env::get('em')->flush(); return $order; } catch (\Exception $e) { throw new OrderRepositoryException($e->getMessage()); } }
} if (sizeof($ERRORS) > 0) { draw_errors($ERRORS); } else { // Create an user and set some base attrs. $new_user = new User($db); $new_user->setUserName($USER['user_name']); $new_user->setRegisteredIpAddr($_SERVER['REMOTE_ADDR']); $new_user->setPassword($USER['password']); $new_user->setCurrentSaltExpiration($new_user->sysdate()); $new_user->setLastActivity($new_user->sysdate()); $new_user->setAccessLevel('user'); $new_user->setEmail($USER['email']); $new_user->setAge($USER['age']); $new_user->setGender($USER['gender']); $new_user->setProfile($USER['profile']); $new_user->setCurrency($APP_CONFIG['starting_funds']); $new_user->setUserTitle('User'); $new_user->setTextareaPreference('tinymce'); $new_user->setDatetimeCreated($new_user->sysdate()); $new_user->setDatetimeLastPost($new_user->sysdate()); $new_user->setPasswordResetRequested($new_user->sysdate()); $new_user->setTimezoneId(54); // 54 = UTC $new_user->setDatetimeFormatId(1); // Y-m-d H:i:s $new_user->setShowOnlineStatus('Y'); $new_user->save(); // Log the user in and send him back home. $new_user->login(); redirect('home');
/** * Searchs for an user with the given user id of the social media platform. * If there is no user, create one and directly log in. * * @param string $oauth_id the user id of the social media platform * @return bool * @throws OAuth_Exception */ protected function getContrexxUser($oauth_id) { global $sessionObj; //\DBG::activate(); $arrSettings = \User_Setting::getSettings(); $provider = $this::OAUTH_PROVIDER; $FWUser = \FWUser::getFWUserObject(); $objUser = $FWUser->objUser->getByNetwork($provider, $oauth_id); if (!$objUser) { // check whether the user is already logged in // if the user is logged in just add a new network to the user object if ($FWUser->objUser->login()) { $objUser = $FWUser->objUser; $this->addProviderToUserObject($provider, $oauth_id, $objUser); $objUser->getNetworks()->save(); return true; } // create a new user with the default profile attributes $objUser = new \User(); $objUser->setEmail($this->getEmail()); $objUser->setAdminStatus(0); $objUser->setProfile(array('firstname' => array($this->getFirstname()), 'lastname' => array($this->getLastname()))); $registrationRedirectNeeded = $arrSettings['sociallogin_show_signup']['status']; // if user_account_verification is true (1), then we need to do checkMandatoryCompliance(), because // the required fields must be set. if ($registrationRedirectNeeded == false && $arrSettings['user_account_verification']['value'] === 1) { $registrationRedirectNeeded = !$objUser->checkMandatoryCompliance(); } $objUser->setActiveStatus(!$registrationRedirectNeeded); if ($registrationRedirectNeeded) { $objUser->setRestoreKey(); $objUser->setRestoreKeyTime(intval($arrSettings['sociallogin_activation_timeout']['value']) * 60); } if (!empty($arrSettings['sociallogin_assign_to_groups']['value'])) { $groups = $arrSettings['sociallogin_assign_to_groups']['value']; } else { $groups = $arrSettings['assigne_to_groups']['value']; } $objUser->setGroups(explode(',', $groups)); // if we can create the user without sign up page if (!$objUser->store()) { // if the email address already exists but not with the given oauth-provider throw new OAuth_Exception(); } // add the social network to user $this->addProviderToUserObject($provider, $oauth_id, $objUser); $objUser->getNetworks()->save(); // check whether there are empty mandatory fields or the setting to show sign up everytime if ($registrationRedirectNeeded) { // start session if no session is open if (!isset($sessionObj) || !is_object($sessionObj)) { $sessionObj = \cmsSession::getInstance(); } // write the user id to session so we can pre-fill the sign up form $_SESSION['user_id'] = $objUser->getId(); // generate url for sign up page and redirect $signUpPageUri = \Cx\Core\Routing\Url::fromModuleAndCmd('Access', 'signup'); \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $signUpPageUri->__toString()); exit; } } $FWUser->loginUser($objUser); }
/** * Returns an array with all placeholders and their values to be * replaced in any shop mailtemplate for the given order ID. * * You only have to set the 'substitution' index value of your MailTemplate * array to the array returned. * Customer data is not included here. See {@see Customer::getSubstitutionArray()}. * Note that this method is now mostly independent of the current session. * The language of the mail template is determined by the browser * language range stored with the order. * @access private * @static * @param integer $order_id The order ID * @param boolean $create_accounts If true, creates User accounts * and Coupon codes. Defaults to true * @return array The array with placeholders as keys * and values from the order on success, * false otherwise */ static function getSubstitutionArray($order_id, $create_accounts = true) { global $_ARRAYLANG; /* $_ARRAYLANG['TXT_SHOP_URI_FOR_DOWNLOAD'].":\r\n". 'http://'.$_SERVER['SERVER_NAME']. "/index.php?section=download\r\n"; */ $objOrder = Order::getById($order_id); if (!$objOrder) { // Order not found return false; } $lang_id = $objOrder->lang_id(); if (!intval($lang_id)) { $lang_id = \FWLanguage::getLangIdByIso639_1($lang_id); } $status = $objOrder->status(); $customer_id = $objOrder->customer_id(); $customer = Customer::getById($customer_id); $payment_id = $objOrder->payment_id(); $shipment_id = $objOrder->shipment_id(); $arrSubstitution = array('CUSTOMER_COUNTRY_ID' => $objOrder->billing_country_id(), 'LANG_ID' => $lang_id, 'NOW' => date(ASCMS_DATE_FORMAT_DATETIME), 'TODAY' => date(ASCMS_DATE_FORMAT_DATE), 'ORDER_ID' => $order_id, 'ORDER_ID_CUSTOM' => ShopLibrary::getCustomOrderId($order_id), 'ORDER_DATE' => date(ASCMS_DATE_FORMAT_DATE, strtotime($objOrder->date_time())), 'ORDER_TIME' => date(ASCMS_DATE_FORMAT_TIME, strtotime($objOrder->date_time())), 'ORDER_STATUS_ID' => $status, 'ORDER_STATUS' => $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $status], 'MODIFIED' => date(ASCMS_DATE_FORMAT_DATETIME, strtotime($objOrder->modified_on())), 'REMARKS' => $objOrder->note(), 'ORDER_SUM' => sprintf('% 9.2f', $objOrder->sum()), 'CURRENCY' => Currency::getCodeById($objOrder->currency_id())); $arrSubstitution += $customer->getSubstitutionArray(); if ($shipment_id) { $arrSubstitution += array('SHIPMENT' => array(0 => array('SHIPMENT_NAME' => sprintf('%-40s', Shipment::getShipperName($shipment_id)), 'SHIPMENT_PRICE' => sprintf('% 9.2f', $objOrder->shipment_amount()))), 'SHIPPING_ADDRESS' => array(0 => array('SHIPPING_COMPANY' => $objOrder->company(), 'SHIPPING_TITLE' => $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHIPPING_FIRSTNAME' => $objOrder->firstname(), 'SHIPPING_LASTNAME' => $objOrder->lastname(), 'SHIPPING_ADDRESS' => $objOrder->address(), 'SHIPPING_ZIP' => $objOrder->zip(), 'SHIPPING_CITY' => $objOrder->city(), 'SHIPPING_COUNTRY_ID' => $objOrder->country_id(), 'SHIPPING_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHIPPING_PHONE' => $objOrder->phone()))); } if ($payment_id) { $arrSubstitution += array('PAYMENT' => array(0 => array('PAYMENT_NAME' => sprintf('%-40s', Payment::getNameById($payment_id)), 'PAYMENT_PRICE' => sprintf('% 9.2f', $objOrder->payment_amount())))); } $arrItems = $objOrder->getItems(); if (!$arrItems) { \Message::warning($_ARRAYLANG['TXT_SHOP_ORDER_WARNING_NO_ITEM']); } // Deduct Coupon discounts, either from each Product price, or // from the items total. Mind that the Coupon has already been // stored with the Order, but not redeemed yet. This is done // in this method, but only if $create_accounts is true. $coupon_code = NULL; $coupon_amount = 0; $objCoupon = Coupon::getByOrderId($order_id); if ($objCoupon) { $coupon_code = $objCoupon->code(); } $orderItemCount = 0; $total_item_price = 0; // Suppress Coupon messages (see Coupon::available()) \Message::save(); foreach ($arrItems as $item) { $product_id = $item['product_id']; $objProduct = Product::getById($product_id); if (!$objProduct) { //die("Product ID $product_id not found"); continue; } //DBG::log("Orders::getSubstitutionArray(): Item: Product ID $product_id"); $product_name = substr($item['name'], 0, 40); $item_price = $item['price']; $quantity = $item['quantity']; // TODO: Add individual VAT rates for Products // $orderItemVatPercent = $objResultItem->fields['vat_percent']; // Decrease the Product stock count, // applies to "real", shipped goods only $objProduct->decreaseStock($quantity); $product_code = $objProduct->code(); // Pick the order items attributes $str_options = ''; // Any attributes? if ($item['attributes']) { $str_options = ' '; // '['; $attribute_name_previous = ''; foreach ($item['attributes'] as $attribute_name => $arrAttribute) { //DBG::log("Attribute /$attribute_name/ => ".var_export($arrAttribute, true)); // NOTE: The option price is optional and may be left out foreach ($arrAttribute as $arrOption) { $option_name = $arrOption['name']; $option_price = $arrOption['price']; $item_price += $option_price; // Recognize the names of uploaded files, // verify their presence and use the original name $option_name_stripped = ShopLibrary::stripUniqidFromFilename($option_name); $path = Order::UPLOAD_FOLDER . $option_name; if ($option_name != $option_name_stripped && \File::exists($path)) { $option_name = $option_name_stripped; } if ($attribute_name != $attribute_name_previous) { if ($attribute_name_previous) { $str_options .= '; '; } $str_options .= $attribute_name . ': ' . $option_name; $attribute_name_previous = $attribute_name; } else { $str_options .= ', ' . $option_name; } // TODO: Add proper formatting with sprintf() and language entries if ($option_price != 0) { $str_options .= ' ' . Currency::formatPrice($option_price) . ' ' . Currency::getActiveCurrencyCode(); } } } // $str_options .= ']'; } // Product details $arrProduct = array('PRODUCT_ID' => $product_id, 'PRODUCT_CODE' => $product_code, 'PRODUCT_QUANTITY' => $quantity, 'PRODUCT_TITLE' => $product_name, 'PRODUCT_OPTIONS' => $str_options, 'PRODUCT_ITEM_PRICE' => sprintf('% 9.2f', $item_price), 'PRODUCT_TOTAL_PRICE' => sprintf('% 9.2f', $item_price * $quantity)); //DBG::log("Orders::getSubstitutionArray($order_id, $create_accounts): Adding article: ".var_export($arrProduct, true)); $orderItemCount += $quantity; $total_item_price += $item_price * $quantity; if ($create_accounts) { // Add an account for every single instance of every Product for ($instance = 1; $instance <= $quantity; ++$instance) { $validity = 0; // Default to unlimited validity // In case there are protected downloads in the cart, // collect the group IDs $arrUsergroupId = array(); if ($objProduct->distribution() == 'download') { $usergroupIds = $objProduct->usergroup_ids(); if ($usergroupIds != '') { $arrUsergroupId = explode(',', $usergroupIds); $validity = $objProduct->weight(); } } // create an account that belongs to all collected // user groups, if any. if (count($arrUsergroupId) > 0) { // The login names are created separately for // each product instance $username = self::usernamePrefix . "_{$order_id}_{$product_id}_{$instance}"; $userEmail = $username . '-' . $arrSubstitution['CUSTOMER_EMAIL']; $userpass = \User::make_password(); $objUser = new \User(); $objUser->setUsername($username); $objUser->setPassword($userpass); $objUser->setEmail($userEmail); $objUser->setAdminStatus(false); $objUser->setActiveStatus(true); $objUser->setGroups($arrUsergroupId); $objUser->setValidityTimePeriod($validity); $objUser->setFrontendLanguage(FRONTEND_LANG_ID); $objUser->setBackendLanguage(FRONTEND_LANG_ID); $objUser->setProfile(array('firstname' => array(0 => $arrSubstitution['CUSTOMER_FIRSTNAME']), 'lastname' => array(0 => $arrSubstitution['CUSTOMER_LASTNAME']), 'company' => array(0 => $arrSubstitution['CUSTOMER_COMPANY']), 'address' => array(0 => $arrSubstitution['CUSTOMER_ADDRESS']), 'zip' => array(0 => $arrSubstitution['CUSTOMER_ZIP']), 'city' => array(0 => $arrSubstitution['CUSTOMER_CITY']), 'country' => array(0 => $arrSubstitution['CUSTOMER_COUNTRY_ID']), 'phone_office' => array(0 => $arrSubstitution['CUSTOMER_PHONE']), 'phone_fax' => array(0 => $arrSubstitution['CUSTOMER_FAX']))); if (!$objUser->store()) { \Message::error(implode('<br />', $objUser->getErrorMsg())); return false; } if (empty($arrProduct['USER_DATA'])) { $arrProduct['USER_DATA'] = array(); } $arrProduct['USER_DATA'][] = array('USER_NAME' => $username, 'USER_PASS' => $userpass); } //echo("Instance $instance"); if ($objProduct->distribution() == 'coupon') { if (empty($arrProduct['COUPON_DATA'])) { $arrProduct['COUPON_DATA'] = array(); } //DBG::log("Orders::getSubstitutionArray(): Getting code"); $code = Coupon::getNewCode(); //DBG::log("Orders::getSubstitutionArray(): Got code: $code, calling Coupon::addCode($code, 0, 0, 0, $item_price)"); Coupon::storeCode($code, 0, 0, 0, $item_price, 0, 0, 10000000000.0, true); $arrProduct['COUPON_DATA'][] = array('COUPON_CODE' => $code); } } // Redeem the *product* Coupon, if possible for the Product if ($coupon_code) { $objCoupon = Coupon::available($coupon_code, $item_price * $quantity, $customer_id, $product_id, $payment_id); if ($objCoupon) { $coupon_code = NULL; $coupon_amount = $objCoupon->getDiscountAmount($item_price, $customer_id); if ($create_accounts) { $objCoupon->redeem($order_id, $customer_id, $item_price * $quantity); } } //\DBG::log("Orders::getSubstitutionArray(): Got Product Coupon $coupon_code"); } } if (empty($arrSubstitution['ORDER_ITEM'])) { $arrSubstitution['ORDER_ITEM'] = array(); } $arrSubstitution['ORDER_ITEM'][] = $arrProduct; } $arrSubstitution['ORDER_ITEM_SUM'] = sprintf('% 9.2f', $total_item_price); $arrSubstitution['ORDER_ITEM_COUNT'] = sprintf('% 4u', $orderItemCount); // Redeem the *global* Coupon, if possible for the Order if ($coupon_code) { $objCoupon = Coupon::available($coupon_code, $total_item_price, $customer_id, null, $payment_id); if ($objCoupon) { $coupon_amount = $objCoupon->getDiscountAmount($total_item_price, $customer_id); if ($create_accounts) { $objCoupon->redeem($order_id, $customer_id, $total_item_price); } } } \Message::restore(); // Fill in the Coupon block with proper discount and amount if ($objCoupon) { $coupon_code = $objCoupon->code(); //\DBG::log("Orders::getSubstitutionArray(): Coupon $coupon_code, amount $coupon_amount"); } if ($coupon_amount) { //\DBG::log("Orders::getSubstitutionArray(): Got Order Coupon $coupon_code"); $arrSubstitution['DISCOUNT_COUPON'][] = array('DISCOUNT_COUPON_CODE' => sprintf('%-40s', $coupon_code), 'DISCOUNT_COUPON_AMOUNT' => sprintf('% 9.2f', -$coupon_amount)); } else { //\DBG::log("Orders::getSubstitutionArray(): No Coupon for Order ID $order_id"); } Products::deactivate_soldout(); if (Vat::isEnabled()) { //DBG::log("Orders::getSubstitutionArray(): VAT amount: ".$objOrder->vat_amount()); $arrSubstitution['VAT'] = array(0 => array('VAT_TEXT' => sprintf('%-40s', Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL']), 'VAT_PRICE' => $objOrder->vat_amount())); } return $arrSubstitution; }
/** * Import Users from a CSV file * * Sets up common User and Profile fields as well as * Newsletter list relations. * Fields and their mapping: * Anrede -> Titel * Vorname * Name * eMail * Firma * Strasse -> Zusammen mit Hausnummer in Adresse * Hausnummer -> Zusammen mit Strasse in Adresse * PLZ * Ort * Land * Bundesland -> Evtl in Ort? * Tel.-Vorwahl -> Zusammen mit Tel.-Nummer in phone_office * Tel.-Nummer -> Zusammen mit Tel.-Vorwahl in phone_office * Fax-Vorwahl -> Zusammen mit Fax.-Nummer in phone_fax * Fax-Nummer -> Zusammen mit Fax.-Vorwahl in phone_fax * Mobil-Vorwahl -> Zusammen mit Mobil-Nummer in phone_mobile * Mobil-Nummer -> Zusammen mit Mobil-Vorwahl in phone_mobile * P1 -> Interessen: Newsletter Listen, kommagetrennt * -> Nicht vorhandene Listen werden angelegt * P2 -> Antwort: ? * P3 -> ? * P4 -> Titel: ? * P5 -> ? * Ursprungsformular -> ? * Permission -> ? * Ausgetragen -> Wenn true, alle Listenzuordnungen entfernen, sonst fehlende anlegen * Anzahl Hard-Bounces -> Nicht vorhanden? * Status -> Bedeutung? * Sprache -> Wird die verwendet? * ID -> Bedeutung? * Eintragungsdatum -> regdate * Aenderungsdatum -> ? (Nur regdate) * Austragungsdatum -> ? (Nur regdate) * @param string $file_name The CSV file name */ static function import_csv($file_name) { global $_ARRAYLANG; \Env::get('ClassLoader')->loadFile(ASCMS_LIBRARY_PATH . '/importexport/lib/csv.class.php'); //DBG::activate(DBG_ADODB_ERROR|DBG_LOG_FIREPHP|DBG_PHP); $objUser = \FWUser::getFWUserObject()->objUser; $objCsv = new \CsvLib(); $arrCsv = $objCsv->parse($file_name); // $arrFields = $arrCsv['fieldnames']; $arrUsers = $arrCsv['data']; //DBG::log("Found ".count($arrUsers)." Users in the CSV file"); foreach ($arrUsers as $arrUser) { //echo(var_export($arrUser, true)."<br />");// var_export($objUser, true)."<hr />" $email = $arrUser['3']; //DBG::log("Found e-mail $email"); if (!\FWValidator::isEmail($email)) { self::$arrStatusMsg['error'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $email, $_ARRAYLANG['TXT_ACCESS_IMPORT_ERROR_INVALID_EMAIL']); continue; } // TODO: I suppose that the imported file is ISO-8859-1 or so $title = utf8_encode($arrUser[0]); $gender = preg_match('//', $title) ? 'gender_male' : 'gender_female'; $firstname = utf8_encode($arrUser[1]); $lastname = utf8_encode($arrUser[2]); $company = utf8_encode($arrUser[4]); $address = utf8_encode($arrUser[5]) . ' ' . utf8_encode($arrUser[6]); $zip = utf8_encode($arrUser[7]); $city = utf8_encode($arrUser[8]); $country = utf8_encode($arrUser[9]); $state = utf8_encode($arrUser[10]); if ($state) { $city .= ", {$state}"; } $phone_office = utf8_encode($arrUser[11]) . ' ' . utf8_encode($arrUser[12]); $phone_fax = utf8_encode($arrUser[13]) . ' ' . utf8_encode($arrUser[14]); $phone_mobile = utf8_encode($arrUser[15]) . ' ' . utf8_encode($arrUser[16]); $p1_lists = utf8_encode($arrUser[17]); $unsubscribed = utf8_encode($arrUser[24]); $language = utf8_encode($arrUser[27]); // These are all unused for the time being // $p2_answer = $arrUser[18]; // $p3 = $arrUser[19]; // $p4_title = $arrUser[20]; // $p5 = $arrUser[21]; // $source = $arrUser[22]; // $permission = $arrUser[23]; // $bounces = $arrUser[25]; // $status = $arrUser[26]; // $id = $arrUser[28]; // $date_subscribed = $arrUser[29]; // $date_changed = $arrUser[30]; // $date_unsubscribe = $arrUser[31]; $objUser = new \User(); $objUser = $objUser->getUsers(array('email' => array($email))); $new_user = false; if (!$objUser) { $new_user = true; $objUser = new \User(); $objUser->setUsername(\User::makeUsername($lastname, $firstname)); $objUser->setPassword(\User::makePassword()); $objUser->setEmail($email); } // TODO: Make new Users active or inactive? // $objUser->setActiveStatus(0); // $objUser->setAdminStatus(0); $lang_id = \FWLanguage::getLanguageIdByCode($language); $objUser->setFrontendLanguage($lang_id); $objUser->setBackendLanguage($lang_id); $objUser->setProfile(array('gender' => array($gender), 'title' => array($title), 'firstname' => array($firstname), 'lastname' => array($lastname), 'company' => array($company), 'address' => array($address), 'city' => array($city), 'zip' => array($zip), 'country' => array($country), 'phone_office' => array($phone_office), 'phone_mobile' => array($phone_mobile), 'phone_fax' => array($phone_fax))); $arrLists = preg_split('/\\s*,\\s*/', $p1_lists, null, PREG_SPLIT_NO_EMPTY); $arrListId = array(); if (preg_match('/false/i', $unsubscribed)) { // User has not unsubscribed (yet), collect the List IDs foreach ($arrLists as $list_name) { $list_id = \Cx\Modules\Newsletter\Controller\NewsletterLib::getListIdByName($list_name); //DBG::log("List '$list_name' => ID $list_id"); if (!$list_id) { // TODO: Shall I do this? $list_id = \Cx\Modules\Newsletter\Controller\NewsletterLib::_addList(addslashes($list_name)); self::$arrStatusMsg['ok'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $list_name, $_ARRAYLANG['TXT_ACCESS_IMPORT_SUCCESS_LIST_CREATED']); } $arrListId[$list_id] = $list_id; } } $objUser->setNewsletterCategories($arrListId); if ($objUser->store()) { self::$arrStatusMsg['ok'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $email, $new_user ? $_ARRAYLANG['TXT_ACCESS_IMPORT_SUCCESS_USER_CREATED'] : $_ARRAYLANG['TXT_ACCESS_IMPORT_SUCCESS_USER_UPDATED']); } else { self::$arrStatusMsg['error'][] = sprintf($_ARRAYLANG['TXT_ACCESS_IMPORT_MESSAGE_TEMPLATE'], $email, $_ARRAYLANG['TXT_ACCESS_IMPORT_ERROR_CREATING_USER']); } } }
/** * Search for a user in the database, and users with similar names. * * @param String $username The search term. * @return \model\User | array User if match has been found, * else an array of users with similar names. */ public function searchForUser($username) { $searchResult = array(); $sqli = $this->database->connect(); $stmt = $sqli->prepare("SELECT * FROM " . $this->table . " WHERE " . $this->usernameCol . " LIKE '%" . $username . "%'"); if ($stmt === false) { throw new Exception($sqli->error); } $stmt->execute(); $stmt->bind_result($dbUsername, $dbPassword, $dbProfileInfo); while ($stmt->fetch()) { if ($username === $dbUsername) { $user = new User($dbUsername, $dbPassword); $user->setProfile($dbProfileInfo); return $user; } else { $user = new User($dbUsername, $dbPassword); $user->setProfile($dbProfileInfo); $searchResult[] = $user; } } return $searchResult; }
$utente = $res_user->fetch_assoc(); $gid = split(",", $utente['gruppi']); $user = new User($utente['uid'], $utente['nome'], $utente['cognome'], $gid, $utente['permessi']); /** * profile */ $sel_profile = "SELECT * FROM profili WHERE id = " . $user->getUid(); try { $res_profile = $db->executeQuery($sel_profile); } catch (MySQLException $ex) { print "ko;" . $ex->getMessage(); exit; } if ($res_profile->num_rows) { $profile = $res_profile->fetch_assoc(); $user->setProfile($profile); } /** * subjects and classes : only for teachers */ if ($user->isTeacher()) { $sel_subject = "SELECT materia FROM docenti WHERE id_docente = " . $user->getUid(); try { $res_materia = $db->executeQuery($sel_subject); } catch (MySQLException $ex) { print "ko;" . $ex->getMessage(); exit; } $materia = $res_materia->fetch_assoc(); $user->setSubject($materia['materia']); /**